From c8651eb3141f63765f426b2686c85550bbddb507 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 06:59:44 +0000 Subject: [PATCH 01/10] Resolve engine identities without principal-store registration --- .../src/kumo_core/sources/principals.py | 23 ++- .../kumo/engine/connector/identity.py | 72 +------ .../engine/integrations/_mlflow_target.py | 4 +- packages/kumo-engine/test/test_identity.py | 178 +++++++----------- 4 files changed, 97 insertions(+), 180 deletions(-) diff --git a/packages/kumo-core/src/kumo_core/sources/principals.py b/packages/kumo-core/src/kumo_core/sources/principals.py index 63b4223db..008933485 100644 --- a/packages/kumo-core/src/kumo_core/sources/principals.py +++ b/packages/kumo-core/src/kumo_core/sources/principals.py @@ -27,6 +27,7 @@ ) __all__ = [ + "DirectIdentity", "IdentityRef", "Named", "Principal", @@ -52,12 +53,6 @@ def slug(self) -> str: ... -#: Anything that names an identity: the object the SDK handed back, the ID a -#: bound connector recorded, the slug, or the display name it was created -#: under. All four resolve to one store name. -IdentityRef = Union[str, Named] - - def identity_id(name: str) -> str: r"""Derives the ID of an identity created in this process. @@ -102,6 +97,20 @@ def type(self) -> IdentityType: return self.config.type +@runtime_checkable +class DirectIdentity(Protocol): + """An identity carrying its connection principal without store lookup.""" + + @property + def principal(self) -> Principal: + """Return configuration and credentials for a fresh local session.""" + ... + + +#: A self-contained principal or a legacy object, ID, slug, or store name. +IdentityRef = Union[str, Named, DirectIdentity] + + @dataclass(frozen=True) class Registration: r"""One identity as the store holds it: a principal, and how it is named. @@ -299,6 +308,8 @@ def resolve( """ named = [reference for reference in candidates if reference] for reference in named: + if isinstance(reference, DirectIdentity): + return reference.principal name = store.resolve(reference) if name is not None: return store.get(name) diff --git a/packages/kumo-engine/kumo/engine/connector/identity.py b/packages/kumo-engine/kumo/engine/connector/identity.py index 816dbbc90..e502eac79 100644 --- a/packages/kumo-engine/kumo/engine/connector/identity.py +++ b/packages/kumo-engine/kumo/engine/connector/identity.py @@ -1,54 +1,20 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -r"""Identity objects: pass credentials directly, not by reference. - -`kumo_core.sources.principals.SourceBackend`/`Sessions` classes resolve -identity through `kumo_core`'s own process-wide `PrincipalStore`, addressed by -name (`kumo_core.sources.principals.IdentityRef = Union[str, Named]`). That's -a registry, and a caller who wants to pass credentials directly would -otherwise have to register them under a name first and then pass the name -- -exactly the indirection this package avoids elsewhere. - -`Identity` (and its five per-provider subclasses below) hides that: a caller -builds e.g. `SnowflakeIdentity(account=..., username=..., password=...)` and -passes it straight to `SnowflakeConnector(identity=...)`. Construction -registers the identity into `kumo_core`'s store under a random slug and the -object exposes that slug (`Named.slug`), so from `kumo_core`'s point of view -it's still going through `PrincipalStore` -- credentials still live only in -that process-local store, never copied elsewhere -- but the caller never -sees the "register, then reference by name" two-step. - -The slug is a random per-registration key, not derived from `config`/ -`credentials` in any way: a slug computed from credential content, even -hashed, would be a deterministic, externally-visible function of a -(frequently low-entropy) secret -- logged or otherwise leaked, it becomes -an offline verifier an attacker can check a guessed credential against, -for a connection configuration that's often already known. A random slug -has none of that risk, at the cost of two `Identity`s built from -identical config/credentials no longer coalescing into one store entry -- -each `Identity()` call is its own registration, which is fine here: -nothing in this package looks two `Identity` objects up by whether they -happen to share credentials, and `PrincipalStore` is a process-local, -per-run registry, not a durable one two separate `Identity()` calls need -to agree on. - -Config/credential dataclasses (`SnowflakeIdentityConfig`, -`SnowflakePasswordCredentials`, ...) are reused unchanged from -`kumoapi.data_source` -- the same pure, wire-format dataclasses the cloud SDK -uses, including their validation (`validate_identity_credentials_match`, -per-field normalization). +"""Self-contained provider identities with random, credential-independent slugs. + +Explicit credentials travel with identities when pickled. Ambient authentication +and referenced token files are resolved independently on each worker. """ import uuid from typing import Optional -from kumo_core.sources.principals import store +from kumo_core.sources.principals import Principal from kumoapi.data_source import ( ADLSIdentityConfig, AzureCloud, BigQueryIdentityConfig, - CreateIdentityArgs, DatabricksAuthenticationKind, DatabricksIdentityConfig, DatabricksOAuthCredentials, @@ -92,30 +58,12 @@ def __init__( validate_identity_credentials_match(config, credentials) self._config = config self._credentials = credentials - # A random key, not derived from config/credentials at all -- see - # the module docstring for why. `uuid4().hex` is 32 lowercase hex - # characters, comfortably inside the slug format (kumoapi. - # data_source's validate_resource_slug: 3-48 lowercase ASCII - # letters/digits/hyphens, starting with a letter, ending with a - # letter or digit). self._slug = "identity-" + uuid.uuid4().hex - # Always a fresh name in practice (birthday collision on a random - # 128-bit value) -- but unlike the earlier credential-derived slug, - # a collision here is never expected to be the *same* registration, - # so it must not be treated as one. Call store.create unconditionally - # rather than guarding on `self._slug not in store.names()` first: - # store.create already raises on a name that already exists, and a - # guard that silently skipped registration on that outcome would - # silently alias this Identity to a stored Principal it doesn't - # actually share credentials with -- the exact hazard this random - # scheme exists to avoid, reintroduced by trying to avoid it. - store.create( - CreateIdentityArgs( - display_name=self._slug, - slug=self._slug, - config=self._config, - credentials=self._credentials, - )) + + @property + def principal(self) -> Principal: + """Return this identity's connection principal, including credentials.""" + return Principal(self._slug, self._config, self._credentials) @property def slug(self) -> str: diff --git a/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py b/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py index 365898026..e08c4a955 100644 --- a/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py +++ b/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py @@ -195,9 +195,7 @@ def _workspace_host() -> Optional[str]: def _principal(identity: Any) -> Any: - from kumo_core.sources.principals import store - - return None if identity is None else store.get(identity.slug) + return None if identity is None else identity.principal def _databricks(connector: Any) -> Target: diff --git a/packages/kumo-engine/test/test_identity.py b/packages/kumo-engine/test/test_identity.py index ed4793f1d..b86ffee6a 100644 --- a/packages/kumo-engine/test/test_identity.py +++ b/packages/kumo-engine/test/test_identity.py @@ -1,118 +1,78 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -r"""`Identity`'s slug is a random per-registration key, not derived from -`config`/`credentials` at all. - -An earlier version fingerprinted `repr(credentials)`, which always hashed -the same redacted `SecretStr` placeholder regardless of the wrapped value: -two `Identity`s built from *different* secrets collided on one slug, and -the second silently resolved to the first's credentials. A later version -fixed that by unwrapping `SecretStr` before hashing, but that just traded -one problem for another: the slug became a deterministic, externally -visible function of the credentials themselves, which -- logged or -otherwise leaked, against an often-already-known connection configuration --- is an offline verifier an attacker can check a guessed low-entropy -credential (e.g. a password) against. A random slug has neither problem. - -Uses a fresh, isolated `PrincipalStore` (not the process-wide one) so -these tests don't depend on -- or pollute -- any other test's identities. -""" +"""Direct credentials resolve without process-local registration.""" +import pickle import uuid import pytest -from kumo_core.sources.principals import PrincipalStore - from kumo.engine.connector.identity import S3Identity - - -def test_distinct_credentials_get_distinct_slugs_and_resolve_to_themselves( - monkeypatch) -> None: - isolated_store = PrincipalStore() - monkeypatch.setattr('kumo.engine.connector.identity.store', isolated_store) - - first = S3Identity(access_key_id='AKIA1', secret_access_key='secret1') - second = S3Identity(access_key_id='AKIA2', secret_access_key='secret2') - - assert first.slug != second.slug - - first_principal = isolated_store.get(first.slug) - second_principal = isolated_store.get(second.slug) - assert (first_principal.credentials.access_key_id.get_secret_value() == - 'AKIA1') - assert (second_principal.credentials.access_key_id.get_secret_value() == - 'AKIA2') - assert (second_principal.credentials.secret_access_key.get_secret_value() - == 'secret2') - - -def test_identical_credentials_still_get_distinct_slugs( - monkeypatch) -> None: - r"""Unlike the earlier credential-derived scheme, identical credentials - no longer coalesce into one store entry -- each `Identity()` call is - its own registration. Nothing in this package looks two `Identity` - objects up by whether they share credentials, so this is fine.""" - isolated_store = PrincipalStore() - monkeypatch.setattr('kumo.engine.connector.identity.store', isolated_store) - - first = S3Identity(access_key_id='AKIA1', secret_access_key='secret1') - second = S3Identity(access_key_id='AKIA1', secret_access_key='secret1') - - assert first.slug != second.slug - assert set(isolated_store.names()) == {first.slug, second.slug} - - -def test_credential_free_identities_still_get_distinct_slugs( - monkeypatch) -> None: - isolated_store = PrincipalStore() - monkeypatch.setattr('kumo.engine.connector.identity.store', isolated_store) - - ambient = S3Identity() - assume_role = S3Identity(role_arn='arn:aws:iam::123456789012:role/kumo') - - assert ambient.slug != assume_role.slug - - -def test_slug_never_encodes_the_credential_value(monkeypatch) -> None: - r"""The slug must not be a deterministic function of the credentials at - all -- not even a hashed one -- since a deterministic, externally - visible slug is an offline verifier for a guessed credential. Two - `Identity`s built from the same credentials getting unrelated slugs - (not just different from each other, but not reproducible from the - credential value itself) is what this asserts.""" - isolated_store = PrincipalStore() - monkeypatch.setattr('kumo.engine.connector.identity.store', isolated_store) - - slugs = { - S3Identity(access_key_id='AKIA1', secret_access_key='secret1').slug +from kumo_core.sources.principals import PrincipalStore, identity_id, resolve +from kumoapi.data_source import CreateIdentityArgs + + +def test_direct_identity_survives_pickle_without_store( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Workers resolve credentials even when their identity store is empty.""" + isolated = PrincipalStore() + monkeypatch.setattr("kumo_core.sources.principals.store", isolated) + original = S3Identity(access_key_id="example", secret_access_key="secret") + identity = pickle.loads(pickle.dumps(original)) + principal = resolve([identity], connector="s3", config_example="", fallback="") + assert isolated.names() == [] + assert identity.slug == original.slug + assert principal.credentials.secret_access_key.get_secret_value() == "secret" + assert "secret" not in repr(identity) + + +def test_random_slugs_do_not_encode_credentials() -> None: + """Equivalent credentials have unrelated public identifiers.""" + identities = [ + S3Identity(access_key_id="example", secret_access_key="secret") for _ in range(5) - } - assert len(slugs) == 5 - - -def test_a_slug_collision_raises_instead_of_silently_aliasing( - monkeypatch) -> None: - r"""On the (astronomically unlikely) event of two `Identity()` calls - generating the same `uuid4()` slug, registration must fail loudly, not - silently resolve the second `Identity` to the first's stored - credentials -- code review finding: an earlier version guarded - `store.create(...)` behind `if self._slug not in store.names()`, which - skipped registration (and silently aliased) on exactly this collision, - backwards from what its own comment claimed. `store.create` already - raises on a name collision -- calling it unconditionally is the fix. - """ - isolated_store = PrincipalStore() - monkeypatch.setattr('kumo.engine.connector.identity.store', isolated_store) - monkeypatch.setattr( - uuid, 'uuid4', lambda: uuid.UUID('12345678123456781234567812345678')) - - first = S3Identity(access_key_id='AKIA1', secret_access_key='secret1') - with pytest.raises(ValueError, match='already exists'): - S3Identity(access_key_id='AKIA2', secret_access_key='secret2') - - # The failed second construction must not have aliased -- the store - # still only knows the first identity's credentials. - assert isolated_store.names() == [first.slug] - principal = isolated_store.get(first.slug) - assert principal.credentials.access_key_id.get_secret_value() == 'AKIA1' + ] + assert len({identity.slug for identity in identities}) == 5 + + +def test_colliding_slugs_do_not_alias_credentials( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Direct resolution uses the supplied principal even with identical names.""" + monkeypatch.setattr(uuid, "uuid4", lambda: uuid.UUID(int=1)) + first = S3Identity(access_key_id="first", secret_access_key="secret1") + second = S3Identity(access_key_id="second", secret_access_key="secret2") + assert first.slug == second.slug + assert second.principal.credentials.access_key_id.get_secret_value() == "second" + + +def test_legacy_name_id_and_slug_resolution(monkeypatch: pytest.MonkeyPatch) -> None: + """Existing registered callers still resolve by every legacy identifier.""" + isolated = PrincipalStore() + monkeypatch.setattr("kumo_core.sources.principals.store", isolated) + identity = S3Identity() + isolated.create( + CreateIdentityArgs( + display_name="legacy", slug="legacy-slug", config=identity.principal.config + ) + ) + for reference in ("legacy", "legacy-slug", identity_id("legacy")): + principal = resolve([reference], connector="s3", config_example="", fallback="") + assert principal.name == "legacy" + + +def test_structural_direct_identity_needs_no_store_name( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Core accepts principal-bearing objects without importing engine types.""" + from types import SimpleNamespace + + isolated = PrincipalStore() + monkeypatch.setattr("kumo_core.sources.principals.store", isolated) + identity = SimpleNamespace(principal=S3Identity().principal) + assert ( + resolve([identity], connector="s3", config_example="", fallback="") + == identity.principal + ) + assert isolated.names() == [] From 5ac5afd796f231fcba848836bdd64ea3a5b77130 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 07:13:15 +0000 Subject: [PATCH 02/10] Remove process-local principal registration and lookup --- .../src/kumo_bigquery/backend.py | 60 ++- .../src/kumo_bigquery/session.py | 27 +- .../tests/live/test_live_sink.py | 15 +- packages/kumo-core/README.md | 30 ++ .../sources/object_store_sessions.py | 5 +- .../src/kumo_core/sources/principals.py | 355 ++++-------------- .../tests/sources/unit/test_principals.py | 262 +++++-------- .../src/kumo_databricks/backend.py | 50 +-- .../src/kumo_databricks/session.py | 18 +- .../src/kumo_databricks/sink.py | 13 +- .../kumo/engine/connector/identity.py | 4 +- .../engine/integrations/_mlflow_target.py | 3 +- packages/kumo-engine/test/test_identity.py | 77 ++-- packages/kumo-gcs/src/kumo_gcs/backend.py | 16 +- packages/kumo-s3/src/kumo_s3/backend.py | 18 +- .../src/kumo_snowflake/artifacts.py | 26 +- .../src/kumo_snowflake/backend.py | 57 ++- .../src/kumo_snowflake/session.py | 19 +- .../kumo-snowflake/src/kumo_snowflake/sink.py | 10 +- .../tests/test_artifact_identity.py | 63 ++++ 20 files changed, 438 insertions(+), 690 deletions(-) create mode 100644 packages/kumo-snowflake/tests/test_artifact_identity.py diff --git a/packages/kumo-bigquery/src/kumo_bigquery/backend.py b/packages/kumo-bigquery/src/kumo_bigquery/backend.py index cbc881a29..71b44c7fb 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/backend.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/backend.py @@ -17,18 +17,6 @@ import logging from typing import Any, List, Mapping, Optional -from kumo_bigquery.session import ( - _BigQuerySessions, - _billing_project, - _clients, - _name, - _qualified, - _rows, - _target_config, -) -from kumo_bigquery.source import BigQuerySourceReader -from kumo_bigquery.sql import QueryPlan, sample_request, table_names -from kumo_bigquery.types import dtype_for, schema_columns from kumo_core.sources.backend import ( ingest_result, sampled_table, @@ -50,6 +38,19 @@ ) from kumoapi.typing import Dtype +from kumo_bigquery.session import ( + _BigQuerySessions, + _billing_project, + _clients, + _name, + _qualified, + _rows, + _target_config, +) +from kumo_bigquery.source import BigQuerySourceReader +from kumo_bigquery.sql import QueryPlan, sample_request, table_names +from kumo_bigquery.types import dtype_for, schema_columns + logger = logging.getLogger(__name__) @@ -57,12 +58,9 @@ class BigQuerySourceBackend(_BigQuerySessions): r"""Resolves source tables by querying BigQuery. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts an :class:`~kumoai_studio.identity.Identity`, an - identity ID, or the name it was created under. Leaving it unset is - the common case: a bound - :class:`~kumoai_studio.connector.BigQueryConnector` records the identity - it was created with. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. mode: The read mode every table is read under, or ``None`` to take whichever the reader offers first. staging_uri: A ``gs://`` prefix this run may export Parquet to. Without @@ -71,29 +69,17 @@ class BigQuerySourceBackend(_BigQuerySessions): an error: no bucket is a complete configuration. Example: - >>> import kumoai_studio as kumo # doctest: +SKIP - >>> from kumoapi.data_source import ( # doctest: +SKIP - ... BigQueryIdentityConfig, CreateIdentityArgs, - ... GoogleWorkloadIdentityAuthentication) - >>> identity = kumo.create_identity( # doctest: +SKIP - ... CreateIdentityArgs( - ... display_name='prod-bq', - ... config=BigQueryIdentityConfig( - ... authentication=GoogleWorkloadIdentityAuthentication( - ... service_account_email='kumo@data-project' - ... '.iam.gserviceaccount.com')))) - >>> kumo.set_backend(kumo.LocalBackend( # doctest: +SKIP - ... sources={kumo.DataSourceType.BIGQUERY: BigQuerySourceBackend( - ... staging_uri='gs://bucket/kumo')})) - >>> events = kumo.BigQueryConnector( # doctest: +SKIP - ... name='events', project_id='data-project', - ... dataset_id='analytics', identity=identity) + >>> from kumo_core.sources.principals import Principal + >>> from kumoapi.data_source import ( + ... BigQueryIdentityConfig, GoogleAmbientAuthentication) + >>> principal = Principal('prod-bq', BigQueryIdentityConfig( + ... authentication=GoogleAmbientAuthentication()), None) + >>> backend = BigQuerySourceBackend(identity=principal) """ source_type = DataSourceType.BIGQUERY - _default_hint = ('LocalBackend(sources={DataSourceType.BIGQUERY: ' - 'BigQuerySourceBackend(identity=identity)})') + _default_hint = 'BigQuerySourceBackend(identity=identity)' def __init__( self, diff --git a/packages/kumo-bigquery/src/kumo_bigquery/session.py b/packages/kumo-bigquery/src/kumo_bigquery/session.py index 62ee6be6c..28dfd645b 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/session.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/session.py @@ -18,7 +18,6 @@ import google.auth.transport.requests from google.auth.credentials import Credentials from google.cloud import bigquery, bigquery_storage, storage -from kumo_bigquery.auth import google_credentials from kumo_core.sources.principals import IdentityRef, Principal, resolve from kumoapi.data_source import ( BigQueryConnectorResourceConfig, @@ -26,6 +25,8 @@ ) from kumoapi.plugin import SourceConnector +from kumo_bigquery.auth import google_credentials + #: What an impersonated token is minted for. The platform uses the same scope #: for BigQuery (``rest/config/identity.py``'s ``_google_scope``), so a local #: read and a platform read reach the same APIs as the same principal. @@ -167,10 +168,10 @@ class _ClientCache: """ def __init__(self) -> None: self._lock = threading.RLock() - self._query: Dict[Tuple[str, str, str], Any] = {} + self._query: Dict[Tuple[str, ...], Any] = {} self._read: Dict[str, Any] = {} self._write: Dict[str, Any] = {} - self._storage: Dict[Tuple[str, str], Any] = {} + self._storage: Dict[Tuple[str, ...], Any] = {} def query_client(self, principal: Principal, *, project: str, location: str) -> Any: @@ -223,11 +224,11 @@ def close(self, name: Optional[str] = None) -> None: key for key in cache if name is None or key[0] == name ]: del cache[key] - for cache in (self._read, self._write): - for key in [ - key for key in cache if name is None or key == name + for client_cache in (self._read, self._write): + for client_name in [ + key for key in client_cache if name is None or key == name ]: - del cache[key] + del client_cache[client_name] _clients = _ClientCache() @@ -248,9 +249,9 @@ class _BigQuerySessions: identity. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts the identity object the SDK handed back, an - identity ID, or the name it was created under. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. """ #: How a subclass spells "supply a default identity" in its own terms. The @@ -289,11 +290,9 @@ def _client(self, connector: SourceConnector) -> Any: def _principal(self, connector: SourceConnector) -> Principal: return resolve( - (getattr(connector, 'identity', None), - getattr(connector, 'identity_id', None), self._identity), + (getattr(connector, 'identity', None), self._identity, + getattr(connector, 'identity_id', None)), connector=connector, - config_example='BigQueryIdentityConfig(...), credentials=...', - connector_example='BigQueryConnector(identity=identity, ...)', fallback=(f'A default for sources that name none is also ' f'accepted, as {self._default_hint}.'), ) diff --git a/packages/kumo-bigquery/tests/live/test_live_sink.py b/packages/kumo-bigquery/tests/live/test_live_sink.py index ba150c931..b84906986 100644 --- a/packages/kumo-bigquery/tests/live/test_live_sink.py +++ b/packages/kumo-bigquery/tests/live/test_live_sink.py @@ -47,17 +47,20 @@ SourceNotFoundError, UnsupportedReadModeError, ) -from kumo_core.sources.principals import store # noqa: E402 +from kumo_core.sources.principals import Principal # noqa: E402 from kumo_core.sources.types import ReadMode # noqa: E402 from kumoapi.data_source import ( # noqa: E402 BigQueryConnectorResourceConfig, BigQueryIdentityConfig, - CreateIdentityArgs, GoogleAmbientAuthentication, ) from kumoapi.jobs import WriteMode # noqa: E402 -IDENTITY = f"bq-sink-live-{RUN}" +IDENTITY = Principal( + name=f"bq-sink-live-{RUN}", + config=BigQueryIdentityConfig(authentication=GoogleAmbientAuthentication()), + credentials=None, +) def connector(dataset=DATASET, location="US", project=PROJECT): @@ -71,10 +74,6 @@ def connector(dataset=DATASET, location="US", project=PROJECT): @pytest.fixture(scope="module") def client(): - store.create( - CreateIdentityArgs( - display_name=IDENTITY, slug=IDENTITY, config=BigQueryIdentityConfig( - authentication=GoogleAmbientAuthentication()))) bq = bigquery.Client(project=PROJECT, credentials=CREDENTIALS) bq.create_dataset(bigquery.Dataset(f"{PROJECT}.{DATASET}")) try: @@ -224,7 +223,7 @@ def test_append_widens_and_accepts_all_null(client, sink, tmp_path): loaded = sorted( (row.entity, row.score, row.label) for row in client.query(f"SELECT * FROM `{PROJECT}.{DATASET}.{name}`")) - assert [(int(e), s, l) for e, s, l in loaded] == [(1, 3.0, None), + assert [(int(entity), score, label) for entity, score, label in loaded] == [(1, 3.0, None), (2, 4.0, None)] diff --git a/packages/kumo-core/README.md b/packages/kumo-core/README.md index 22da3ce9e..28966b3a0 100644 --- a/packages/kumo-core/README.md +++ b/packages/kumo-core/README.md @@ -94,3 +94,33 @@ Run commands from the repository worktree after installing the normal Kumo devel On a CUDA-capable development machine, `make test-kumo-core-gpu` selects the retained device-parametrized package cases. The focused, non-required Kumo Core GPU workflow runs on manual dispatch and, for trusted in-repository PRs, when the existing `ml-algorithms` component label triggers a workflow event or a labeled PR is subsequently updated; bot-applied labels may require that subsequent update because `GITHUB_TOKEN` events do not launch workflows. The retired Triton workflow is not part of this package. Kumo is not yet a uv workspace. These commands operate on `packages/kumo-core` explicitly and do not rely on workspace discovery. + +## Source identities + +Source and sink backends accept a `kumo_core.sources.principals.Principal` or +an identity object exposing a `.principal` property. Configuration and explicit +credentials travel with that object; ambient credentials and token-file contents +are resolved on the receiving worker. Identity names, IDs, and objects containing +only a slug no longer resolve through a process-global registry. + +Pass the identity directly on a connector, or supply `identity=principal` to its +backend when a hosted connector contains only credential-free metadata. For +example: + +```python +from kumo_core.sources.principals import Principal +from kumo_s3.backend import S3SourceBackend +from kumoapi.data_source import S3AmbientAuthentication, S3IdentityConfig + +principal = Principal( + name="source-reader", + config=S3IdentityConfig(authentication=S3AmbientAuthentication()), + credentials=None, +) +backend = S3SourceBackend(identity=principal) +``` + +A name or ID supplied without a principal raises a migration error. Leaving the +identity unset still selects ambient authentication for backends that support it. +The service SDK's remote identity-management API is separate from this local +connection interface. diff --git a/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py b/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py index 06f5ca29f..f47560ff2 100644 --- a/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py +++ b/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py @@ -166,10 +166,9 @@ def _destination(self, connector: SourceConnector, def _principal(self, connector: SourceConnector) -> Optional[Principal]: return resolve( - (getattr(connector, 'identity', None), - getattr(connector, 'identity_id', None), self._identity), + (getattr(connector, 'identity', None), self._identity, + getattr(connector, 'identity_id', None)), connector=connector, - config_example=f'{self.provider}IdentityConfig(...)', fallback=('Leaving the identity unset is also supported, and ' 'signs with the ambient credential chain.'), optional=True, diff --git a/packages/kumo-core/src/kumo_core/sources/principals.py b/packages/kumo-core/src/kumo_core/sources/principals.py index 008933485..decc73c90 100644 --- a/packages/kumo-core/src/kumo_core/sources/principals.py +++ b/packages/kumo-core/src/kumo_core/sources/principals.py @@ -1,105 +1,40 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 +"""Self-contained connection principals with no process-global identity registry.""" -from __future__ import annotations +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Literal, Protocol, overload, runtime_checkable -import hashlib -import json -import threading -from dataclasses import dataclass, replace -from typing import ( - Dict, - List, - Optional, - Protocol, - Sequence, - Union, - runtime_checkable, -) +from kumoapi.data_source import IdentityConfig, IdentityCredentials, IdentityType -from kumoapi.data_source import ( - CreateIdentityArgs, - IdentityConfig, - IdentityCredentials, - IdentityType, - validate_identity_credentials_match, -) - -__all__ = [ - "DirectIdentity", - "IdentityRef", - "Named", - "Principal", - "Registration", - "PrincipalStore", - "identity_id", - "resolve", - "store", -] - - -@runtime_checkable -class Named(Protocol): - """Anything carrying the slug an identity was created with. - - The SDK's credential-free identity object satisfies this, and is the - shape a caller most often holds. Matched structurally rather than by type - because that class is defined above this layer, in a package a plugin - resolving an identity must not import. - """ - @property - def slug(self) -> str: - ... - - -def identity_id(name: str) -> str: - r"""Derives the ID of an identity created in this process. - - A local identity is not assigned an ID by a server, so it derives one from - the name it was created under: the same name yields the same ID in every - process that creates it, which is what lets a connector bound in one - process resolve in another. Connectors and saved graphs record this ID, so - the derivation is a compatibility surface -- changing it orphans them. - """ - digest = hashlib.sha256(json.dumps(name).encode("utf-8")).hexdigest() - return f"identity-{digest[:16]}" +__all__ = ["DirectIdentity", "IdentityRef", "Principal", "resolve"] @dataclass(frozen=True) class Principal: - r"""The principal a source plugin opens its connections as. - - Four things, and only the things a plugin reads. :attr:`config` names the - account, host or workspace; :attr:`credentials` holds material where the - authentication kind stores any, and is ``None`` where it does not -- a - Snowflake ``oauth_token_file`` identity reads a token the container - runtime mounts, and a Google workload identity uses the environment's own - principal. Both are fully configured and store nothing, so ``None`` is not - an error. + """Configuration and credentials used to open a provider connection. - :attr:`name` travels because a plugin that caches connections keys them by - it, and because it is what an error should say when a connection cannot be - opened. It is also what a saved graph records, so a reload in a fresh - process finds the same principal behind it. - - The slug and description an identity was created with are deliberately - *not* here. They serve resolution and the credential-free summary the SDK - hands a user; no plugin reads either, and the narrower this is, the less - an implementation can come to depend on. + Args: + name: Stable connection-cache key, independent of credential contents. + config: Provider account and authentication configuration. + credentials: Explicit credentials, or None for worker-local authentication. """ + name: str config: IdentityConfig - credentials: Optional[IdentityCredentials] + credentials: IdentityCredentials | None @property def type(self) -> IdentityType: + """Return the provider selected by this principal's configuration.""" return self.config.type @runtime_checkable class DirectIdentity(Protocol): - """An identity carrying its connection principal without store lookup.""" + """An identity supplying its connection principal directly.""" @property def principal(self) -> Principal: @@ -107,220 +42,80 @@ def principal(self) -> Principal: ... -#: A self-contained principal or a legacy object, ID, slug, or store name. -IdentityRef = Union[str, Named, DirectIdentity] - - -@dataclass(frozen=True) -class Registration: - r"""One identity as the store holds it: a principal, and how it is named. - - The slug is matched when a caller names an identity by something other - than its display name; the description is reported back in the - credential-free summary. Neither crosses into a plugin. - """ - principal: Principal - slug: str - description: str - - @property - def name(self) -> str: - return self.principal.name - - -class PrincipalStore: - r"""The identities this process holds, by name. +IdentityRef = Principal | DirectIdentity - Safe to use from several threads. The module-level :data:`store` is the - one every caller shares, so the identity area and the data sources cannot - disagree about what a name means; this class is instantiable so a test can - work against an isolated one. - Nothing here is serialized or written to an artifact. A saved graph - records the identity *reference*; the material never leaves this process, - and credential types protect themselves -- ``SnowflakePasswordCredentials`` - and its siblings hold ``SecretStr``, whose representation is redacted - unless a caller asks for plaintext explicitly. - """ - def __init__(self) -> None: - self._lock = threading.RLock() - self._by_name: Dict[str, Registration] = {} - - @staticmethod - def _check_name(name: str) -> str: - if not isinstance(name, str) or not name: - raise ValueError("An identity name must be a non-empty string.") - if name != name.strip(): - raise ValueError( - f"Identity name {name!r} must not have leading or trailing " - f"whitespace; names are matched exactly and are recorded in " - f"saved graphs.") - return name - - def create(self, args: CreateIdentityArgs) -> Registration: - name = self._check_name(args.display_name) - # Re-checked here even though `CreateIdentityArgs` validates on - # construction, because a caller may have built the args before this - # store existed and mutated them since. - validate_identity_credentials_match(args.config, args.credentials) - with self._lock: - if name in self._by_name: - raise ValueError( - f"Identity {name!r} already exists in this process. " - f"Delete it with kumoai_studio.delete_identity, or rotate its " - f"credentials with kumoai_studio.rotate_identity_credentials.") - registration = Registration( - principal=Principal(name=name, config=args.config, - credentials=args.credentials), - slug=args.slug or name, - description=args.description or "", - ) - self._by_name[name] = registration - return registration - - def get(self, name: str) -> Principal: - r"""Returns the principal behind :obj:`name`, for opening a connection. - """ - with self._lock: - return self._by_name[name].principal - - def registration(self, name: str) -> Registration: - r"""Returns the full record, for the SDK's own credential-free view.""" - with self._lock: - return self._by_name[name] - - def names(self) -> List[str]: - with self._lock: - return sorted(self._by_name) - - def remove(self, name: str) -> None: - with self._lock: - self._by_name.pop(name, None) - - def rotate(self, name: str, - credentials: Optional[IdentityCredentials]) -> Registration: - r"""Replaces the material behind :obj:`name`. - - The config is untouched: rotation replaces a secret, it does not move - the identity to a different principal or authentication kind. That is - also why it does not invalidate connections by itself -- a session - already open authenticates as the same principal either way. What a - caller *does* have to do is close cached connections, so that a - rotation prompted by a failing one is not answered from the cache; the - identity area does that, because only it knows which plugin to ask. - """ - with self._lock: - current = self._by_name[name] - validate_identity_credentials_match(current.principal.config, - credentials) - rotated = replace( - current, - principal=replace(current.principal, credentials=credentials), - ) - self._by_name[name] = rotated - return rotated - - def resolve(self, reference: Optional[IdentityRef]) -> Optional[str]: - r"""Maps anything that names an identity to its store name. - - A caller may hold the credential-free identity object the SDK handed - back, the ID a bound connector recorded, or the name the identity was - created under, and all three reach here. Resolving them in one place - is what keeps the identity area and the data sources from drifting. - - The identity object is matched by shape rather than by type, because - this layer is below the SDK that defines it: anything carrying a - ``slug`` is taken to mean that slug. +@overload +def resolve( + candidates: Sequence[object], + *, + connector: object, + fallback: str = "", + optional: Literal[False] = False, +) -> Principal: ... - Returns ``None`` for anything unknown, because a caller who supplied a - default identity instead is not in error. A caller that does require - one raises on ``None`` itself, where it can say what it wanted. - """ - if reference is None: - return None - if isinstance(reference, str): - wanted = reference - elif isinstance(reference, Named): - wanted = reference.slug - else: - # Unknown shape: `None`, as the docstring promises, so a caller - # who also supplied a default gets it instead of an AttributeError - # raised from inside resolution. - return None - with self._lock: - if wanted in self._by_name: - return wanted - for name, registration in self._by_name.items(): - if wanted in (registration.slug, identity_id(name)): - return name - return None - def clear(self) -> None: - with self._lock: - self._by_name.clear() +@overload +def resolve( + candidates: Sequence[object], + *, + connector: object, + fallback: str = "", + optional: Literal[True], +) -> Principal | None: ... -#: The identities this process holds. One store, so the identity area and the -#: data sources cannot disagree about what a name means. -store = PrincipalStore() +@overload +def resolve( + candidates: Sequence[object], + *, + connector: object, + fallback: str = "", + optional: bool, +) -> Principal | None: ... def resolve( - candidates: Sequence[Optional[IdentityRef]], + candidates: Sequence[object], *, connector: object, - config_example: str, - fallback: str, - connector_example: Optional[str] = None, + fallback: str = "", optional: bool = False, -) -> Optional[Principal]: - r"""Finds the principal behind whatever a source backend has. - - One resolver for every provider, because the fallthrough is the same in - all of them: a bound connector records the identity *ID* the identity area - issued, an unbound target may carry a name or the identity object itself, - and a backend may hold a default of any of those shapes. They differ only - in where they look, not in what they mean. - - A reference this process cannot resolve falls through to the next - candidate rather than failing, because a caller who also supplied a - default meant it to be used. If nothing resolves, what *was* named is - reported: an identity that was never created and a name misspelled at - creation are the two ways to arrive here, and the caller can only tell - them apart by seeing the name. +) -> Principal | None: + """Select the first supplied principal or principal-bearing identity. Args: - candidates: References to try in order. ``None`` and empty entries are - skipped, so a caller passes the same three slots every time. - connector: Whatever named the identity, for the error message. - config_example: How this provider's identity is configured, spelled as - the argument to ``CreateIdentityArgs``. - fallback: What leaving the identity unset does. The main UX of a - misconfigured identity, and the one part that is genuinely - per-backend rather than per-provider. - connector_example: How the identity is then named on a connector, - where the provider has one to name. - optional: Whether naming *no* identity at all is allowed. It is for an - object store, where an unset identity selects the host's ambient - credential chain. A name that fails to resolve is still an error: - falling back to a different principal silently is not a service to - anyone. + candidates: Connector identity and backend default, in preference order. + None entries are ignored. Names, IDs, and credential-free metadata + cannot authenticate; a later explicit principal may supply a default. + connector: Connector identifier used in error messages. + fallback: Provider-specific instructions appended to missing-identity errors. + optional: Allow no identity to select ambient authentication. + + Returns: + The first available principal, or None when optional and none was supplied. + + Raises: + TypeError: An identity's principal property returns an invalid value. + ValueError: Supplied references cannot authenticate or an identity is required. """ - named = [reference for reference in candidates if reference] - for reference in named: - if isinstance(reference, DirectIdentity): - return reference.principal - name = store.resolve(reference) - if name is not None: - return store.get(name) - if optional and not named: + supplied = False + for candidate in candidates: + if candidate is None: + continue + supplied = True + if isinstance(candidate, Principal): + return candidate + if isinstance(candidate, DirectIdentity): + principal = candidate.principal + if not isinstance(principal, Principal): + raise TypeError("Identity.principal must return a Principal.") + return principal + if optional and not supplied: return None - wanted = ", ".join(repr(reference) for reference in named) or "no" - known = ", ".join(repr(name) for name in store.names()) or "none" - bind = f"; {connector_example}" if connector_example else "" raise ValueError( - f"Connector {getattr(connector, 'id', connector)!r} names {wanted} " - f"identity, and none exists in this process. Create one and name it " - f"on the connector: identity = kumoai_studio.create_identity(" - f"CreateIdentityArgs(display_name='', " - f"config={config_example})){bind}. {fallback} Existing: {known}.") + f"Connector {getattr(connector, 'id', connector)!r} needs an identity " + "object or Principal containing authentication configuration. " + "Identity name, ID, and slug lookup is no longer supported. " + f"{fallback}".rstrip() + ) diff --git a/packages/kumo-core/tests/sources/unit/test_principals.py b/packages/kumo-core/tests/sources/unit/test_principals.py index a762a73fd..a50e6f8c8 100644 --- a/packages/kumo-core/tests/sources/unit/test_principals.py +++ b/packages/kumo-core/tests/sources/unit/test_principals.py @@ -1,18 +1,14 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 +"""Principals resolve from supplied values without process-local registration.""" -from __future__ import annotations +import pickle +from types import SimpleNamespace import pytest -from kumo_core.sources.principals import ( - PrincipalStore, - identity_id, - resolve, - store, -) +from kumo_core.sources.principals import Principal, resolve from kumoapi.data_source import ( - CreateIdentityArgs, IdentityType, S3AmbientAuthentication, S3IdentityConfig, @@ -20,186 +16,96 @@ SnowflakeIdentityConfig, SnowflakeKeyPairCredentials, ) -from pydantic import SecretStr - -SNOWFLAKE = SnowflakeIdentityConfig( - account="xy12345", - username="KUMO_READER", - authentication=SnowflakeAuthenticationKind.KEY_PAIR, -) -KEY = SnowflakeKeyPairCredentials(private_key=SecretStr("unused")) -S3 = S3IdentityConfig(authentication=S3AmbientAuthentication()) @pytest.fixture -def isolated(monkeypatch): - r"""A store of this test's own. - - The module-level one is process-global on purpose -- the identity area and - the data sources must not disagree about a name -- so a test that wants to - put things in it swaps it out rather than mutating the shared one. - """ - fresh = PrincipalStore() - monkeypatch.setattr("kumo_core.sources.principals.store", fresh) - return fresh - +def principal() -> Principal: + """Provide an explicit Snowflake principal with redacted credential types.""" + return Principal( + name="snowflake-test", + config=SnowflakeIdentityConfig( + account="account", + username="reader", + authentication=SnowflakeAuthenticationKind.KEY_PAIR, + ), + credentials=SnowflakeKeyPairCredentials(private_key="unused"), + ) + + +def test_principal_preserves_configuration_and_credentials( + principal: Principal, +) -> None: + """A principal remains self-contained after crossing a process boundary.""" + restored = pickle.loads(pickle.dumps(principal)) + assert restored == principal + assert restored.type is IdentityType.SNOWFLAKE + assert restored.credentials.private_key.get_secret_value() == "unused" + assert "unused" not in repr(restored) + + +def test_ambient_principal_needs_no_stored_credentials() -> None: + """Worker-local authentication is explicit in the supplied principal config.""" + principal = Principal( + "ambient", S3IdentityConfig(authentication=S3AmbientAuthentication()), None + ) + assert resolve([principal], connector="source") is principal + assert principal.type is IdentityType.S3 + assert principal.credentials is None -def _create(store, name, config=SNOWFLAKE, credentials=KEY, slug=None): - return store.create( - CreateIdentityArgs(display_name=name, slug=slug, config=config, - credentials=credentials)) +def test_structural_identity_resolves_directly(principal: Principal) -> None: + """A principal-bearing object needs no SDK-specific class or store name.""" + identity = SimpleNamespace(principal=principal) + assert resolve([identity], connector="source") is principal -def test_a_principal_reports_its_provider_from_its_config(isolated): - principal = _create(isolated, "prod-sf").principal - assert principal.type is IdentityType.SNOWFLAKE - assert principal.name == "prod-sf" - assert principal.credentials == KEY +def test_connector_identity_precedes_backend_default(principal: Principal) -> None: + """Resolution retains caller preference among explicit principals.""" + default = Principal("default", principal.config, principal.credentials) + assert resolve([principal, default], connector="source") is principal -def test_an_ambient_identity_holds_no_credentials(isolated): - r"""``None`` is a configured state, not a missing one: an S3 ambient - identity signs with the host's own chain and has nothing to store. - """ - principal = _create(isolated, "prod-s3", config=S3, - credentials=None).principal - assert principal.credentials is None - assert principal.type is IdentityType.S3 +def test_supplied_default_can_authenticate_credential_free_metadata( + principal: Principal, +) -> None: + """Hosted connector metadata can be paired with an explicit backend principal.""" + metadata = SimpleNamespace(slug="remote-identity") + assert ( + resolve([metadata, "remote-identity", principal], connector="source") + is principal + ) -def test_an_id_is_derived_from_the_name_and_is_stable(): - r"""Connectors and saved graphs record this, so it is a compatibility - surface: the same name must yield the same ID in every process. - """ - assert identity_id("prod-sf") == identity_id("prod-sf") - assert identity_id("prod-sf") != identity_id("prod-bq") - assert identity_id("prod-sf").startswith("identity-") - -@pytest.mark.parametrize("spelling", ["name", "slug", "id", "object"]) -def test_resolution_understands_every_way_to_name_an_identity( - isolated, spelling): - _create(isolated, "prod-sf", slug="prod-sf-slug") - given = { - "name": "prod-sf", - "slug": "prod-sf-slug", - "id": identity_id("prod-sf"), - # Matched by shape, not by type: the SDK's identity object lives above - # this layer, so anything carrying a slug is taken to mean that slug. - "object": type("Identity", (), {"slug": "prod-sf-slug"})(), - } - assert isolated.resolve(given[spelling]) == "prod-sf" - - -def test_an_unknown_reference_resolves_to_none(isolated): - r"""Not an error here: a caller who also supplied a default meant it to be - used, and only the caller knows whether it had one. - """ - assert isolated.resolve("nope") is None - assert isolated.resolve(None) is None - - -def test_creating_a_name_twice_is_refused(isolated): - _create(isolated, "prod-sf") - with pytest.raises(ValueError, match="already exists"): - _create(isolated, "prod-sf") - - -@pytest.mark.parametrize("name", ["", " prod-sf", "prod-sf "]) -def test_a_name_that_would_not_match_exactly_is_refused(isolated, name): - r"""Names are matched exactly and recorded in saved graphs, so padding - that a caller cannot see would orphan a graph later. - """ - with pytest.raises(ValueError, match="(?i)identity name"): - _create(isolated, name) - - -def test_rotation_replaces_material_and_leaves_the_principal_alone(isolated): - before = _create(isolated, "prod-sf").principal - rotated = SnowflakeKeyPairCredentials(private_key=SecretStr("rotated")) - after = isolated.rotate("prod-sf", rotated).principal - - assert after.config == before.config - assert after.credentials == rotated - assert isolated.get("prod-sf").credentials == rotated - - -def test_rotation_refuses_material_the_config_cannot_use(isolated): - r"""The pairing is validated on the way in, so a key-pair identity cannot - be rotated onto a password. - """ - _create(isolated, "prod-sf") - with pytest.raises(ValueError): - isolated.rotate("prod-sf", None) - - -def test_the_store_hands_out_only_what_a_plugin_reads(isolated): - r"""The slug and description stay on the registration; a principal is the - four things a plugin actually uses. - """ - registration = _create(isolated, "prod-sf", slug="prod-sf-slug") - assert registration.slug == "prod-sf-slug" - assert not hasattr(registration.principal, "slug") - assert isolated.get("prod-sf") == registration.principal - - -def _resolve(**kwargs): - return resolve(config_example="SnowflakeIdentityConfig(...)", - fallback="A default is also accepted.", **kwargs) - - -def test_resolution_prefers_the_connector_over_the_backend_default(isolated): - _create(isolated, "on-connector") - _create(isolated, "the-default") - connector = type("C", (), {"id": "c1", "identity": "on-connector"})() - - assert _resolve(candidates=(connector.identity, None, "the-default"), - connector=connector).name == "on-connector" - - -def test_an_unresolvable_reference_falls_through_to_the_next(isolated): - r"""A caller who supplied a default meant it to be used, so a stale name - on a connector is not fatal while a usable default is standing by. - """ - _create(isolated, "the-default") - connector = type("C", (), {"id": "c1"})() - - assert _resolve(candidates=("gone", None, "the-default"), - connector=connector).name == "the-default" - - -def test_naming_nothing_that_resolves_reports_what_was_named(isolated): - r"""An identity never created and a name misspelled at creation are the - two ways to arrive here, and only the names tell them apart. - """ - _create(isolated, "prod-sf") - connector = type("C", (), {"id": "c1"})() - - with pytest.raises(ValueError) as raised: - _resolve(candidates=("typo-sf", None, None), connector=connector) - message = str(raised.value) - assert "'c1'" in message - assert "'typo-sf'" in message - assert "'prod-sf'" in message - assert "A default is also accepted." in message - - -def test_an_optional_identity_is_none_only_when_nothing_was_named(isolated): - r"""An unset identity selects the ambient credential chain; a name that - fails to resolve must not, since that would sign as a different principal - without saying so. - """ - connector = type("C", (), {"id": "c1"})() - assert _resolve(candidates=(None, None, None), connector=connector, - optional=True) is None - with pytest.raises(ValueError, match="'named'"): - _resolve(candidates=("named", None, None), connector=connector, - optional=True) +@pytest.mark.parametrize("candidates", [[], [None], [None, None]]) +def test_unset_optional_identity_selects_ambient_authentication( + candidates: list[None], +) -> None: + """Ambient authentication is selected only when no identity was supplied.""" + assert resolve(candidates, connector="source", optional=True) is None -def test_the_module_level_store_is_the_one_everything_shares(): - r"""One store, so the identity area and the data sources cannot disagree - about what a name means. - """ - assert isinstance(store, PrincipalStore) - assert isinstance(store.names(), list) +@pytest.mark.parametrize( + "reference", ["name", "identity-id", "", SimpleNamespace(slug="slug")] +) +@pytest.mark.parametrize("optional", [False, True]) +def test_names_and_ids_cannot_silently_select_ambient_authentication( + reference: object, + optional: bool, +) -> None: + """Removed references raise an actionable error without echoing their contents.""" + with pytest.raises(ValueError, match="lookup is no longer supported"): + resolve([reference], connector="source", optional=optional) + + +def test_missing_required_identity_reports_provider_instructions() -> None: + """Failures describe direct identity inputs rather than a removed registry.""" + with pytest.raises(ValueError, match="Pass SnowflakeIdentity") as error: + resolve([None], connector="source", fallback="Pass SnowflakeIdentity(...).") + assert "identity object or Principal" in str(error.value) + assert "create_identity" not in str(error.value) + + +def test_invalid_principal_property_is_rejected() -> None: + """A structural match cannot return arbitrary authentication objects.""" + with pytest.raises(TypeError, match="must return a Principal"): + resolve([SimpleNamespace(principal="invalid")], connector="source") diff --git a/packages/kumo-databricks/src/kumo_databricks/backend.py b/packages/kumo-databricks/src/kumo_databricks/backend.py index 8f3b8e759..586ea0652 100644 --- a/packages/kumo-databricks/src/kumo_databricks/backend.py +++ b/packages/kumo-databricks/src/kumo_databricks/backend.py @@ -35,11 +35,6 @@ from kumo_core.sources.layout import staging_dir from kumo_core.sources.principals import IdentityRef from kumo_core.sources.types import ReadMode -from kumo_databricks import sql as dbx_sql -from kumo_databricks.catalog import table_names -from kumo_databricks.session import _DatabricksSessions, _target_config -from kumo_databricks.source import DatabricksSourceReader -from kumo_databricks.types import dtype_for from kumoapi.data_source import DataSourceType from kumoapi.plugin import PrepareIngestResult, SourceConnector from kumoapi.source_table import ( @@ -51,17 +46,20 @@ ) from kumoapi.typing import Dtype +from kumo_databricks import sql as dbx_sql +from kumo_databricks.catalog import table_names +from kumo_databricks.session import _DatabricksSessions, _target_config +from kumo_databricks.source import DatabricksSourceReader +from kumo_databricks.types import dtype_for + class DatabricksSourceBackend(_DatabricksSessions): r"""Resolves source tables by querying Databricks. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts an :class:`~kumoai_studio.identity.Identity`, an - identity ID, or the name it was created under. Leaving it unset is the - common case: a bound - :class:`~kumoai_studio.connector.DatabricksConnector` records the - identity it was created with. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. mode: A :class:`~kumo_core.sources.types.ReadMode` to force, when a run needs to know which path it took rather than only that the table was read. ``None`` takes the cheapest the reader offers. @@ -72,33 +70,17 @@ class DatabricksSourceBackend(_DatabricksSessions): ``SELECT`` the table already required. Example: - >>> import kumoai_studio as kumo # doctest: +SKIP - >>> from kumoapi.data_source import ( # doctest: +SKIP - ... CreateIdentityArgs, DatabricksIdentityConfig, - ... DatabricksOAuthCredentials) - >>> from pydantic import SecretStr # doctest: +SKIP - >>> identity = kumo.create_identity( # doctest: +SKIP - ... CreateIdentityArgs( - ... display_name='prod-dbx', - ... config=DatabricksIdentityConfig( - ... host='https://workspace.cloud.databricks.com', - ... client_id='service-principal-id'), - ... credentials=DatabricksOAuthCredentials( - ... client_secret=SecretStr('...')))) - >>> kumo.set_backend(kumo.LocalBackend( # doctest: +SKIP - ... sources={kumo.DataSourceType.DATABRICKS: - ... DatabricksSourceBackend( - ... staging_volume_path='/Volumes/main/kumo/staging')} - ... )) - >>> bricks = kumo.DatabricksConnector( # doctest: +SKIP - ... name='analytics', catalog='main', schema_name='features', - ... warehouse_id='warehouse-id', identity=identity) + >>> from kumo_core.sources.principals import Principal + >>> from kumoapi.data_source import ( + ... DatabricksAuthenticationKind, DatabricksIdentityConfig) + >>> principal = Principal('prod-dbx', DatabricksIdentityConfig( + ... authentication=DatabricksAuthenticationKind.AMBIENT), None) + >>> backend = DatabricksSourceBackend(identity=principal) """ source_type = DataSourceType.DATABRICKS - _default_hint = ('LocalBackend(sources={DataSourceType.DATABRICKS: ' - 'DatabricksSourceBackend(identity=identity)})') + _default_hint = 'DatabricksSourceBackend(identity=identity)' def __init__( self, diff --git a/packages/kumo-databricks/src/kumo_databricks/session.py b/packages/kumo-databricks/src/kumo_databricks/session.py index d74fc3883..818981de4 100644 --- a/packages/kumo-databricks/src/kumo_databricks/session.py +++ b/packages/kumo-databricks/src/kumo_databricks/session.py @@ -15,7 +15,7 @@ from __future__ import annotations from contextlib import contextmanager -from typing import Iterator, List, Optional +from typing import Iterator, List, Optional, TypeAlias from databricks import sql from databricks.sdk import WorkspaceClient @@ -31,7 +31,7 @@ from pydantic import SecretStr #: What this module builds and hands upward. -DatabricksSession = WorkspaceClient +DatabricksSession: TypeAlias = WorkspaceClient #: A warehouse is addressed by its own ID alone; a cluster is addressed #: through the workspace it belongs to, which only the workspace can report. @@ -131,9 +131,9 @@ class _DatabricksSessions: r"""Resolving a connector to a live Databricks SQL connection. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts the identity object the SDK handed back, an - identity ID, or the name it was created under. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. """ #: How a subclass spells "supply a default identity" in its own terms. The @@ -187,11 +187,9 @@ def _connected( def _principal(self, connector: SourceConnector) -> Principal: return resolve( - (getattr(connector, 'identity', None), - getattr(connector, 'identity_id', None), self._identity), + (getattr(connector, 'identity', None), self._identity, + getattr(connector, 'identity_id', None)), connector=connector, - config_example='DatabricksIdentityConfig(...), credentials=...', - connector_example='DatabricksConnector(identity=identity, ...)', fallback=(f'A default for sources that name none is also ' f'accepted, as {self._default_hint}.'), ) @@ -209,7 +207,7 @@ def _qualified(connector: SourceConnector, """ from kumo_databricks import sql as dbx config = _target_config(connector) - parts = (config.catalog, config.schema_name) + parts: tuple[str, ...] = (config.catalog, config.schema_name) if table_name is not None: parts += (table_name, ) return dbx.qualified_name(*parts) diff --git a/packages/kumo-databricks/src/kumo_databricks/sink.py b/packages/kumo-databricks/src/kumo_databricks/sink.py index 0b82aca01..891f592ab 100644 --- a/packages/kumo-databricks/src/kumo_databricks/sink.py +++ b/packages/kumo-databricks/src/kumo_databricks/sink.py @@ -27,15 +27,16 @@ import pandas as pd from databricks.sql.client import Connection from kumo_core.object_store_sink import FileStoreRouting -from kumo_databricks.registry import DatabricksModelRegistryMixin -from kumo_databricks.session import _target_config -from kumo_databricks.volume import is_volume_path, volume_filesystem -from kumo_databricks.write import RunVolume from kumoapi.data_source import DataSourceType from kumoapi.jobs import WriteMode from kumoapi.plugin import SourceConnector from pyarrow.fs import FileSystem +from kumo_databricks.registry import DatabricksModelRegistryMixin +from kumo_databricks.session import _target_config +from kumo_databricks.volume import is_volume_path, volume_filesystem +from kumo_databricks.write import RunVolume + class _DatabricksTables(DatabricksModelRegistryMixin): def write_table( @@ -113,6 +114,7 @@ def write_files(self, connector, table_name, files, from kumo_core.artifact_export import prepared_artifact_file from kumo_core.artifact_staging import selected_local_parquet_files + from kumo_databricks import output, sql, write selected = selected_local_parquet_files(files) @@ -151,8 +153,7 @@ class DatabricksSinkBackend(FileStoreRouting, _DatabricksTables): source_type = DataSourceType.DATABRICKS - _default_hint = ('LocalBackend(sinks={DataSourceType.DATABRICKS: ' - 'DatabricksSinkBackend(identity=identity)})') + _default_hint = 'DatabricksSinkBackend(identity=identity)' def holds_files(self, connector: SourceConnector, path: str) -> bool: return is_volume_path(path) diff --git a/packages/kumo-engine/kumo/engine/connector/identity.py b/packages/kumo-engine/kumo/engine/connector/identity.py index e502eac79..1bcd02c46 100644 --- a/packages/kumo-engine/kumo/engine/connector/identity.py +++ b/packages/kumo-engine/kumo/engine/connector/identity.py @@ -67,9 +67,7 @@ def principal(self) -> Principal: @property def slug(self) -> str: - r"""Satisfies `kumo_core.sources.principals.Named`, so this object is - directly usable wherever an `IdentityRef` is expected. - """ + """Return the stable, credential-independent identity slug.""" return self._slug def __repr__(self) -> str: diff --git a/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py b/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py index e08c4a955..7ac162ab5 100644 --- a/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py +++ b/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py @@ -233,9 +233,8 @@ def _databricks_token(client: Any) -> Iterator[None]: def _sagemaker(target: SageMakerMLflow) -> Target: - from kumoapi.data_source import S3AmbientAuthentication - from kumo.engine.connector import S3Connector + from kumoapi.data_source import S3AmbientAuthentication arn = target.tracking_server_arn assets = S3Connector(identity=target.identity) diff --git a/packages/kumo-engine/test/test_identity.py b/packages/kumo-engine/test/test_identity.py index b86ffee6a..a170d1018 100644 --- a/packages/kumo-engine/test/test_identity.py +++ b/packages/kumo-engine/test/test_identity.py @@ -8,20 +8,14 @@ import pytest from kumo.engine.connector.identity import S3Identity -from kumo_core.sources.principals import PrincipalStore, identity_id, resolve -from kumoapi.data_source import CreateIdentityArgs +from kumo_core.sources.principals import resolve -def test_direct_identity_survives_pickle_without_store( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_direct_identity_survives_pickle_without_store() -> None: """Workers resolve credentials even when their identity store is empty.""" - isolated = PrincipalStore() - monkeypatch.setattr("kumo_core.sources.principals.store", isolated) original = S3Identity(access_key_id="example", secret_access_key="secret") identity = pickle.loads(pickle.dumps(original)) - principal = resolve([identity], connector="s3", config_example="", fallback="") - assert isolated.names() == [] + principal = resolve([identity], connector="s3") assert identity.slug == original.slug assert principal.credentials.secret_access_key.get_secret_value() == "secret" assert "secret" not in repr(identity) @@ -47,32 +41,55 @@ def test_colliding_slugs_do_not_alias_credentials( assert second.principal.credentials.access_key_id.get_secret_value() == "second" -def test_legacy_name_id_and_slug_resolution(monkeypatch: pytest.MonkeyPatch) -> None: - """Existing registered callers still resolve by every legacy identifier.""" - isolated = PrincipalStore() - monkeypatch.setattr("kumo_core.sources.principals.store", isolated) - identity = S3Identity() - isolated.create( - CreateIdentityArgs( - display_name="legacy", slug="legacy-slug", config=identity.principal.config - ) - ) - for reference in ("legacy", "legacy-slug", identity_id("legacy")): - principal = resolve([reference], connector="s3", config_example="", fallback="") - assert principal.name == "legacy" +@pytest.mark.parametrize("reference", ["legacy", "legacy-slug", "identity-legacy"]) +def test_legacy_name_and_id_require_explicit_identity(reference: str) -> None: + """Names and IDs cannot select credentials from a removed global registry.""" + with pytest.raises(ValueError, match="lookup is no longer supported"): + resolve([reference], connector="s3", optional=True) -def test_structural_direct_identity_needs_no_store_name( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_structural_direct_identity_needs_no_store_name() -> None: """Core accepts principal-bearing objects without importing engine types.""" from types import SimpleNamespace - isolated = PrincipalStore() - monkeypatch.setattr("kumo_core.sources.principals.store", isolated) identity = SimpleNamespace(principal=S3Identity().principal) + assert resolve([identity], connector="s3") == identity.principal + + +@pytest.mark.parametrize("provider", ["s3", "gcs", "bigquery", "databricks"]) +def test_source_backends_use_explicit_principals(provider: str) -> None: + """Provider authentication paths consume supplied identities without lookup.""" + from types import SimpleNamespace + + from kumo.engine.connector import ( + BigQueryConnector, + BigQueryIdentity, + DatabricksConnector, + DatabricksIdentity, + GCSConnector, + GCSIdentity, + S3Connector, + ) + + connectors = { + "s3": lambda: S3Connector(identity=S3Identity()), + "gcs": lambda: GCSConnector(identity=GCSIdentity()), + "bigquery": lambda: BigQueryConnector( + project_id="test-project", dataset_id="dataset", identity=BigQueryIdentity() + ), + "databricks": lambda: DatabricksConnector( + catalog="catalog", + schema_name="schema", + warehouse_id="warehouse", + identity=DatabricksIdentity(), + ), + } + connector = connectors[provider]() + backend = connector.source_backend + principal = connector.identity.principal + assert backend._principal(connector) == principal + backend._identity = principal assert ( - resolve([identity], connector="s3", config_example="", fallback="") - == identity.principal + backend._principal(SimpleNamespace(id="remote", identity_id="remote-id")) + is principal ) - assert isolated.names() == [] diff --git a/packages/kumo-gcs/src/kumo_gcs/backend.py b/packages/kumo-gcs/src/kumo_gcs/backend.py index c7d350004..91ad3b2c9 100644 --- a/packages/kumo-gcs/src/kumo_gcs/backend.py +++ b/packages/kumo-gcs/src/kumo_gcs/backend.py @@ -11,7 +11,6 @@ ) from kumo_core.sources.principals import IdentityRef, Principal from kumo_core.sources.types import ReadMode -from kumo_gcs.session import GCS_NAMESPACE, _gcs_session_for, _live_token from kumoapi.data_source import ( DataSourceType, GCSConnectorResourceConfig, @@ -28,6 +27,8 @@ ) from pyarrow import fs +from kumo_gcs.session import GCS_NAMESPACE, _gcs_session_for, _live_token + class GCSSessions(ObjectStoreSessions): r"""Resolving a connector and a table name to a reader over a live bucket. @@ -39,10 +40,9 @@ class GCSSessions(ObjectStoreSessions): has gone stale -- see :func:`_live_token`. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts an identity ID or the name it was created - under. Unset is the common case, and the one the ambient - credential chain serves. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a table contributes. Defaults to Google Cloud Storage; name a compatible service explicitly, or its @@ -122,9 +122,9 @@ class GCSSourceBackend(GCSSessions, ObjectStoreSourceBackend): the shared downloader handles native and SDK transfers. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts an :class:`~kumoai_studio.identity.Identity`, an - identity ID, or the name it was created under. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a GCS table contributes. Defaults to Google Cloud Storage. diff --git a/packages/kumo-s3/src/kumo_s3/backend.py b/packages/kumo-s3/src/kumo_s3/backend.py index dfd31df9d..6b9d62416 100644 --- a/packages/kumo-s3/src/kumo_s3/backend.py +++ b/packages/kumo-s3/src/kumo_s3/backend.py @@ -3,7 +3,6 @@ # SPDX-License-Identifier: Apache-2.0 from typing import Any, Optional, Union -import kumo_s3 from kumo_core.sources.errors import ReconnectRequiredError from kumo_core.sources.object_store_access import ObjectStoreAccess from kumo_core.sources.object_store_backend import ObjectStoreSourceBackend @@ -13,7 +12,6 @@ ) from kumo_core.sources.principals import IdentityRef, Principal from kumo_core.sources.types import ReadMode -from kumo_s3.session import anonymous_filesystem, arrow_connection_options from kumoapi.data_source import ( DataSourceType, S3AccessKeyAuthentication, @@ -35,6 +33,9 @@ from pyarrow.fs import S3FileSystem from pydantic import SecretStr +import kumo_s3 +from kumo_s3.session import anonymous_filesystem, arrow_connection_options + #: What an S3 identity resolves to: a ready filesystem, or a #: ``boto3.session.Session`` whose resolved credentials are read off it. S3Session = Union[S3FileSystem, Any] @@ -48,10 +49,9 @@ class S3Sessions(ObjectStoreSessions): cannot resolve to two different principals. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts an identity ID or the name it was created - under. Unset is the common case, and the one the ambient - credential chain serves. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a table contributes. Defaults to ordinary AWS S3; name an S3-compatible service explicitly, or its @@ -158,9 +158,9 @@ class S3SourceBackend(S3Sessions, ObjectStoreSourceBackend): setup. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts an :class:`~kumoai_studio.identity.Identity`, an - identity ID, or the name it was created under. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. storage_namespace: The storage system this process reaches, recorded in every graph coordinate an S3 table contributes. Defaults to ordinary AWS S3; name an S3-compatible service explicitly, or its diff --git a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py index cd374c1dd..a6d26c3fd 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py @@ -29,11 +29,9 @@ from pathlib import Path from typing import Callable, Dict, List, Optional, Sequence, Tuple, TypeVar -# Aliased: three methods below take a `SnapshotStore` parameter named -# `store`, and one name meaning two stores inside one class is how a line -# reaching for the identity store quietly gets the snapshot store instead. -from kumo_core.sources.principals import IdentityRef -from kumo_core.sources.principals import store as identity_store +from kumo_core.sources.principals import IdentityRef, resolve +from kumoapi.plugin import IngestResult, SnapshotStore, _Handle + from kumo_snowflake.session import ( SnowflakeSession, _quoted_literal, @@ -42,7 +40,6 @@ _sessions, resolved, ) -from kumoapi.plugin import IngestResult, SnapshotStore, _Handle _Item = TypeVar('_Item') _Result = TypeVar('_Result') @@ -492,10 +489,8 @@ class StageArtifactLocation: root: Fully-qualified stage URI, optionally with a prefix, such as ``@PROD.ML.KUMO_ARTIFACTS/local-backend``. The stage must already exist. Its role needs database/schema usage plus stage read/write. - identity: A name, local identity ID, or - :class:`~kumoai_studio.identity.Identity` created through - :func:`kumoai_studio.create_identity`. Its role needs the stage - privileges below. + identity: A Principal or self-contained identity object. Its role + needs the stage privileges below. Names and IDs are not accepted. parallel: Concurrent file transfers, from 1 through 99. The local working artifact directory is derived from ``Storage.scratch``; @@ -526,15 +521,8 @@ def _session(self) -> SnowflakeSession: borrow a connector's, since a stage location is independent of whatever table happened to be read last. """ - name = identity_store.resolve(self.identity) - if name is None: - known = ', '.join(repr(item) for item in identity_store.names()) or 'none' - raise ValueError( - f'Snowflake stage {self.root!r} names identity ' - f'{self.identity!r}, which does not exist in this process. ' - f'Create it with kumoai_studio.create_identity first. ' - f'Existing: {known}.') - session = _sessions.get(identity_store.get(name), None) + principal = resolve((self.identity,), connector=self.root) + session = _sessions.get(principal, None) _require_snowpark(session) return session diff --git a/packages/kumo-snowflake/src/kumo_snowflake/backend.py b/packages/kumo-snowflake/src/kumo_snowflake/backend.py index 8f6fee652..d8a1c9a36 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/backend.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/backend.py @@ -30,16 +30,6 @@ from kumo_core.sources.layout import staging_dir from kumo_core.sources.principals import IdentityRef from kumo_core.sources.types import ReadMode -from kumo_snowflake.session import ( - SnowflakeSession, - _require_snowpark, - _SnowflakeSessions, - _target_config, - resolved, -) -from kumo_snowflake.source import SnowflakeSourceReader -from kumo_snowflake.sql import describe_columns -from kumo_snowflake.types import dtype_for from kumoapi.data_source import DataSourceType from kumoapi.plugin import PrepareIngestResult, SourceConnector from kumoapi.source_table import ( @@ -51,42 +41,39 @@ ) from kumoapi.typing import Dtype +from kumo_snowflake.session import ( + SnowflakeSession, + _require_snowpark, + _SnowflakeSessions, + _target_config, + resolved, +) +from kumo_snowflake.source import SnowflakeSourceReader +from kumo_snowflake.sql import describe_columns +from kumo_snowflake.types import dtype_for + class SnowflakeSourceBackend(_SnowflakeSessions): r"""Resolves source tables by querying Snowflake. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts an :class:`~kumoai_studio.identity.Identity`, an - identity ID, or the name it was created under. Leaving it unset is the - common case: a bound - :class:`~kumoai_studio.connector.SnowflakeConnector` records the identity - it was created with, which is what makes this reader stateless - enough for :class:`~kumoai_studio.backend.LocalBackend` to register by - default. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. Example: - >>> import kumoai_studio as kumo # doctest: +SKIP - >>> from kumoapi.data_source import ( # doctest: +SKIP - ... CreateIdentityArgs, SnowflakeAuthenticationKind, - ... SnowflakeIdentityConfig) - >>> identity = kumo.create_identity( # doctest: +SKIP - ... CreateIdentityArgs( - ... display_name='prod-sf', - ... config=SnowflakeIdentityConfig( - ... account='xy12345', - ... authentication=( - ... SnowflakeAuthenticationKind.OAUTH_TOKEN_FILE)))) - >>> kumo.set_backend(kumo.LocalBackend()) # doctest: +SKIP - >>> snow = kumo.SnowflakeConnector( # doctest: +SKIP - ... name='analytics', warehouse='WH', database='ANALYTICS', - ... schema_name='PUBLIC', identity=identity) + >>> from kumo_core.sources.principals import Principal + >>> from kumoapi.data_source import ( + ... SnowflakeAuthenticationKind, SnowflakeIdentityConfig) + >>> principal = Principal('prod-sf', SnowflakeIdentityConfig( + ... account='account', + ... authentication=SnowflakeAuthenticationKind.OAUTH_TOKEN_FILE), None) + >>> backend = SnowflakeSourceBackend(identity=principal) """ source_type = DataSourceType.SNOWFLAKE - _default_hint = ('LocalBackend(sources={DataSourceType.SNOWFLAKE: ' - 'SnowflakeSourceBackend(identity=identity)})') + _default_hint = 'SnowflakeSourceBackend(identity=identity)' def __init__( self, diff --git a/packages/kumo-snowflake/src/kumo_snowflake/session.py b/packages/kumo-snowflake/src/kumo_snowflake/session.py index e96c88165..474c71aee 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/session.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/session.py @@ -27,11 +27,10 @@ import threading from contextlib import contextmanager -from typing import Any, Dict, Iterator, List, Optional, Tuple, Union +from typing import Any, Dict, Iterator, List, Optional, Tuple, TypeAlias, Union from kumo_core.sources.principals import IdentityRef, Principal, resolve from kumo_core.sources.sql import resolve_snowflake_identifier -from kumo_snowflake.keys import load_private_key, private_key_bytes from kumoapi.data_source import ( SnowflakeAuthenticationKind, SnowflakeConnectorResourceConfig, @@ -43,8 +42,10 @@ from pydantic import SecretStr from snowflake.snowpark import Session +from kumo_snowflake.keys import load_private_key, private_key_bytes + #: What this module builds and hands upward. -SnowflakeSession = Session +SnowflakeSession: TypeAlias = Session #: Where Snowpark Container Services mounts the OAuth token, when an identity #: names no path of its own. @@ -426,9 +427,9 @@ class _SnowflakeSessions: beside it is the whole reason this class is not written twice. Args: - identity: A fallback identity, used only for connectors that name none - themselves. Accepts the identity object the SDK handed back, an - identity ID, or the name it was created under. + identity: A fallback Principal or self-contained identity object for + connectors without their own principal. Names, IDs, and slug-only + metadata cannot authenticate. Omit it to use a connector's identity. """ #: How a subclass spells "supply a default identity" in its own terms. The @@ -453,11 +454,9 @@ def _session(self, connector: SourceConnector, *, def _principal(self, connector: SourceConnector) -> Principal: return resolve( - (getattr(connector, 'identity', None), - getattr(connector, 'identity_id', None), self._identity), + (getattr(connector, 'identity', None), self._identity, + getattr(connector, 'identity_id', None)), connector=connector, - config_example='SnowflakeIdentityConfig(...), credentials=...', - connector_example='SnowflakeConnector(identity=identity, ...)', fallback=(f'A default for sources that name none is also ' f'accepted, as {self._default_hint}.'), ) diff --git a/packages/kumo-snowflake/src/kumo_snowflake/sink.py b/packages/kumo-snowflake/src/kumo_snowflake/sink.py index 751cefd1c..3a5cc0c8f 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/sink.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/sink.py @@ -14,6 +14,9 @@ import numpy as np import pandas as pd from kumo_core.object_store_sink import FileStoreRouting +from kumoapi.jobs import WriteMode +from kumoapi.plugin import SourceConnector + from kumo_snowflake.artifacts import _split_stage_location from kumo_snowflake.errors import is_lapsed_credential from kumo_snowflake.registry import SnowflakeModelRegistryMixin @@ -24,8 +27,6 @@ _target_config, resolved, ) -from kumoapi.jobs import WriteMode -from kumoapi.plugin import SourceConnector # Snowflake ARRAY and VARIANT are acquired as JSON strings, so nested # predictions cannot round-trip as typed lists or mappings. NumPy arrays @@ -122,6 +123,7 @@ def write_files(self, connector, table_name, files, """COPY selected Parquet into a table.""" del project_id, export_id from kumo_core.artifact_staging import selected_local_parquet_files + from kumo_snowflake.write import export_table_files selected = [str(path) for path in selected_local_parquet_files(files)] @@ -159,8 +161,7 @@ class SnowflakeSinkBackend(FileStoreRouting, _SnowflakeTables): identity: Fallback identity for connectors that name none. """ - _default_hint = ('LocalBackend(sinks={DataSourceType.SNOWFLAKE: ' - 'SnowflakeSinkBackend(identity=identity)})') + _default_hint = 'SnowflakeSinkBackend(identity=identity)' def holds_files(self, connector, path): """Whether ``path`` names a named internal stage location.""" @@ -229,6 +230,7 @@ def write_artifacts_to_table(self, table_name, artifact_path, replace=False, from functools import partial from kumo_core.artifact_export import prepared_artifact_file + from kumo_snowflake.write import ( _upload_local_parquet_to_user_stage, write_artifacts_to_table, diff --git a/packages/kumo-snowflake/tests/test_artifact_identity.py b/packages/kumo-snowflake/tests/test_artifact_identity.py new file mode 100644 index 000000000..1f0397a56 --- /dev/null +++ b/packages/kumo-snowflake/tests/test_artifact_identity.py @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Stage artifact authentication uses the caller's principal without a registry.""" + +import importlib.util +import sys +from pathlib import Path +from types import ModuleType, SimpleNamespace +from unittest.mock import Mock + +import pytest +from kumo_core.sources.principals import Principal +from kumoapi.data_source import SnowflakeAuthenticationKind, SnowflakeIdentityConfig + + +@pytest.fixture +def artifacts(monkeypatch: pytest.MonkeyPatch) -> ModuleType: + """Load the stage adapter with a mocked Snowpark session boundary.""" + session = ModuleType("kumo_snowflake.session") + session.SnowflakeSession = object + for name in ( + "_quoted_literal", + "_require_snowpark", + "_rows", + "_sessions", + "resolved", + ): + setattr(session, name, Mock()) + monkeypatch.setitem(sys.modules, session.__name__, session) + path = Path(__file__).parents[1] / "src/kumo_snowflake/artifacts.py" + spec = importlib.util.spec_from_file_location("_stage_artifact_identity_test", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, spec.name, module) + spec.loader.exec_module(module) + return module + + +@pytest.mark.parametrize("wrapped", [False, True]) +def test_stage_uses_supplied_principal(artifacts: ModuleType, wrapped: bool) -> None: + """Both plain principals and engine-style identities open target-free sessions.""" + principal = Principal( + "stage-test", + SnowflakeIdentityConfig( + account="account", + authentication=SnowflakeAuthenticationKind.OAUTH_TOKEN_FILE, + ), + None, + ) + identity = SimpleNamespace(principal=principal) if wrapped else principal + location = artifacts.StageArtifactLocation("@DB.SCHEMA.ARTIFACTS/root", identity) + result = location._session() + artifacts._sessions.get.assert_called_once_with(principal, None) + artifacts._require_snowpark.assert_called_once_with(result) + + +def test_stage_rejects_name_lookup(artifacts: ModuleType) -> None: + """A removed name reference fails before opening any Snowflake connection.""" + location = artifacts.StageArtifactLocation("@DB.SCHEMA.ARTIFACTS", "old-name") + with pytest.raises(ValueError, match="lookup is no longer supported"): + location._session() + artifacts._sessions.get.assert_not_called() From 629bb0e5b239df97da7781f4181e82ab7fc243aa Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 07:31:50 +0000 Subject: [PATCH 03/10] Normalize engine identities to Principal before provider calls --- packages/kumo-adls/src/kumo_adls/backend.py | 4 +- .../src/kumo_bigquery/backend.py | 6 +-- .../src/kumo_bigquery/session.py | 6 +-- .../kumo-bigquery/src/kumo_bigquery/sink.py | 17 ++++---- packages/kumo-core/README.md | 18 +++++---- .../sources/object_store_sessions.py | 4 +- .../src/kumo_core/sources/principals.py | 39 +++++-------------- .../tests/sources/unit/test_principals.py | 17 ++++---- .../src/kumo_databricks/backend.py | 6 +-- .../src/kumo_databricks/session.py | 6 +-- .../kumo-engine/kumo/engine/connector/adls.py | 11 +++--- .../kumo-engine/kumo/engine/connector/base.py | 13 ++++--- .../kumo/engine/connector/bigquery.py | 9 ++--- .../kumo/engine/connector/databricks.py | 11 +++--- .../kumo-engine/kumo/engine/connector/gcs.py | 11 +++--- .../kumo-engine/kumo/engine/connector/s3.py | 11 +++--- .../kumo/engine/connector/snowflake.py | 11 +++--- .../kumo-engine/test/test_adls_connector.py | 16 ++++---- .../test/test_bigquery_connector.py | 10 ++--- .../test/test_databricks_connector.py | 9 ++--- packages/kumo-engine/test/test_identity.py | 23 +++++------ packages/kumo-gcs/src/kumo_gcs/backend.py | 8 ++-- packages/kumo-s3/src/kumo_s3/backend.py | 8 ++-- .../src/kumo_snowflake/artifacts.py | 6 +-- .../src/kumo_snowflake/backend.py | 6 +-- .../src/kumo_snowflake/session.py | 6 +-- .../tests/test_artifact_identity.py | 10 ++--- 27 files changed, 139 insertions(+), 163 deletions(-) diff --git a/packages/kumo-adls/src/kumo_adls/backend.py b/packages/kumo-adls/src/kumo_adls/backend.py index 78aa543f6..f765b3529 100644 --- a/packages/kumo-adls/src/kumo_adls/backend.py +++ b/packages/kumo-adls/src/kumo_adls/backend.py @@ -11,7 +11,7 @@ ObjectStoreRoot, ObjectStoreSessions, ) -from kumo_core.sources.principals import IdentityRef +from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumoapi.adls import ( normalize_adls_root_uri, @@ -140,7 +140,7 @@ class ADLSSourceBackend(ADLSSessions, ObjectStoreSourceBackend): uri_source = ADLSURISource source_table = ADLSSourceTable - def __init__(self, identity: Optional[IdentityRef] = None, + def __init__(self, identity: Optional[Principal] = None, storage_namespace: Optional[str] = None, mode: Optional[ReadMode] = None): super().__init__(identity, storage_namespace) diff --git a/packages/kumo-bigquery/src/kumo_bigquery/backend.py b/packages/kumo-bigquery/src/kumo_bigquery/backend.py index 71b44c7fb..fcff2dcd5 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/backend.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/backend.py @@ -25,7 +25,7 @@ ) from kumo_core.sources.errors import PermanentSourceError, SourceNotFoundError from kumo_core.sources.layout import staging_dir -from kumo_core.sources.principals import IdentityRef +from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumoapi.data_source import DataSourceType from kumoapi.plugin import PrepareIngestResult, SourceConnector @@ -58,7 +58,7 @@ class BigQuerySourceBackend(_BigQuerySessions): r"""Resolves source tables by querying BigQuery. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. mode: The read mode every table is read under, or ``None`` to take @@ -83,7 +83,7 @@ class BigQuerySourceBackend(_BigQuerySessions): def __init__( self, - identity: Optional[IdentityRef] = None, + identity: Optional[Principal] = None, mode: Optional[ReadMode] = None, staging_uri: Optional[str] = None, ) -> None: diff --git a/packages/kumo-bigquery/src/kumo_bigquery/session.py b/packages/kumo-bigquery/src/kumo_bigquery/session.py index 28dfd645b..3a8f66400 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/session.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/session.py @@ -18,7 +18,7 @@ import google.auth.transport.requests from google.auth.credentials import Credentials from google.cloud import bigquery, bigquery_storage, storage -from kumo_core.sources.principals import IdentityRef, Principal, resolve +from kumo_core.sources.principals import Principal, resolve from kumoapi.data_source import ( BigQueryConnectorResourceConfig, BigQueryIdentityConfig, @@ -249,7 +249,7 @@ class _BigQuerySessions: identity. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. """ @@ -259,7 +259,7 @@ class _BigQuerySessions: #: constructor to reach for. _default_hint = '' - def __init__(self, identity: Optional[IdentityRef] = None) -> None: + def __init__(self, identity: Optional[Principal] = None) -> None: self._identity = identity def _credentials(self, connector: SourceConnector) -> Credentials: diff --git a/packages/kumo-bigquery/src/kumo_bigquery/sink.py b/packages/kumo-bigquery/src/kumo_bigquery/sink.py index f4366808e..c7c4fe84f 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/sink.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/sink.py @@ -20,6 +20,14 @@ from functools import partial from typing import Any, Iterator, Mapping, Optional +from kumo_core.sources.diagnostics import translated +from kumo_core.sources.errors import SourceAccessDeniedError +from kumo_core.sources.principals import Principal +from kumo_core.sources.protocol import require_mode, staged_first +from kumo_core.sources.types import Capability, ReadMode +from kumoapi.jobs import WriteMode +from kumoapi.plugin import SourceConnector + from kumo_bigquery import errors, staging, streaming, write from kumo_bigquery.session import ( _BigQuerySessions, @@ -28,13 +36,6 @@ _target_config, ) from kumo_bigquery.staging import StagingLocation -from kumo_core.sources.diagnostics import translated -from kumo_core.sources.errors import SourceAccessDeniedError -from kumo_core.sources.principals import IdentityRef -from kumo_core.sources.protocol import require_mode, staged_first -from kumo_core.sources.types import Capability, ReadMode -from kumoapi.jobs import WriteMode -from kumoapi.plugin import SourceConnector logger = logging.getLogger(__name__) @@ -65,7 +66,7 @@ class BigQuerySinkBackend(_BigQuerySessions): _default_hint = 'BigQuerySinkBackend(identity=identity)' - def __init__(self, identity: Optional[IdentityRef] = None, *, + def __init__(self, identity: Optional[Principal] = None, *, staging_uri: Optional[str] = None, mode: Optional[ReadMode] = None) -> None: if mode is ReadMode.STAGED and not staging_uri: diff --git a/packages/kumo-core/README.md b/packages/kumo-core/README.md index 28966b3a0..90178c549 100644 --- a/packages/kumo-core/README.md +++ b/packages/kumo-core/README.md @@ -97,14 +97,16 @@ Kumo is not yet a uv workspace. These commands operate on `packages/kumo-core` e ## Source identities -Source and sink backends accept a `kumo_core.sources.principals.Principal` or -an identity object exposing a `.principal` property. Configuration and explicit -credentials travel with that object; ambient credentials and token-file contents -are resolved on the receiving worker. Identity names, IDs, and objects containing -only a slug no longer resolve through a process-global registry. - -Pass the identity directly on a connector, or supply `identity=principal` to its -backend when a hosted connector contains only credential-free metadata. For +Source and sink backends accept `kumo_core.sources.principals.Principal` values. +Engine connectors convert convenience identities such as `S3Identity` into a +principal before constructing their backends. When calling a backend directly, +pass `identity.principal` or construct a `Principal` yourself. Configuration and +explicit credentials travel with that value; ambient credentials and token-file +contents are resolved on the receiving worker. Identity names, IDs, and objects +containing only a slug no longer resolve through a process-global registry. + +Pass a convenience identity on an engine connector, or supply `identity=principal` +to a backend when a hosted connector contains only credential-free metadata. For example: ```python diff --git a/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py b/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py index f47560ff2..e331ea80e 100644 --- a/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py +++ b/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py @@ -14,7 +14,7 @@ from .layout import within_root from .object_store import ObjectStoreSourceReader from .object_store_access import ObjectStoreAccess -from .principals import IdentityRef, Principal, resolve +from .principals import Principal, resolve _KEY_SAFE = "/-._~!$&'()*+,;=:@" @@ -45,7 +45,7 @@ class ObjectStoreSessions(ABC): rooted: type[Any] resource_config: type[Any] - def __init__(self, identity: Optional[IdentityRef] = None, + def __init__(self, identity: Optional[Principal] = None, storage_namespace: Optional[str] = None) -> None: self._identity = identity self.storage_namespace = storage_namespace or self.namespace diff --git a/packages/kumo-core/src/kumo_core/sources/principals.py b/packages/kumo-core/src/kumo_core/sources/principals.py index decc73c90..069faa022 100644 --- a/packages/kumo-core/src/kumo_core/sources/principals.py +++ b/packages/kumo-core/src/kumo_core/sources/principals.py @@ -5,11 +5,11 @@ from collections.abc import Sequence from dataclasses import dataclass -from typing import Literal, Protocol, overload, runtime_checkable +from typing import Literal, overload from kumoapi.data_source import IdentityConfig, IdentityCredentials, IdentityType -__all__ = ["DirectIdentity", "IdentityRef", "Principal", "resolve"] +__all__ = ["Principal", "resolve"] @dataclass(frozen=True) @@ -32,22 +32,9 @@ def type(self) -> IdentityType: return self.config.type -@runtime_checkable -class DirectIdentity(Protocol): - """An identity supplying its connection principal directly.""" - - @property - def principal(self) -> Principal: - """Return configuration and credentials for a fresh local session.""" - ... - - -IdentityRef = Principal | DirectIdentity - - @overload def resolve( - candidates: Sequence[object], + candidates: Sequence[Principal | None], *, connector: object, fallback: str = "", @@ -57,7 +44,7 @@ def resolve( @overload def resolve( - candidates: Sequence[object], + candidates: Sequence[Principal | None], *, connector: object, fallback: str = "", @@ -67,7 +54,7 @@ def resolve( @overload def resolve( - candidates: Sequence[object], + candidates: Sequence[Principal | None], *, connector: object, fallback: str = "", @@ -76,16 +63,16 @@ def resolve( def resolve( - candidates: Sequence[object], + candidates: Sequence[Principal | None], *, connector: object, fallback: str = "", optional: bool = False, ) -> Principal | None: - """Select the first supplied principal or principal-bearing identity. + """Select the first supplied connection principal. Args: - candidates: Connector identity and backend default, in preference order. + candidates: Connector principal and backend default, in preference order. None entries are ignored. Names, IDs, and credential-free metadata cannot authenticate; a later explicit principal may supply a default. connector: Connector identifier used in error messages. @@ -96,7 +83,6 @@ def resolve( The first available principal, or None when optional and none was supplied. Raises: - TypeError: An identity's principal property returns an invalid value. ValueError: Supplied references cannot authenticate or an identity is required. """ supplied = False @@ -106,16 +92,11 @@ def resolve( supplied = True if isinstance(candidate, Principal): return candidate - if isinstance(candidate, DirectIdentity): - principal = candidate.principal - if not isinstance(principal, Principal): - raise TypeError("Identity.principal must return a Principal.") - return principal if optional and not supplied: return None raise ValueError( - f"Connector {getattr(connector, 'id', connector)!r} needs an identity " - "object or Principal containing authentication configuration. " + f"Connector {getattr(connector, 'id', connector)!r} needs a Principal " + "containing authentication configuration. " "Identity name, ID, and slug lookup is no longer supported. " f"{fallback}".rstrip() ) diff --git a/packages/kumo-core/tests/sources/unit/test_principals.py b/packages/kumo-core/tests/sources/unit/test_principals.py index a50e6f8c8..498be41c2 100644 --- a/packages/kumo-core/tests/sources/unit/test_principals.py +++ b/packages/kumo-core/tests/sources/unit/test_principals.py @@ -53,10 +53,11 @@ def test_ambient_principal_needs_no_stored_credentials() -> None: assert principal.credentials is None -def test_structural_identity_resolves_directly(principal: Principal) -> None: - """A principal-bearing object needs no SDK-specific class or store name.""" +def test_identity_wrappers_require_engine_normalization(principal: Principal) -> None: + """Core accepts connection data rather than inspecting wrapper interfaces.""" identity = SimpleNamespace(principal=principal) - assert resolve([identity], connector="source") is principal + with pytest.raises(ValueError, match="needs a Principal"): + resolve([identity], connector="source") def test_connector_identity_precedes_backend_default(principal: Principal) -> None: @@ -99,13 +100,13 @@ def test_names_and_ids_cannot_silently_select_ambient_authentication( def test_missing_required_identity_reports_provider_instructions() -> None: """Failures describe direct identity inputs rather than a removed registry.""" - with pytest.raises(ValueError, match="Pass SnowflakeIdentity") as error: - resolve([None], connector="source", fallback="Pass SnowflakeIdentity(...).") - assert "identity object or Principal" in str(error.value) + with pytest.raises(ValueError, match="Pass a Principal") as error: + resolve([None], connector="source", fallback="Pass a Principal.") + assert "needs a Principal" in str(error.value) assert "create_identity" not in str(error.value) def test_invalid_principal_property_is_rejected() -> None: - """A structural match cannot return arbitrary authentication objects.""" - with pytest.raises(TypeError, match="must return a Principal"): + """Core rejects wrappers regardless of the shape of their principal property.""" + with pytest.raises(ValueError, match="needs a Principal"): resolve([SimpleNamespace(principal="invalid")], connector="source") diff --git a/packages/kumo-databricks/src/kumo_databricks/backend.py b/packages/kumo-databricks/src/kumo_databricks/backend.py index 586ea0652..ce56874b2 100644 --- a/packages/kumo-databricks/src/kumo_databricks/backend.py +++ b/packages/kumo-databricks/src/kumo_databricks/backend.py @@ -33,7 +33,7 @@ ) from kumo_core.sources.errors import PermanentSourceError, SourceNotFoundError from kumo_core.sources.layout import staging_dir -from kumo_core.sources.principals import IdentityRef +from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumoapi.data_source import DataSourceType from kumoapi.plugin import PrepareIngestResult, SourceConnector @@ -57,7 +57,7 @@ class DatabricksSourceBackend(_DatabricksSessions): r"""Resolves source tables by querying Databricks. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. mode: A :class:`~kumo_core.sources.types.ReadMode` to force, when a @@ -84,7 +84,7 @@ class DatabricksSourceBackend(_DatabricksSessions): def __init__( self, - identity: Optional[IdentityRef] = None, + identity: Optional[Principal] = None, mode: Optional[ReadMode] = None, staging_volume_path: Optional[str] = None, ) -> None: diff --git a/packages/kumo-databricks/src/kumo_databricks/session.py b/packages/kumo-databricks/src/kumo_databricks/session.py index 818981de4..22d3c3e62 100644 --- a/packages/kumo-databricks/src/kumo_databricks/session.py +++ b/packages/kumo-databricks/src/kumo_databricks/session.py @@ -20,7 +20,7 @@ from databricks import sql from databricks.sdk import WorkspaceClient from databricks.sql.client import Connection -from kumo_core.sources.principals import IdentityRef, Principal, resolve +from kumo_core.sources.principals import Principal, resolve from kumoapi.data_source import ( DatabricksAuthenticationKind, DatabricksConnectorResourceConfig, @@ -131,7 +131,7 @@ class _DatabricksSessions: r"""Resolving a connector to a live Databricks SQL connection. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. """ @@ -141,7 +141,7 @@ class _DatabricksSessions: #: constructor to reach for. _default_hint = '' - def __init__(self, identity: Optional[IdentityRef] = None) -> None: + def __init__(self, identity: Optional[Principal] = None) -> None: self._identity = identity def _client(self, connector: SourceConnector) -> DatabricksSession: diff --git a/packages/kumo-engine/kumo/engine/connector/adls.py b/packages/kumo-engine/kumo/engine/connector/adls.py index 19c1a439f..8f63e13c2 100644 --- a/packages/kumo-engine/kumo/engine/connector/adls.py +++ b/packages/kumo-engine/kumo/engine/connector/adls.py @@ -7,6 +7,9 @@ from typing import Optional from urllib.parse import unquote, urlsplit +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import ADLSIdentity from kumoapi.adls import normalize_adls_root_uri from kumoapi.data_source import ( ADLSAnyURIConnectorTarget, @@ -15,10 +18,6 @@ DataSourceType, ) -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import ADLSIdentity - class ADLSConnector(Connector): """Read ADLS Gen2 files and write output beneath a configured root. @@ -64,12 +63,12 @@ def config(self) -> ADLSConnectorResourceConfig: @cached_property def source_backend(self): backend = import_provider('kumo_adls.backend', 'adls').ADLSSourceBackend - return backend(identity=self.identity) + return backend(identity=self._principal) @cached_property def sink_backend(self): backend = import_provider('kumo_adls.sink', 'adls').ADLSSinkBackend - return backend(identity=self.identity) + return backend(identity=self._principal) def source_table_for(self, table_name: str): return self.source_backend.get_table_config(self, diff --git a/packages/kumo-engine/kumo/engine/connector/base.py b/packages/kumo-engine/kumo/engine/connector/base.py index 9d90c4011..6e801bb01 100644 --- a/packages/kumo-engine/kumo/engine/connector/base.py +++ b/packages/kumo-engine/kumo/engine/connector/base.py @@ -30,12 +30,12 @@ from pathlib import Path from typing import List, Literal, Optional, Union -from kumoapi.data_source import ConnectorResourceConfig, DataSourceType -from kumoapi.plugin import ArtifactSink, SourceBackend - from kumo.engine._local_schema import FileConnectorConfig, LocalSourceTableType from kumo.engine._scratch import fingerprint from kumo.engine.connector.identity import Identity +from kumo_core.sources.principals import Principal +from kumoapi.data_source import ConnectorResourceConfig, DataSourceType +from kumoapi.plugin import ArtifactSink, SourceBackend class Connector(ABC): @@ -43,7 +43,8 @@ class Connector(ABC): Instances are immutable and are threaded directly through `Table` construction and through output/export configs -- never referenced by a - string id. + string id. The original convenience identity stays on ``identity``; + provider backends receive its normalized connection principal. Args: identity: Credentials to authenticate as -- an `Identity` object @@ -52,8 +53,10 @@ class Connector(ABC): package treats as its ambient default (e.g. the local AWS/GCP credential chain for S3/GCS). """ - def __init__(self, identity: Optional[Identity] = None): + def __init__(self, identity: Optional[Identity] = None) -> None: self.identity = identity + self._principal: Principal | None = ( + None if identity is None else identity.principal) self.identity_id = identity.slug if identity is not None else None @property diff --git a/packages/kumo-engine/kumo/engine/connector/bigquery.py b/packages/kumo-engine/kumo/engine/connector/bigquery.py index 7f6181474..61182d38f 100644 --- a/packages/kumo-engine/kumo/engine/connector/bigquery.py +++ b/packages/kumo-engine/kumo/engine/connector/bigquery.py @@ -10,12 +10,11 @@ from functools import cached_property from typing import Optional -from kumoapi.data_source import BigQueryConnectorResourceConfig, DataSourceType -from kumoapi.source_table import BigQuerySourceTable - from kumo.engine.connector._extras import import_provider from kumo.engine.connector.base import Connector from kumo.engine.connector.identity import BigQueryIdentity +from kumoapi.data_source import BigQueryConnectorResourceConfig, DataSourceType +from kumoapi.source_table import BigQuerySourceTable class BigQueryConnector(Connector): @@ -83,7 +82,7 @@ def source_backend(self): "kumo_bigquery.backend", "bigquery").BigQuerySourceBackend from kumo_core.sources.types import ReadMode return BigQuerySourceBackend( - identity=self.identity, + identity=self._principal, staging_uri=self.staging_uri, mode=ReadMode.STAGED if self.require_staged else None, ) @@ -94,7 +93,7 @@ def sink_backend(self): "bigquery").BigQuerySinkBackend from kumo_core.sources.types import ReadMode return BigQuerySinkBackend( - identity=self.identity, + identity=self._principal, staging_uri=self.staging_uri, mode=ReadMode.STAGED if self.require_staged else None, ) diff --git a/packages/kumo-engine/kumo/engine/connector/databricks.py b/packages/kumo-engine/kumo/engine/connector/databricks.py index 4bc380a66..7643096a8 100644 --- a/packages/kumo-engine/kumo/engine/connector/databricks.py +++ b/packages/kumo-engine/kumo/engine/connector/databricks.py @@ -10,6 +10,9 @@ from functools import cached_property from typing import Optional +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import DatabricksIdentity from kumoapi.data_source import ( DatabricksConnectorResourceConfig, DataSourceType, @@ -18,10 +21,6 @@ from kumoapi.source_table import DatabricksSourceTable from typing_extensions import Self -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import DatabricksIdentity - class DatabricksConnector(Connector): r"""Connect directly to a Databricks Unity Catalog catalog and schema. @@ -90,7 +89,7 @@ def source_backend(self) -> SourceBackend: DatabricksSourceBackend = import_provider( "kumo_databricks.backend", "databricks").DatabricksSourceBackend return DatabricksSourceBackend( - identity=self.identity, + identity=self._principal, staging_volume_path=self.staging_volume_path, mode=ReadMode.STAGED if self.require_staged else None, ) @@ -99,7 +98,7 @@ def source_backend(self) -> SourceBackend: def sink_backend(self) -> ArtifactSink: DatabricksSinkBackend = import_provider( "kumo_databricks.sink", "databricks").DatabricksSinkBackend - return DatabricksSinkBackend(identity=self.identity) + return DatabricksSinkBackend(identity=self._principal) def source_table_for(self, table_name: str) -> DatabricksSourceTable: return DatabricksSourceTable( diff --git a/packages/kumo-engine/kumo/engine/connector/gcs.py b/packages/kumo-engine/kumo/engine/connector/gcs.py index 501fb9af8..ff86bfbb1 100644 --- a/packages/kumo-engine/kumo/engine/connector/gcs.py +++ b/packages/kumo-engine/kumo/engine/connector/gcs.py @@ -14,6 +14,9 @@ from typing import Optional from urllib.parse import urlsplit +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import GCSIdentity from kumoapi.data_source import ( DataSourceType, GCSAnyURIConnectorTarget, @@ -23,10 +26,6 @@ ) from kumoapi.source_table import GCSSourceTable -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import GCSIdentity - def _parse_gcs_root_dir(root_dir: str) -> GCSConnectorTarget: parsed = urlsplit(root_dir) @@ -95,12 +94,12 @@ def config(self) -> GCSConnectorResourceConfig: def source_backend(self): GCSSourceBackend = import_provider("kumo_gcs.backend", "gcs").GCSSourceBackend - return GCSSourceBackend(identity=self.identity) + return GCSSourceBackend(identity=self._principal) @cached_property def sink_backend(self): GCSSinkBackend = import_provider("kumo_gcs.sink", "gcs").GCSSinkBackend - return GCSSinkBackend(identity=self.identity) + return GCSSinkBackend(identity=self._principal) def source_table_for(self, table_name: str) -> GCSSourceTable: """Resolve source format and addressing through the provider reader.""" diff --git a/packages/kumo-engine/kumo/engine/connector/s3.py b/packages/kumo-engine/kumo/engine/connector/s3.py index 3788f3e77..d4d53c61c 100644 --- a/packages/kumo-engine/kumo/engine/connector/s3.py +++ b/packages/kumo-engine/kumo/engine/connector/s3.py @@ -18,6 +18,9 @@ class lives in the cloud SDK package, which this package does not depend on; from typing import Optional from urllib.parse import urlsplit +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import S3Identity from kumoapi.data_source import ( DataSourceType, S3AnyURIConnectorTarget, @@ -27,10 +30,6 @@ class lives in the cloud SDK package, which this package does not depend on; ) from kumoapi.source_table import S3SourceTable -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import S3Identity - def _parse_s3_root_dir(root_dir: str, region: Optional[str]) -> S3ConnectorTarget: @@ -102,12 +101,12 @@ def config(self) -> S3ConnectorResourceConfig: def source_backend(self): S3SourceBackend = import_provider("kumo_s3.backend", "s3").S3SourceBackend - return S3SourceBackend(identity=self.identity) + return S3SourceBackend(identity=self._principal) @cached_property def sink_backend(self): S3SinkBackend = import_provider("kumo_s3.sink", "s3").S3SinkBackend - return S3SinkBackend(identity=self.identity) + return S3SinkBackend(identity=self._principal) def source_table_for(self, table_name: str) -> S3SourceTable: """Resolve source format and addressing through the provider reader.""" diff --git a/packages/kumo-engine/kumo/engine/connector/snowflake.py b/packages/kumo-engine/kumo/engine/connector/snowflake.py index 19f2606c5..9092c05f9 100644 --- a/packages/kumo-engine/kumo/engine/connector/snowflake.py +++ b/packages/kumo-engine/kumo/engine/connector/snowflake.py @@ -13,6 +13,9 @@ from pathlib import Path from typing import Any, Dict, List, Optional +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import SnowflakeIdentity from kumoapi.data_source import ( DataSourceType, SnowflakeConnectorResourceConfig, @@ -21,10 +24,6 @@ from kumoapi.source_table import SnowflakeSourceTable from typing_extensions import Self -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import SnowflakeIdentity - #: Warehouse/database/schema environment variables Snowpark Container #: Services exports alongside the account/host `kumo_snowflake.spcs` already #: reads (https://docs.snowflake.com/en/developer-guide/snowpark-container- @@ -87,7 +86,7 @@ def source_backend(self) -> SourceBackend: # installed. SnowflakeSourceBackend = import_provider( "kumo_snowflake.backend", "snowflake").SnowflakeSourceBackend - return SnowflakeSourceBackend(identity=self.identity) + return SnowflakeSourceBackend(identity=self._principal) @cached_property def sink_backend(self) -> ArtifactSink: @@ -98,7 +97,7 @@ def sink_backend(self) -> ArtifactSink: """ SnowflakeSinkBackend = import_provider("kumo_snowflake.sink", "snowflake").SnowflakeSinkBackend - return SnowflakeSinkBackend(identity=self.identity) + return SnowflakeSinkBackend(identity=self._principal) def session(self) -> Any: r"""The Snowpark session this connector reads through.""" diff --git a/packages/kumo-engine/test/test_adls_connector.py b/packages/kumo-engine/test/test_adls_connector.py index 16e801e3f..d1a84089d 100644 --- a/packages/kumo-engine/test/test_adls_connector.py +++ b/packages/kumo-engine/test/test_adls_connector.py @@ -11,6 +11,9 @@ import pyarrow as pa import pyarrow.parquet as pq import pytest +from kumo.engine import ADLSConnector, ADLSIdentity, Table +from kumo.engine._portable import _source_table_name, portable_graph_config +from kumo.engine.trainer._scoring import ScoringDefaults from kumo_core.sources.object_store_access import ObjectStoreAccess from kumoapi.data_source import AzureCloud, DataSourceType from kumoapi.jobs import PredictionArtifactType, WriteMode @@ -18,10 +21,6 @@ from kumoapi.source_table import ADLSRelativeSource, ADLSSourceTable from pyarrow.fs import LocalFileSystem, SubTreeFileSystem -from kumo.engine import ADLSConnector, ADLSIdentity, Table -from kumo.engine._portable import _source_table_name, portable_graph_config -from kumo.engine.trainer._scoring import ScoringDefaults - ROOT = 'abfss://curated@companylake.dfs.core.windows.net/orders/' @@ -70,7 +69,7 @@ def test_invalid_roots_fail_locally(root): ADLSConnector(root_dir=root) -def test_workload_identity_is_registered_without_credentials(): +def test_workload_identity_is_normalized_without_credentials(): identity = ADLSIdentity(tenant_id='tenant', client_id='client', cloud=AzureCloud.PUBLIC) connector = ADLSConnector(root_dir=ROOT, identity=identity) @@ -78,8 +77,8 @@ def test_workload_identity_is_registered_without_credentials(): assert connector.identity_id == identity.slug assert identity._credentials is None assert 'tenant' not in repr(identity) - assert connector.source_backend._identity is identity - assert connector.sink_backend._identity is identity + assert connector.source_backend._identity == identity.principal + assert connector.sink_backend._identity is connector.source_backend._identity assert connector.source_backend is connector.source_backend assert connector.sink_backend is connector.sink_backend @@ -129,9 +128,8 @@ def test_rootless_graph_coordinate_contains_exact_source(storage): def test_invalid_prediction_output_fails_before_scoring(monkeypatch, tmp_path, snapshot, case, error, match): - from kumo_core.types import TaskType - from kumo.engine import PredictionOutputConfig, PredictionTable, Trainer + from kumo_core.types import TaskType monkeypatch.setenv('AZURE_TENANT_ID', 'tenant') monkeypatch.setenv('AZURE_CLIENT_ID', 'client') diff --git a/packages/kumo-engine/test/test_bigquery_connector.py b/packages/kumo-engine/test/test_bigquery_connector.py index e49bb7210..7bbbc3ea4 100644 --- a/packages/kumo-engine/test/test_bigquery_connector.py +++ b/packages/kumo-engine/test/test_bigquery_connector.py @@ -3,10 +3,9 @@ # SPDX-License-Identifier: Apache-2.0 import pytest -from kumo_core.sources.types import ReadMode - from kumo.engine.connector.bigquery import BigQueryConnector from kumo.engine.connector.identity import BigQueryIdentity +from kumo_core.sources.types import ReadMode @pytest.mark.parametrize( @@ -32,7 +31,7 @@ def test_read_configuration_reaches_the_cached_backend(staging_uri, backend = connector.source_backend assert connector.source_backend is backend - assert backend._identity is identity + assert backend._identity == identity.principal assert backend.staging_uri == staging_uri assert backend.mode is expected_mode @@ -63,15 +62,14 @@ def test_sink_backend_is_cached_and_carries_configuration(): assert connector.sink_backend is sink assert isinstance(sink, BigQuerySinkBackend) - assert sink._identity is identity + assert sink._identity == identity.principal assert sink.staging_uri == 'gs://staging/kumo' def test_fit_rejects_model_export_to_bigquery_up_front(): - from kumoapi.model_plan import ModelPlan - from kumo.engine.trainer.output_config import ModelOutputConfig from kumo.engine.trainer.trainer import Trainer + from kumoapi.model_plan import ModelPlan connector = BigQueryConnector(project_id='data-project', dataset_id='analytics') diff --git a/packages/kumo-engine/test/test_databricks_connector.py b/packages/kumo-engine/test/test_databricks_connector.py index 2abbd539b..254d934e8 100644 --- a/packages/kumo-engine/test/test_databricks_connector.py +++ b/packages/kumo-engine/test/test_databricks_connector.py @@ -3,11 +3,10 @@ # SPDX-License-Identifier: Apache-2.0 import pytest -from kumo_core.sources.types import ReadMode -from kumoapi.data_source import DatabricksAuthenticationKind - from kumo.engine.connector.databricks import DatabricksConnector from kumo.engine.connector.identity import DatabricksIdentity +from kumo_core.sources.types import ReadMode +from kumoapi.data_source import DatabricksAuthenticationKind @pytest.mark.parametrize( @@ -36,7 +35,7 @@ def test_read_configuration_reaches_the_cached_backend(staging_volume_path, backend = connector.source_backend assert connector.source_backend is backend - assert backend._identity is identity + assert backend._identity == identity.principal assert backend.staging_volume_path == staging_volume_path assert backend.mode is expected_mode @@ -78,4 +77,4 @@ def test_without_an_identity_the_connector_is_ambient(build): backend = connector.source_backend - assert backend._identity is connector.identity + assert backend._identity == connector.identity.principal diff --git a/packages/kumo-engine/test/test_identity.py b/packages/kumo-engine/test/test_identity.py index a170d1018..363fcb47d 100644 --- a/packages/kumo-engine/test/test_identity.py +++ b/packages/kumo-engine/test/test_identity.py @@ -8,14 +8,14 @@ import pytest from kumo.engine.connector.identity import S3Identity -from kumo_core.sources.principals import resolve +from kumo_core.sources.principals import Principal, resolve def test_direct_identity_survives_pickle_without_store() -> None: - """Workers resolve credentials even when their identity store is empty.""" + """Transported convenience identities supply explicit connection principals.""" original = S3Identity(access_key_id="example", secret_access_key="secret") identity = pickle.loads(pickle.dumps(original)) - principal = resolve([identity], connector="s3") + principal = resolve([identity.principal], connector="s3") assert identity.slug == original.slug assert principal.credentials.secret_access_key.get_secret_value() == "secret" assert "secret" not in repr(identity) @@ -48,12 +48,10 @@ def test_legacy_name_and_id_require_explicit_identity(reference: str) -> None: resolve([reference], connector="s3", optional=True) -def test_structural_direct_identity_needs_no_store_name() -> None: - """Core accepts principal-bearing objects without importing engine types.""" - from types import SimpleNamespace - - identity = SimpleNamespace(principal=S3Identity().principal) - assert resolve([identity], connector="s3") == identity.principal +def test_core_rejects_unnormalized_engine_identity() -> None: + """Convenience identities are normalized in engine, outside the core API.""" + with pytest.raises(ValueError, match="needs a Principal"): + resolve([S3Identity()], connector="s3") @pytest.mark.parametrize("provider", ["s3", "gcs", "bigquery", "databricks"]) @@ -86,8 +84,11 @@ def test_source_backends_use_explicit_principals(provider: str) -> None: } connector = connectors[provider]() backend = connector.source_backend - principal = connector.identity.principal - assert backend._principal(connector) == principal + principal = backend._identity + assert isinstance(principal, Principal) + assert principal == connector.identity.principal + assert connector.sink_backend._identity is principal + assert backend._principal(connector) is principal backend._identity = principal assert ( backend._principal(SimpleNamespace(id="remote", identity_id="remote-id")) diff --git a/packages/kumo-gcs/src/kumo_gcs/backend.py b/packages/kumo-gcs/src/kumo_gcs/backend.py index 91ad3b2c9..3f9a34585 100644 --- a/packages/kumo-gcs/src/kumo_gcs/backend.py +++ b/packages/kumo-gcs/src/kumo_gcs/backend.py @@ -9,7 +9,7 @@ ObjectStorePaths, ObjectStoreSessions, ) -from kumo_core.sources.principals import IdentityRef, Principal +from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumoapi.data_source import ( DataSourceType, @@ -40,7 +40,7 @@ class GCSSessions(ObjectStoreSessions): has gone stale -- see :func:`_live_token`. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. storage_namespace: The storage system this process reaches, recorded @@ -122,7 +122,7 @@ class GCSSourceBackend(GCSSessions, ObjectStoreSourceBackend): the shared downloader handles native and SDK transfers. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. storage_namespace: The storage system this process reaches, recorded @@ -148,7 +148,7 @@ class GCSSourceBackend(GCSSessions, ObjectStoreSourceBackend): def __init__( self, - identity: Optional[IdentityRef] = None, + identity: Optional[Principal] = None, storage_namespace: Optional[str] = None, mode: Optional[ReadMode] = None, ) -> None: diff --git a/packages/kumo-s3/src/kumo_s3/backend.py b/packages/kumo-s3/src/kumo_s3/backend.py index 6b9d62416..9af36b937 100644 --- a/packages/kumo-s3/src/kumo_s3/backend.py +++ b/packages/kumo-s3/src/kumo_s3/backend.py @@ -10,7 +10,7 @@ ObjectStorePaths, ObjectStoreSessions, ) -from kumo_core.sources.principals import IdentityRef, Principal +from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumoapi.data_source import ( DataSourceType, @@ -49,7 +49,7 @@ class S3Sessions(ObjectStoreSessions): cannot resolve to two different principals. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. storage_namespace: The storage system this process reaches, recorded @@ -158,7 +158,7 @@ class S3SourceBackend(S3Sessions, ObjectStoreSourceBackend): setup. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. storage_namespace: The storage system this process reaches, recorded @@ -185,7 +185,7 @@ class S3SourceBackend(S3Sessions, ObjectStoreSourceBackend): def __init__( self, - identity: Optional[IdentityRef] = None, + identity: Optional[Principal] = None, storage_namespace: Optional[str] = None, mode: Optional[ReadMode] = None, ) -> None: diff --git a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py index a6d26c3fd..d24349f34 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py @@ -29,7 +29,7 @@ from pathlib import Path from typing import Callable, Dict, List, Optional, Sequence, Tuple, TypeVar -from kumo_core.sources.principals import IdentityRef, resolve +from kumo_core.sources.principals import Principal, resolve from kumoapi.plugin import IngestResult, SnapshotStore, _Handle from kumo_snowflake.session import ( @@ -489,7 +489,7 @@ class StageArtifactLocation: root: Fully-qualified stage URI, optionally with a prefix, such as ``@PROD.ML.KUMO_ARTIFACTS/local-backend``. The stage must already exist. Its role needs database/schema usage plus stage read/write. - identity: A Principal or self-contained identity object. Its role + identity: A Principal with provider configuration and credentials. Its role needs the stage privileges below. Names and IDs are not accepted. parallel: Concurrent file transfers, from 1 through 99. @@ -498,7 +498,7 @@ class StageArtifactLocation: ``kumo_core``. """ root: str - identity: IdentityRef + identity: Principal parallel: int = 16 def __post_init__(self) -> None: diff --git a/packages/kumo-snowflake/src/kumo_snowflake/backend.py b/packages/kumo-snowflake/src/kumo_snowflake/backend.py index d8a1c9a36..193e5fe90 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/backend.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/backend.py @@ -28,7 +28,7 @@ ) from kumo_core.sources.errors import PermanentSourceError, SourceNotFoundError from kumo_core.sources.layout import staging_dir -from kumo_core.sources.principals import IdentityRef +from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumoapi.data_source import DataSourceType from kumoapi.plugin import PrepareIngestResult, SourceConnector @@ -57,7 +57,7 @@ class SnowflakeSourceBackend(_SnowflakeSessions): r"""Resolves source tables by querying Snowflake. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. @@ -77,7 +77,7 @@ class SnowflakeSourceBackend(_SnowflakeSessions): def __init__( self, - identity: Optional[IdentityRef] = None, + identity: Optional[Principal] = None, mode: Optional[ReadMode] = None, ) -> None: super().__init__(identity) diff --git a/packages/kumo-snowflake/src/kumo_snowflake/session.py b/packages/kumo-snowflake/src/kumo_snowflake/session.py index 474c71aee..f499e8cf6 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/session.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/session.py @@ -29,7 +29,7 @@ from contextlib import contextmanager from typing import Any, Dict, Iterator, List, Optional, Tuple, TypeAlias, Union -from kumo_core.sources.principals import IdentityRef, Principal, resolve +from kumo_core.sources.principals import Principal, resolve from kumo_core.sources.sql import resolve_snowflake_identifier from kumoapi.data_source import ( SnowflakeAuthenticationKind, @@ -427,7 +427,7 @@ class _SnowflakeSessions: beside it is the whole reason this class is not written twice. Args: - identity: A fallback Principal or self-contained identity object for + identity: A fallback Principal for connectors without their own principal. Names, IDs, and slug-only metadata cannot authenticate. Omit it to use a connector's identity. """ @@ -438,7 +438,7 @@ class _SnowflakeSessions: #: under different keyword arguments. _default_hint = '' - def __init__(self, identity: Optional[IdentityRef] = None) -> None: + def __init__(self, identity: Optional[Principal] = None) -> None: self._identity = identity @contextmanager diff --git a/packages/kumo-snowflake/tests/test_artifact_identity.py b/packages/kumo-snowflake/tests/test_artifact_identity.py index 1f0397a56..7fb242c12 100644 --- a/packages/kumo-snowflake/tests/test_artifact_identity.py +++ b/packages/kumo-snowflake/tests/test_artifact_identity.py @@ -6,7 +6,7 @@ import importlib.util import sys from pathlib import Path -from types import ModuleType, SimpleNamespace +from types import ModuleType from unittest.mock import Mock import pytest @@ -37,9 +37,8 @@ def artifacts(monkeypatch: pytest.MonkeyPatch) -> ModuleType: return module -@pytest.mark.parametrize("wrapped", [False, True]) -def test_stage_uses_supplied_principal(artifacts: ModuleType, wrapped: bool) -> None: - """Both plain principals and engine-style identities open target-free sessions.""" +def test_stage_uses_supplied_principal(artifacts: ModuleType) -> None: + """Explicit principals open target-free sessions without wrapper adapters.""" principal = Principal( "stage-test", SnowflakeIdentityConfig( @@ -48,8 +47,7 @@ def test_stage_uses_supplied_principal(artifacts: ModuleType, wrapped: bool) -> ), None, ) - identity = SimpleNamespace(principal=principal) if wrapped else principal - location = artifacts.StageArtifactLocation("@DB.SCHEMA.ARTIFACTS/root", identity) + location = artifacts.StageArtifactLocation("@DB.SCHEMA.ARTIFACTS/root", principal) result = location._session() artifacts._sessions.get.assert_called_once_with(principal, None) artifacts._require_snowpark.assert_called_once_with(result) From 23888ae74129028bd4b7c0498908a6ef92b1f333 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 19:11:55 +0000 Subject: [PATCH 04/10] Remove principal fallback selection from provider backends --- .../src/kumo_bigquery/backend.py | 6 +- .../src/kumo_bigquery/session.py | 23 ++---- .../kumo-bigquery/src/kumo_bigquery/sink.py | 4 +- .../sources/object_store_sessions.py | 15 ++-- .../src/kumo_core/sources/principals.py | 74 +---------------- .../tests/sources/unit/test_principals.py | 81 ++++++++----------- .../src/kumo_databricks/backend.py | 6 +- .../src/kumo_databricks/session.py | 23 ++---- .../src/kumo_databricks/sink.py | 4 +- packages/kumo-engine/test/test_identity.py | 31 +++---- packages/kumo-gcs/src/kumo_gcs/backend.py | 10 +-- packages/kumo-s3/src/kumo_s3/backend.py | 10 +-- .../src/kumo_snowflake/artifacts.py | 13 +-- .../src/kumo_snowflake/backend.py | 6 +- .../src/kumo_snowflake/session.py | 24 ++---- .../kumo-snowflake/src/kumo_snowflake/sink.py | 4 +- 16 files changed, 99 insertions(+), 235 deletions(-) diff --git a/packages/kumo-bigquery/src/kumo_bigquery/backend.py b/packages/kumo-bigquery/src/kumo_bigquery/backend.py index fcff2dcd5..926925b7a 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/backend.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/backend.py @@ -58,9 +58,7 @@ class BigQuerySourceBackend(_BigQuerySessions): r"""Resolves source tables by querying BigQuery. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. mode: The read mode every table is read under, or ``None`` to take whichever the reader offers first. staging_uri: A ``gs://`` prefix this run may export Parquet to. Without @@ -79,8 +77,6 @@ class BigQuerySourceBackend(_BigQuerySessions): source_type = DataSourceType.BIGQUERY - _default_hint = 'BigQuerySourceBackend(identity=identity)' - def __init__( self, identity: Optional[Principal] = None, diff --git a/packages/kumo-bigquery/src/kumo_bigquery/session.py b/packages/kumo-bigquery/src/kumo_bigquery/session.py index 3a8f66400..e118f3ea6 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/session.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/session.py @@ -18,7 +18,7 @@ import google.auth.transport.requests from google.auth.credentials import Credentials from google.cloud import bigquery, bigquery_storage, storage -from kumo_core.sources.principals import Principal, resolve +from kumo_core.sources.principals import Principal from kumoapi.data_source import ( BigQueryConnectorResourceConfig, BigQueryIdentityConfig, @@ -249,16 +249,9 @@ class _BigQuerySessions: identity. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. """ - #: How a subclass spells "supply a default identity" in its own terms. The - #: message resolution raises is the only place a caller learns the - #: constructor to reach for. - _default_hint = '' - def __init__(self, identity: Optional[Principal] = None) -> None: self._identity = identity @@ -289,10 +282,8 @@ def _client(self, connector: SourceConnector) -> Any: location=_target_config(connector).location) def _principal(self, connector: SourceConnector) -> Principal: - return resolve( - (getattr(connector, 'identity', None), self._identity, - getattr(connector, 'identity_id', None)), - connector=connector, - fallback=(f'A default for sources that name none is also ' - f'accepted, as {self._default_hint}.'), - ) + if isinstance(self._identity, Principal): + return self._identity + raise ValueError( + f"Connector {connector.id!r} needs a Principal passed to its backend. " + "Identity name, ID, and slug lookup is no longer supported.") diff --git a/packages/kumo-bigquery/src/kumo_bigquery/sink.py b/packages/kumo-bigquery/src/kumo_bigquery/sink.py index c7c4fe84f..8cc8d8b06 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/sink.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/sink.py @@ -55,7 +55,7 @@ class BigQuerySinkBackend(_BigQuerySessions): dataset. Args: - identity: A fallback identity for connectors that name none. + identity: Principal used for all connections opened by this backend. staging_uri: Optional ``gs://`` prefix. Output is uploaded under ``/_kumo.export//``, loaded by one job and deleted. Without one, output is streamed through the Storage @@ -64,8 +64,6 @@ class BigQuerySinkBackend(_BigQuerySessions): :meth:`write_modes` offers first. """ - _default_hint = 'BigQuerySinkBackend(identity=identity)' - def __init__(self, identity: Optional[Principal] = None, *, staging_uri: Optional[str] = None, mode: Optional[ReadMode] = None) -> None: diff --git a/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py b/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py index e331ea80e..4d93a9916 100644 --- a/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py +++ b/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py @@ -14,7 +14,7 @@ from .layout import within_root from .object_store import ObjectStoreSourceReader from .object_store_access import ObjectStoreAccess -from .principals import Principal, resolve +from .principals import Principal _KEY_SAFE = "/-._~!$&'()*+,;=:@" @@ -165,11 +165,8 @@ def _destination(self, connector: SourceConnector, return self._filesystem(connector, bucket, region), path def _principal(self, connector: SourceConnector) -> Optional[Principal]: - return resolve( - (getattr(connector, 'identity', None), self._identity, - getattr(connector, 'identity_id', None)), - connector=connector, - fallback=('Leaving the identity unset is also supported, and ' - 'signs with the ambient credential chain.'), - optional=True, - ) + if self._identity is None or isinstance(self._identity, Principal): + return self._identity + raise ValueError( + f"Connector {connector.id!r} needs a Principal passed to its backend. " + "Identity name, ID, and slug lookup is no longer supported.") diff --git a/packages/kumo-core/src/kumo_core/sources/principals.py b/packages/kumo-core/src/kumo_core/sources/principals.py index 069faa022..95cd46f9c 100644 --- a/packages/kumo-core/src/kumo_core/sources/principals.py +++ b/packages/kumo-core/src/kumo_core/sources/principals.py @@ -3,13 +3,11 @@ # SPDX-License-Identifier: Apache-2.0 """Self-contained connection principals with no process-global identity registry.""" -from collections.abc import Sequence from dataclasses import dataclass -from typing import Literal, overload from kumoapi.data_source import IdentityConfig, IdentityCredentials, IdentityType -__all__ = ["Principal", "resolve"] +__all__ = ["Principal"] @dataclass(frozen=True) @@ -30,73 +28,3 @@ class Principal: def type(self) -> IdentityType: """Return the provider selected by this principal's configuration.""" return self.config.type - - -@overload -def resolve( - candidates: Sequence[Principal | None], - *, - connector: object, - fallback: str = "", - optional: Literal[False] = False, -) -> Principal: ... - - -@overload -def resolve( - candidates: Sequence[Principal | None], - *, - connector: object, - fallback: str = "", - optional: Literal[True], -) -> Principal | None: ... - - -@overload -def resolve( - candidates: Sequence[Principal | None], - *, - connector: object, - fallback: str = "", - optional: bool, -) -> Principal | None: ... - - -def resolve( - candidates: Sequence[Principal | None], - *, - connector: object, - fallback: str = "", - optional: bool = False, -) -> Principal | None: - """Select the first supplied connection principal. - - Args: - candidates: Connector principal and backend default, in preference order. - None entries are ignored. Names, IDs, and credential-free metadata - cannot authenticate; a later explicit principal may supply a default. - connector: Connector identifier used in error messages. - fallback: Provider-specific instructions appended to missing-identity errors. - optional: Allow no identity to select ambient authentication. - - Returns: - The first available principal, or None when optional and none was supplied. - - Raises: - ValueError: Supplied references cannot authenticate or an identity is required. - """ - supplied = False - for candidate in candidates: - if candidate is None: - continue - supplied = True - if isinstance(candidate, Principal): - return candidate - if optional and not supplied: - return None - raise ValueError( - f"Connector {getattr(connector, 'id', connector)!r} needs a Principal " - "containing authentication configuration. " - "Identity name, ID, and slug lookup is no longer supported. " - f"{fallback}".rstrip() - ) diff --git a/packages/kumo-core/tests/sources/unit/test_principals.py b/packages/kumo-core/tests/sources/unit/test_principals.py index 498be41c2..71125d887 100644 --- a/packages/kumo-core/tests/sources/unit/test_principals.py +++ b/packages/kumo-core/tests/sources/unit/test_principals.py @@ -1,13 +1,15 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Principals resolve from supplied values without process-local registration.""" +"""Principals carry explicit authentication without registry lookup or fallback.""" import pickle from types import SimpleNamespace +from typing import cast import pytest -from kumo_core.sources.principals import Principal, resolve +from kumo_core.sources.object_store_sessions import ObjectStoreSessions +from kumo_core.sources.principals import Principal from kumoapi.data_source import ( IdentityType, S3AmbientAuthentication, @@ -48,65 +50,48 @@ def test_ambient_principal_needs_no_stored_credentials() -> None: principal = Principal( "ambient", S3IdentityConfig(authentication=S3AmbientAuthentication()), None ) - assert resolve([principal], connector="source") is principal assert principal.type is IdentityType.S3 assert principal.credentials is None -def test_identity_wrappers_require_engine_normalization(principal: Principal) -> None: - """Core accepts connection data rather than inspecting wrapper interfaces.""" - identity = SimpleNamespace(principal=principal) - with pytest.raises(ValueError, match="needs a Principal"): - resolve([identity], connector="source") - - -def test_connector_identity_precedes_backend_default(principal: Principal) -> None: - """Resolution retains caller preference among explicit principals.""" - default = Principal("default", principal.config, principal.credentials) - assert resolve([principal, default], connector="source") is principal - - -def test_supplied_default_can_authenticate_credential_free_metadata( +@pytest.mark.parametrize("connector_identity", [None, "legacy", "other-principal"]) +def test_object_store_uses_only_backend_principal( principal: Principal, + connector_identity: object, ) -> None: - """Hosted connector metadata can be paired with an explicit backend principal.""" - metadata = SimpleNamespace(slug="remote-identity") - assert ( - resolve([metadata, "remote-identity", principal], connector="source") - is principal + """Connector identity metadata cannot override the backend's credentials.""" + other = Principal("other", principal.config, principal.credentials) + connector = SimpleNamespace( + id="source", + identity=other + if connector_identity == "other-principal" + else connector_identity, ) + backend = cast(ObjectStoreSessions, SimpleNamespace(_identity=principal)) + assert ObjectStoreSessions._principal(backend, connector) is principal -@pytest.mark.parametrize("candidates", [[], [None], [None, None]]) -def test_unset_optional_identity_selects_ambient_authentication( - candidates: list[None], + +def test_object_store_without_principal_uses_ambient_authentication( + principal: Principal, ) -> None: - """Ambient authentication is selected only when no identity was supplied.""" - assert resolve(candidates, connector="source", optional=True) is None + """A principal on a connector cannot replace an unset backend principal.""" + connector = SimpleNamespace(id="source", identity=principal) + backend = cast(ObjectStoreSessions, SimpleNamespace(_identity=None)) + + assert ObjectStoreSessions._principal(backend, connector) is None @pytest.mark.parametrize( - "reference", ["name", "identity-id", "", SimpleNamespace(slug="slug")] + "identity", ["name", "identity-id", "", SimpleNamespace(slug="slug")] ) -@pytest.mark.parametrize("optional", [False, True]) -def test_names_and_ids_cannot_silently_select_ambient_authentication( - reference: object, - optional: bool, +def test_invalid_backend_identity_is_rejected( + principal: Principal, + identity: object, ) -> None: - """Removed references raise an actionable error without echoing their contents.""" - with pytest.raises(ValueError, match="lookup is no longer supported"): - resolve([reference], connector="source", optional=optional) - + """Invalid backend credentials fail even when a connector has a principal.""" + connector = SimpleNamespace(id="source", identity=principal) + backend = cast(ObjectStoreSessions, SimpleNamespace(_identity=identity)) -def test_missing_required_identity_reports_provider_instructions() -> None: - """Failures describe direct identity inputs rather than a removed registry.""" - with pytest.raises(ValueError, match="Pass a Principal") as error: - resolve([None], connector="source", fallback="Pass a Principal.") - assert "needs a Principal" in str(error.value) - assert "create_identity" not in str(error.value) - - -def test_invalid_principal_property_is_rejected() -> None: - """Core rejects wrappers regardless of the shape of their principal property.""" - with pytest.raises(ValueError, match="needs a Principal"): - resolve([SimpleNamespace(principal="invalid")], connector="source") + with pytest.raises(ValueError, match="lookup is no longer supported"): + ObjectStoreSessions._principal(backend, connector) diff --git a/packages/kumo-databricks/src/kumo_databricks/backend.py b/packages/kumo-databricks/src/kumo_databricks/backend.py index ce56874b2..2cb83ffa4 100644 --- a/packages/kumo-databricks/src/kumo_databricks/backend.py +++ b/packages/kumo-databricks/src/kumo_databricks/backend.py @@ -57,9 +57,7 @@ class DatabricksSourceBackend(_DatabricksSessions): r"""Resolves source tables by querying Databricks. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. mode: A :class:`~kumo_core.sources.types.ReadMode` to force, when a run needs to know which path it took rather than only that the table was read. ``None`` takes the cheapest the reader offers. @@ -80,8 +78,6 @@ class DatabricksSourceBackend(_DatabricksSessions): source_type = DataSourceType.DATABRICKS - _default_hint = 'DatabricksSourceBackend(identity=identity)' - def __init__( self, identity: Optional[Principal] = None, diff --git a/packages/kumo-databricks/src/kumo_databricks/session.py b/packages/kumo-databricks/src/kumo_databricks/session.py index 22d3c3e62..51451ab62 100644 --- a/packages/kumo-databricks/src/kumo_databricks/session.py +++ b/packages/kumo-databricks/src/kumo_databricks/session.py @@ -20,7 +20,7 @@ from databricks import sql from databricks.sdk import WorkspaceClient from databricks.sql.client import Connection -from kumo_core.sources.principals import Principal, resolve +from kumo_core.sources.principals import Principal from kumoapi.data_source import ( DatabricksAuthenticationKind, DatabricksConnectorResourceConfig, @@ -131,16 +131,9 @@ class _DatabricksSessions: r"""Resolving a connector to a live Databricks SQL connection. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. """ - #: How a subclass spells "supply a default identity" in its own terms. The - #: message resolution raises is the only place a caller learns the - #: constructor to reach for. - _default_hint = '' - def __init__(self, identity: Optional[Principal] = None) -> None: self._identity = identity @@ -186,13 +179,11 @@ def _connected( connection.close() def _principal(self, connector: SourceConnector) -> Principal: - return resolve( - (getattr(connector, 'identity', None), self._identity, - getattr(connector, 'identity_id', None)), - connector=connector, - fallback=(f'A default for sources that name none is also ' - f'accepted, as {self._default_hint}.'), - ) + if isinstance(self._identity, Principal): + return self._identity + raise ValueError( + f"Connector {connector.id!r} needs a Principal passed to its backend. " + "Identity name, ID, and slug lookup is no longer supported.") def table_location(self, connector: SourceConnector, table_name: str) -> str: diff --git a/packages/kumo-databricks/src/kumo_databricks/sink.py b/packages/kumo-databricks/src/kumo_databricks/sink.py index 891f592ab..1e8b70424 100644 --- a/packages/kumo-databricks/src/kumo_databricks/sink.py +++ b/packages/kumo-databricks/src/kumo_databricks/sink.py @@ -148,13 +148,11 @@ class DatabricksSinkBackend(FileStoreRouting, _DatabricksTables): """Writes artifacts to Delta tables, staged through the schema's volume. Args: - identity: Fallback identity for connectors that name none. + identity: Principal used for all connections opened by this backend. """ source_type = DataSourceType.DATABRICKS - _default_hint = 'DatabricksSinkBackend(identity=identity)' - def holds_files(self, connector: SourceConnector, path: str) -> bool: return is_volume_path(path) diff --git a/packages/kumo-engine/test/test_identity.py b/packages/kumo-engine/test/test_identity.py index 363fcb47d..6a433d0ba 100644 --- a/packages/kumo-engine/test/test_identity.py +++ b/packages/kumo-engine/test/test_identity.py @@ -8,14 +8,14 @@ import pytest from kumo.engine.connector.identity import S3Identity -from kumo_core.sources.principals import Principal, resolve +from kumo_core.sources.principals import Principal def test_direct_identity_survives_pickle_without_store() -> None: """Transported convenience identities supply explicit connection principals.""" original = S3Identity(access_key_id="example", secret_access_key="secret") identity = pickle.loads(pickle.dumps(original)) - principal = resolve([identity.principal], connector="s3") + principal = identity.principal assert identity.slug == original.slug assert principal.credentials.secret_access_key.get_secret_value() == "secret" assert "secret" not in repr(identity) @@ -41,19 +41,6 @@ def test_colliding_slugs_do_not_alias_credentials( assert second.principal.credentials.access_key_id.get_secret_value() == "second" -@pytest.mark.parametrize("reference", ["legacy", "legacy-slug", "identity-legacy"]) -def test_legacy_name_and_id_require_explicit_identity(reference: str) -> None: - """Names and IDs cannot select credentials from a removed global registry.""" - with pytest.raises(ValueError, match="lookup is no longer supported"): - resolve([reference], connector="s3", optional=True) - - -def test_core_rejects_unnormalized_engine_identity() -> None: - """Convenience identities are normalized in engine, outside the core API.""" - with pytest.raises(ValueError, match="needs a Principal"): - resolve([S3Identity()], connector="s3") - - @pytest.mark.parametrize("provider", ["s3", "gcs", "bigquery", "databricks"]) def test_source_backends_use_explicit_principals(provider: str) -> None: """Provider authentication paths consume supplied identities without lookup.""" @@ -94,3 +81,17 @@ def test_source_backends_use_explicit_principals(provider: str) -> None: backend._principal(SimpleNamespace(id="remote", identity_id="remote-id")) is principal ) + + other = Principal("other", principal.config, principal.credentials) + assert backend._principal(SimpleNamespace(id="remote", identity=other)) is principal + + backend._identity = None + if provider in {"s3", "gcs"}: + assert backend._principal(connector) is None + else: + with pytest.raises(ValueError, match="needs a Principal"): + backend._principal(connector) + + backend._identity = "legacy" + with pytest.raises(ValueError, match="lookup is no longer supported"): + backend._principal(connector) diff --git a/packages/kumo-gcs/src/kumo_gcs/backend.py b/packages/kumo-gcs/src/kumo_gcs/backend.py index 3f9a34585..380377469 100644 --- a/packages/kumo-gcs/src/kumo_gcs/backend.py +++ b/packages/kumo-gcs/src/kumo_gcs/backend.py @@ -40,9 +40,8 @@ class GCSSessions(ObjectStoreSessions): has gone stale -- see :func:`_live_token`. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. + None selects ambient authentication. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a table contributes. Defaults to Google Cloud Storage; name a compatible service explicitly, or its @@ -122,9 +121,8 @@ class GCSSourceBackend(GCSSessions, ObjectStoreSourceBackend): the shared downloader handles native and SDK transfers. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. + None selects ambient authentication. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a GCS table contributes. Defaults to Google Cloud Storage. diff --git a/packages/kumo-s3/src/kumo_s3/backend.py b/packages/kumo-s3/src/kumo_s3/backend.py index 9af36b937..ef9f9f05e 100644 --- a/packages/kumo-s3/src/kumo_s3/backend.py +++ b/packages/kumo-s3/src/kumo_s3/backend.py @@ -49,9 +49,8 @@ class S3Sessions(ObjectStoreSessions): cannot resolve to two different principals. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. + None selects ambient authentication. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a table contributes. Defaults to ordinary AWS S3; name an S3-compatible service explicitly, or its @@ -158,9 +157,8 @@ class S3SourceBackend(S3Sessions, ObjectStoreSourceBackend): setup. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. + None selects ambient authentication. storage_namespace: The storage system this process reaches, recorded in every graph coordinate an S3 table contributes. Defaults to ordinary AWS S3; name an S3-compatible service explicitly, or its diff --git a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py index d24349f34..31face491 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py @@ -29,7 +29,7 @@ from pathlib import Path from typing import Callable, Dict, List, Optional, Sequence, Tuple, TypeVar -from kumo_core.sources.principals import Principal, resolve +from kumo_core.sources.principals import Principal from kumoapi.plugin import IngestResult, SnapshotStore, _Handle from kumo_snowflake.session import ( @@ -521,10 +521,13 @@ def _session(self) -> SnowflakeSession: borrow a connector's, since a stage location is independent of whatever table happened to be read last. """ - principal = resolve((self.identity,), connector=self.root) - session = _sessions.get(principal, None) - _require_snowpark(session) - return session + if isinstance(self.identity, Principal): + session = _sessions.get(self.identity, None) + _require_snowpark(session) + return session + raise ValueError( + "Stage artifact storage needs a Principal. " + "Identity name, ID, and slug lookup is no longer supported.") def preflight(self) -> None: r"""Validates stage type and effective transfer privileges.""" diff --git a/packages/kumo-snowflake/src/kumo_snowflake/backend.py b/packages/kumo-snowflake/src/kumo_snowflake/backend.py index 193e5fe90..b068fb043 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/backend.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/backend.py @@ -57,9 +57,7 @@ class SnowflakeSourceBackend(_SnowflakeSessions): r"""Resolves source tables by querying Snowflake. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. Example: >>> from kumo_core.sources.principals import Principal @@ -73,8 +71,6 @@ class SnowflakeSourceBackend(_SnowflakeSessions): source_type = DataSourceType.SNOWFLAKE - _default_hint = 'SnowflakeSourceBackend(identity=identity)' - def __init__( self, identity: Optional[Principal] = None, diff --git a/packages/kumo-snowflake/src/kumo_snowflake/session.py b/packages/kumo-snowflake/src/kumo_snowflake/session.py index f499e8cf6..04d50f8a0 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/session.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/session.py @@ -29,7 +29,7 @@ from contextlib import contextmanager from typing import Any, Dict, Iterator, List, Optional, Tuple, TypeAlias, Union -from kumo_core.sources.principals import Principal, resolve +from kumo_core.sources.principals import Principal from kumo_core.sources.sql import resolve_snowflake_identifier from kumoapi.data_source import ( SnowflakeAuthenticationKind, @@ -427,17 +427,9 @@ class _SnowflakeSessions: beside it is the whole reason this class is not written twice. Args: - identity: A fallback Principal for - connectors without their own principal. Names, IDs, and slug-only - metadata cannot authenticate. Omit it to use a connector's identity. + identity: Principal used for all connections opened by this backend. """ - #: How a subclass spells "supply a default identity" in its own terms. The - #: message resolution raises is the only place a caller learns the - #: constructor to reach for, and the reader and the sink are registered - #: under different keyword arguments. - _default_hint = '' - def __init__(self, identity: Optional[Principal] = None) -> None: self._identity = identity @@ -453,13 +445,11 @@ def _session(self, connector: SourceConnector, *, yield _sessions.get(self._principal(connector), connector, fresh=fresh) def _principal(self, connector: SourceConnector) -> Principal: - return resolve( - (getattr(connector, 'identity', None), self._identity, - getattr(connector, 'identity_id', None)), - connector=connector, - fallback=(f'A default for sources that name none is also ' - f'accepted, as {self._default_hint}.'), - ) + if isinstance(self._identity, Principal): + return self._identity + raise ValueError( + f"Connector {connector.id!r} needs a Principal passed to its backend. " + "Identity name, ID, and slug lookup is no longer supported.") def table_location(self, connector: SourceConnector, table_name: str) -> str: diff --git a/packages/kumo-snowflake/src/kumo_snowflake/sink.py b/packages/kumo-snowflake/src/kumo_snowflake/sink.py index 3a5cc0c8f..451f5b172 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/sink.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/sink.py @@ -158,11 +158,9 @@ class SnowflakeSinkBackend(FileStoreRouting, _SnowflakeTables): Table identifiers are written as given, quoted. Args: - identity: Fallback identity for connectors that name none. + identity: Principal used for all connections opened by this backend. """ - _default_hint = 'SnowflakeSinkBackend(identity=identity)' - def holds_files(self, connector, path): """Whether ``path`` names a named internal stage location.""" try: From ea662d8865b2baba41af029e5c07f3e82bbece32 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 19:20:47 +0000 Subject: [PATCH 05/10] Fix import ordering and live sink test indentation --- .../src/kumo_bigquery/backend.py | 25 +++++++++---------- .../src/kumo_bigquery/session.py | 3 +-- .../kumo-bigquery/src/kumo_bigquery/sink.py | 15 ++++++----- .../tests/live/test_live_sink.py | 6 +++-- .../src/kumo_databricks/backend.py | 11 ++++---- .../src/kumo_databricks/sink.py | 10 +++----- .../kumo-engine/kumo/engine/connector/adls.py | 7 +++--- .../kumo-engine/kumo/engine/connector/base.py | 7 +++--- .../kumo/engine/connector/bigquery.py | 5 ++-- .../kumo/engine/connector/databricks.py | 7 +++--- .../kumo-engine/kumo/engine/connector/gcs.py | 7 +++--- .../kumo-engine/kumo/engine/connector/s3.py | 7 +++--- .../kumo/engine/connector/snowflake.py | 7 +++--- .../engine/integrations/_mlflow_target.py | 3 ++- .../kumo-engine/test/test_adls_connector.py | 10 +++++--- .../test/test_bigquery_connector.py | 6 +++-- .../test/test_databricks_connector.py | 5 ++-- packages/kumo-engine/test/test_identity.py | 3 ++- packages/kumo-gcs/src/kumo_gcs/backend.py | 3 +-- packages/kumo-s3/src/kumo_s3/backend.py | 5 ++-- .../src/kumo_snowflake/artifacts.py | 3 +-- .../src/kumo_snowflake/backend.py | 21 ++++++++-------- .../src/kumo_snowflake/session.py | 3 +-- .../kumo-snowflake/src/kumo_snowflake/sink.py | 7 ++---- .../tests/test_artifact_identity.py | 5 +++- 25 files changed, 98 insertions(+), 93 deletions(-) diff --git a/packages/kumo-bigquery/src/kumo_bigquery/backend.py b/packages/kumo-bigquery/src/kumo_bigquery/backend.py index 926925b7a..6175436c5 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/backend.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/backend.py @@ -17,6 +17,18 @@ import logging from typing import Any, List, Mapping, Optional +from kumo_bigquery.session import ( + _BigQuerySessions, + _billing_project, + _clients, + _name, + _qualified, + _rows, + _target_config, +) +from kumo_bigquery.source import BigQuerySourceReader +from kumo_bigquery.sql import QueryPlan, sample_request, table_names +from kumo_bigquery.types import dtype_for, schema_columns from kumo_core.sources.backend import ( ingest_result, sampled_table, @@ -38,19 +50,6 @@ ) from kumoapi.typing import Dtype -from kumo_bigquery.session import ( - _BigQuerySessions, - _billing_project, - _clients, - _name, - _qualified, - _rows, - _target_config, -) -from kumo_bigquery.source import BigQuerySourceReader -from kumo_bigquery.sql import QueryPlan, sample_request, table_names -from kumo_bigquery.types import dtype_for, schema_columns - logger = logging.getLogger(__name__) diff --git a/packages/kumo-bigquery/src/kumo_bigquery/session.py b/packages/kumo-bigquery/src/kumo_bigquery/session.py index e118f3ea6..05a012b12 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/session.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/session.py @@ -18,6 +18,7 @@ import google.auth.transport.requests from google.auth.credentials import Credentials from google.cloud import bigquery, bigquery_storage, storage +from kumo_bigquery.auth import google_credentials from kumo_core.sources.principals import Principal from kumoapi.data_source import ( BigQueryConnectorResourceConfig, @@ -25,8 +26,6 @@ ) from kumoapi.plugin import SourceConnector -from kumo_bigquery.auth import google_credentials - #: What an impersonated token is minted for. The platform uses the same scope #: for BigQuery (``rest/config/identity.py``'s ``_google_scope``), so a local #: read and a platform read reach the same APIs as the same principal. diff --git a/packages/kumo-bigquery/src/kumo_bigquery/sink.py b/packages/kumo-bigquery/src/kumo_bigquery/sink.py index 8cc8d8b06..394d9952d 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/sink.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/sink.py @@ -20,14 +20,6 @@ from functools import partial from typing import Any, Iterator, Mapping, Optional -from kumo_core.sources.diagnostics import translated -from kumo_core.sources.errors import SourceAccessDeniedError -from kumo_core.sources.principals import Principal -from kumo_core.sources.protocol import require_mode, staged_first -from kumo_core.sources.types import Capability, ReadMode -from kumoapi.jobs import WriteMode -from kumoapi.plugin import SourceConnector - from kumo_bigquery import errors, staging, streaming, write from kumo_bigquery.session import ( _BigQuerySessions, @@ -36,6 +28,13 @@ _target_config, ) from kumo_bigquery.staging import StagingLocation +from kumo_core.sources.diagnostics import translated +from kumo_core.sources.errors import SourceAccessDeniedError +from kumo_core.sources.principals import Principal +from kumo_core.sources.protocol import require_mode, staged_first +from kumo_core.sources.types import Capability, ReadMode +from kumoapi.jobs import WriteMode +from kumoapi.plugin import SourceConnector logger = logging.getLogger(__name__) diff --git a/packages/kumo-bigquery/tests/live/test_live_sink.py b/packages/kumo-bigquery/tests/live/test_live_sink.py index b84906986..f8ea10220 100644 --- a/packages/kumo-bigquery/tests/live/test_live_sink.py +++ b/packages/kumo-bigquery/tests/live/test_live_sink.py @@ -223,8 +223,10 @@ def test_append_widens_and_accepts_all_null(client, sink, tmp_path): loaded = sorted( (row.entity, row.score, row.label) for row in client.query(f"SELECT * FROM `{PROJECT}.{DATASET}.{name}`")) - assert [(int(entity), score, label) for entity, score, label in loaded] == [(1, 3.0, None), - (2, 4.0, None)] + assert [(int(entity), score, label) for entity, score, label in loaded] == [ + (1, 3.0, None), + (2, 4.0, None), + ] def test_overwrite_keeps_column_descriptions(client, sink, tmp_path): diff --git a/packages/kumo-databricks/src/kumo_databricks/backend.py b/packages/kumo-databricks/src/kumo_databricks/backend.py index 2cb83ffa4..b3c9741f0 100644 --- a/packages/kumo-databricks/src/kumo_databricks/backend.py +++ b/packages/kumo-databricks/src/kumo_databricks/backend.py @@ -35,6 +35,11 @@ from kumo_core.sources.layout import staging_dir from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode +from kumo_databricks import sql as dbx_sql +from kumo_databricks.catalog import table_names +from kumo_databricks.session import _DatabricksSessions, _target_config +from kumo_databricks.source import DatabricksSourceReader +from kumo_databricks.types import dtype_for from kumoapi.data_source import DataSourceType from kumoapi.plugin import PrepareIngestResult, SourceConnector from kumoapi.source_table import ( @@ -46,12 +51,6 @@ ) from kumoapi.typing import Dtype -from kumo_databricks import sql as dbx_sql -from kumo_databricks.catalog import table_names -from kumo_databricks.session import _DatabricksSessions, _target_config -from kumo_databricks.source import DatabricksSourceReader -from kumo_databricks.types import dtype_for - class DatabricksSourceBackend(_DatabricksSessions): r"""Resolves source tables by querying Databricks. diff --git a/packages/kumo-databricks/src/kumo_databricks/sink.py b/packages/kumo-databricks/src/kumo_databricks/sink.py index 1e8b70424..d69054e7b 100644 --- a/packages/kumo-databricks/src/kumo_databricks/sink.py +++ b/packages/kumo-databricks/src/kumo_databricks/sink.py @@ -27,15 +27,14 @@ import pandas as pd from databricks.sql.client import Connection from kumo_core.object_store_sink import FileStoreRouting -from kumoapi.data_source import DataSourceType -from kumoapi.jobs import WriteMode -from kumoapi.plugin import SourceConnector -from pyarrow.fs import FileSystem - from kumo_databricks.registry import DatabricksModelRegistryMixin from kumo_databricks.session import _target_config from kumo_databricks.volume import is_volume_path, volume_filesystem from kumo_databricks.write import RunVolume +from kumoapi.data_source import DataSourceType +from kumoapi.jobs import WriteMode +from kumoapi.plugin import SourceConnector +from pyarrow.fs import FileSystem class _DatabricksTables(DatabricksModelRegistryMixin): @@ -114,7 +113,6 @@ def write_files(self, connector, table_name, files, from kumo_core.artifact_export import prepared_artifact_file from kumo_core.artifact_staging import selected_local_parquet_files - from kumo_databricks import output, sql, write selected = selected_local_parquet_files(files) diff --git a/packages/kumo-engine/kumo/engine/connector/adls.py b/packages/kumo-engine/kumo/engine/connector/adls.py index 8f63e13c2..946a6437a 100644 --- a/packages/kumo-engine/kumo/engine/connector/adls.py +++ b/packages/kumo-engine/kumo/engine/connector/adls.py @@ -7,9 +7,6 @@ from typing import Optional from urllib.parse import unquote, urlsplit -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import ADLSIdentity from kumoapi.adls import normalize_adls_root_uri from kumoapi.data_source import ( ADLSAnyURIConnectorTarget, @@ -18,6 +15,10 @@ DataSourceType, ) +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import ADLSIdentity + class ADLSConnector(Connector): """Read ADLS Gen2 files and write output beneath a configured root. diff --git a/packages/kumo-engine/kumo/engine/connector/base.py b/packages/kumo-engine/kumo/engine/connector/base.py index 6e801bb01..ba2761165 100644 --- a/packages/kumo-engine/kumo/engine/connector/base.py +++ b/packages/kumo-engine/kumo/engine/connector/base.py @@ -30,13 +30,14 @@ from pathlib import Path from typing import List, Literal, Optional, Union -from kumo.engine._local_schema import FileConnectorConfig, LocalSourceTableType -from kumo.engine._scratch import fingerprint -from kumo.engine.connector.identity import Identity from kumo_core.sources.principals import Principal from kumoapi.data_source import ConnectorResourceConfig, DataSourceType from kumoapi.plugin import ArtifactSink, SourceBackend +from kumo.engine._local_schema import FileConnectorConfig, LocalSourceTableType +from kumo.engine._scratch import fingerprint +from kumo.engine.connector.identity import Identity + class Connector(ABC): r"""Base class for all local-mode connectors. diff --git a/packages/kumo-engine/kumo/engine/connector/bigquery.py b/packages/kumo-engine/kumo/engine/connector/bigquery.py index 61182d38f..24661a96b 100644 --- a/packages/kumo-engine/kumo/engine/connector/bigquery.py +++ b/packages/kumo-engine/kumo/engine/connector/bigquery.py @@ -10,11 +10,12 @@ from functools import cached_property from typing import Optional +from kumoapi.data_source import BigQueryConnectorResourceConfig, DataSourceType +from kumoapi.source_table import BigQuerySourceTable + from kumo.engine.connector._extras import import_provider from kumo.engine.connector.base import Connector from kumo.engine.connector.identity import BigQueryIdentity -from kumoapi.data_source import BigQueryConnectorResourceConfig, DataSourceType -from kumoapi.source_table import BigQuerySourceTable class BigQueryConnector(Connector): diff --git a/packages/kumo-engine/kumo/engine/connector/databricks.py b/packages/kumo-engine/kumo/engine/connector/databricks.py index 7643096a8..ba84ba3d4 100644 --- a/packages/kumo-engine/kumo/engine/connector/databricks.py +++ b/packages/kumo-engine/kumo/engine/connector/databricks.py @@ -10,9 +10,6 @@ from functools import cached_property from typing import Optional -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import DatabricksIdentity from kumoapi.data_source import ( DatabricksConnectorResourceConfig, DataSourceType, @@ -21,6 +18,10 @@ from kumoapi.source_table import DatabricksSourceTable from typing_extensions import Self +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import DatabricksIdentity + class DatabricksConnector(Connector): r"""Connect directly to a Databricks Unity Catalog catalog and schema. diff --git a/packages/kumo-engine/kumo/engine/connector/gcs.py b/packages/kumo-engine/kumo/engine/connector/gcs.py index ff86bfbb1..202f47fa2 100644 --- a/packages/kumo-engine/kumo/engine/connector/gcs.py +++ b/packages/kumo-engine/kumo/engine/connector/gcs.py @@ -14,9 +14,6 @@ from typing import Optional from urllib.parse import urlsplit -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import GCSIdentity from kumoapi.data_source import ( DataSourceType, GCSAnyURIConnectorTarget, @@ -26,6 +23,10 @@ ) from kumoapi.source_table import GCSSourceTable +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import GCSIdentity + def _parse_gcs_root_dir(root_dir: str) -> GCSConnectorTarget: parsed = urlsplit(root_dir) diff --git a/packages/kumo-engine/kumo/engine/connector/s3.py b/packages/kumo-engine/kumo/engine/connector/s3.py index d4d53c61c..3cd8be66b 100644 --- a/packages/kumo-engine/kumo/engine/connector/s3.py +++ b/packages/kumo-engine/kumo/engine/connector/s3.py @@ -18,9 +18,6 @@ class lives in the cloud SDK package, which this package does not depend on; from typing import Optional from urllib.parse import urlsplit -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import S3Identity from kumoapi.data_source import ( DataSourceType, S3AnyURIConnectorTarget, @@ -30,6 +27,10 @@ class lives in the cloud SDK package, which this package does not depend on; ) from kumoapi.source_table import S3SourceTable +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import S3Identity + def _parse_s3_root_dir(root_dir: str, region: Optional[str]) -> S3ConnectorTarget: diff --git a/packages/kumo-engine/kumo/engine/connector/snowflake.py b/packages/kumo-engine/kumo/engine/connector/snowflake.py index 9092c05f9..1249aadaf 100644 --- a/packages/kumo-engine/kumo/engine/connector/snowflake.py +++ b/packages/kumo-engine/kumo/engine/connector/snowflake.py @@ -13,9 +13,6 @@ from pathlib import Path from typing import Any, Dict, List, Optional -from kumo.engine.connector._extras import import_provider -from kumo.engine.connector.base import Connector -from kumo.engine.connector.identity import SnowflakeIdentity from kumoapi.data_source import ( DataSourceType, SnowflakeConnectorResourceConfig, @@ -24,6 +21,10 @@ from kumoapi.source_table import SnowflakeSourceTable from typing_extensions import Self +from kumo.engine.connector._extras import import_provider +from kumo.engine.connector.base import Connector +from kumo.engine.connector.identity import SnowflakeIdentity + #: Warehouse/database/schema environment variables Snowpark Container #: Services exports alongside the account/host `kumo_snowflake.spcs` already #: reads (https://docs.snowflake.com/en/developer-guide/snowpark-container- diff --git a/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py b/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py index 7ac162ab5..e08c4a955 100644 --- a/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py +++ b/packages/kumo-engine/kumo/engine/integrations/_mlflow_target.py @@ -233,9 +233,10 @@ def _databricks_token(client: Any) -> Iterator[None]: def _sagemaker(target: SageMakerMLflow) -> Target: - from kumo.engine.connector import S3Connector from kumoapi.data_source import S3AmbientAuthentication + from kumo.engine.connector import S3Connector + arn = target.tracking_server_arn assets = S3Connector(identity=target.identity) principal = _principal(target.identity) diff --git a/packages/kumo-engine/test/test_adls_connector.py b/packages/kumo-engine/test/test_adls_connector.py index d1a84089d..892bb1815 100644 --- a/packages/kumo-engine/test/test_adls_connector.py +++ b/packages/kumo-engine/test/test_adls_connector.py @@ -11,9 +11,6 @@ import pyarrow as pa import pyarrow.parquet as pq import pytest -from kumo.engine import ADLSConnector, ADLSIdentity, Table -from kumo.engine._portable import _source_table_name, portable_graph_config -from kumo.engine.trainer._scoring import ScoringDefaults from kumo_core.sources.object_store_access import ObjectStoreAccess from kumoapi.data_source import AzureCloud, DataSourceType from kumoapi.jobs import PredictionArtifactType, WriteMode @@ -21,6 +18,10 @@ from kumoapi.source_table import ADLSRelativeSource, ADLSSourceTable from pyarrow.fs import LocalFileSystem, SubTreeFileSystem +from kumo.engine import ADLSConnector, ADLSIdentity, Table +from kumo.engine._portable import _source_table_name, portable_graph_config +from kumo.engine.trainer._scoring import ScoringDefaults + ROOT = 'abfss://curated@companylake.dfs.core.windows.net/orders/' @@ -128,9 +129,10 @@ def test_rootless_graph_coordinate_contains_exact_source(storage): def test_invalid_prediction_output_fails_before_scoring(monkeypatch, tmp_path, snapshot, case, error, match): - from kumo.engine import PredictionOutputConfig, PredictionTable, Trainer from kumo_core.types import TaskType + from kumo.engine import PredictionOutputConfig, PredictionTable, Trainer + monkeypatch.setenv('AZURE_TENANT_ID', 'tenant') monkeypatch.setenv('AZURE_CLIENT_ID', 'client') monkeypatch.setenv('AZURE_FEDERATED_TOKEN_FILE', '/projected/token') diff --git a/packages/kumo-engine/test/test_bigquery_connector.py b/packages/kumo-engine/test/test_bigquery_connector.py index 7bbbc3ea4..952f911f5 100644 --- a/packages/kumo-engine/test/test_bigquery_connector.py +++ b/packages/kumo-engine/test/test_bigquery_connector.py @@ -3,9 +3,10 @@ # SPDX-License-Identifier: Apache-2.0 import pytest +from kumo_core.sources.types import ReadMode + from kumo.engine.connector.bigquery import BigQueryConnector from kumo.engine.connector.identity import BigQueryIdentity -from kumo_core.sources.types import ReadMode @pytest.mark.parametrize( @@ -67,9 +68,10 @@ def test_sink_backend_is_cached_and_carries_configuration(): def test_fit_rejects_model_export_to_bigquery_up_front(): + from kumoapi.model_plan import ModelPlan + from kumo.engine.trainer.output_config import ModelOutputConfig from kumo.engine.trainer.trainer import Trainer - from kumoapi.model_plan import ModelPlan connector = BigQueryConnector(project_id='data-project', dataset_id='analytics') diff --git a/packages/kumo-engine/test/test_databricks_connector.py b/packages/kumo-engine/test/test_databricks_connector.py index 254d934e8..15fd53020 100644 --- a/packages/kumo-engine/test/test_databricks_connector.py +++ b/packages/kumo-engine/test/test_databricks_connector.py @@ -3,11 +3,12 @@ # SPDX-License-Identifier: Apache-2.0 import pytest -from kumo.engine.connector.databricks import DatabricksConnector -from kumo.engine.connector.identity import DatabricksIdentity from kumo_core.sources.types import ReadMode from kumoapi.data_source import DatabricksAuthenticationKind +from kumo.engine.connector.databricks import DatabricksConnector +from kumo.engine.connector.identity import DatabricksIdentity + @pytest.mark.parametrize( 'staging_volume_path, require_staged, expected_mode', diff --git a/packages/kumo-engine/test/test_identity.py b/packages/kumo-engine/test/test_identity.py index 6a433d0ba..06dd7be54 100644 --- a/packages/kumo-engine/test/test_identity.py +++ b/packages/kumo-engine/test/test_identity.py @@ -7,9 +7,10 @@ import uuid import pytest -from kumo.engine.connector.identity import S3Identity from kumo_core.sources.principals import Principal +from kumo.engine.connector.identity import S3Identity + def test_direct_identity_survives_pickle_without_store() -> None: """Transported convenience identities supply explicit connection principals.""" diff --git a/packages/kumo-gcs/src/kumo_gcs/backend.py b/packages/kumo-gcs/src/kumo_gcs/backend.py index 380377469..44e770a9a 100644 --- a/packages/kumo-gcs/src/kumo_gcs/backend.py +++ b/packages/kumo-gcs/src/kumo_gcs/backend.py @@ -11,6 +11,7 @@ ) from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode +from kumo_gcs.session import GCS_NAMESPACE, _gcs_session_for, _live_token from kumoapi.data_source import ( DataSourceType, GCSConnectorResourceConfig, @@ -27,8 +28,6 @@ ) from pyarrow import fs -from kumo_gcs.session import GCS_NAMESPACE, _gcs_session_for, _live_token - class GCSSessions(ObjectStoreSessions): r"""Resolving a connector and a table name to a reader over a live bucket. diff --git a/packages/kumo-s3/src/kumo_s3/backend.py b/packages/kumo-s3/src/kumo_s3/backend.py index ef9f9f05e..c7419ad0e 100644 --- a/packages/kumo-s3/src/kumo_s3/backend.py +++ b/packages/kumo-s3/src/kumo_s3/backend.py @@ -3,6 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 from typing import Any, Optional, Union +import kumo_s3 from kumo_core.sources.errors import ReconnectRequiredError from kumo_core.sources.object_store_access import ObjectStoreAccess from kumo_core.sources.object_store_backend import ObjectStoreSourceBackend @@ -12,6 +13,7 @@ ) from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode +from kumo_s3.session import anonymous_filesystem, arrow_connection_options from kumoapi.data_source import ( DataSourceType, S3AccessKeyAuthentication, @@ -33,9 +35,6 @@ from pyarrow.fs import S3FileSystem from pydantic import SecretStr -import kumo_s3 -from kumo_s3.session import anonymous_filesystem, arrow_connection_options - #: What an S3 identity resolves to: a ready filesystem, or a #: ``boto3.session.Session`` whose resolved credentials are read off it. S3Session = Union[S3FileSystem, Any] diff --git a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py index 31face491..a6b11adc5 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py @@ -30,8 +30,6 @@ from typing import Callable, Dict, List, Optional, Sequence, Tuple, TypeVar from kumo_core.sources.principals import Principal -from kumoapi.plugin import IngestResult, SnapshotStore, _Handle - from kumo_snowflake.session import ( SnowflakeSession, _quoted_literal, @@ -40,6 +38,7 @@ _sessions, resolved, ) +from kumoapi.plugin import IngestResult, SnapshotStore, _Handle _Item = TypeVar('_Item') _Result = TypeVar('_Result') diff --git a/packages/kumo-snowflake/src/kumo_snowflake/backend.py b/packages/kumo-snowflake/src/kumo_snowflake/backend.py index b068fb043..5a73078e1 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/backend.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/backend.py @@ -30,17 +30,6 @@ from kumo_core.sources.layout import staging_dir from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode -from kumoapi.data_source import DataSourceType -from kumoapi.plugin import PrepareIngestResult, SourceConnector -from kumoapi.source_table import ( - SnowflakeSourceTable, - SourceColumn, - SourceTableConfigResponse, - SourceTableDataResponse, - SourceTableListResponse, -) -from kumoapi.typing import Dtype - from kumo_snowflake.session import ( SnowflakeSession, _require_snowpark, @@ -51,6 +40,16 @@ from kumo_snowflake.source import SnowflakeSourceReader from kumo_snowflake.sql import describe_columns from kumo_snowflake.types import dtype_for +from kumoapi.data_source import DataSourceType +from kumoapi.plugin import PrepareIngestResult, SourceConnector +from kumoapi.source_table import ( + SnowflakeSourceTable, + SourceColumn, + SourceTableConfigResponse, + SourceTableDataResponse, + SourceTableListResponse, +) +from kumoapi.typing import Dtype class SnowflakeSourceBackend(_SnowflakeSessions): diff --git a/packages/kumo-snowflake/src/kumo_snowflake/session.py b/packages/kumo-snowflake/src/kumo_snowflake/session.py index 04d50f8a0..eee0ddf21 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/session.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/session.py @@ -31,6 +31,7 @@ from kumo_core.sources.principals import Principal from kumo_core.sources.sql import resolve_snowflake_identifier +from kumo_snowflake.keys import load_private_key, private_key_bytes from kumoapi.data_source import ( SnowflakeAuthenticationKind, SnowflakeConnectorResourceConfig, @@ -42,8 +43,6 @@ from pydantic import SecretStr from snowflake.snowpark import Session -from kumo_snowflake.keys import load_private_key, private_key_bytes - #: What this module builds and hands upward. SnowflakeSession: TypeAlias = Session diff --git a/packages/kumo-snowflake/src/kumo_snowflake/sink.py b/packages/kumo-snowflake/src/kumo_snowflake/sink.py index 451f5b172..ace2e55cf 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/sink.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/sink.py @@ -14,9 +14,6 @@ import numpy as np import pandas as pd from kumo_core.object_store_sink import FileStoreRouting -from kumoapi.jobs import WriteMode -from kumoapi.plugin import SourceConnector - from kumo_snowflake.artifacts import _split_stage_location from kumo_snowflake.errors import is_lapsed_credential from kumo_snowflake.registry import SnowflakeModelRegistryMixin @@ -27,6 +24,8 @@ _target_config, resolved, ) +from kumoapi.jobs import WriteMode +from kumoapi.plugin import SourceConnector # Snowflake ARRAY and VARIANT are acquired as JSON strings, so nested # predictions cannot round-trip as typed lists or mappings. NumPy arrays @@ -123,7 +122,6 @@ def write_files(self, connector, table_name, files, """COPY selected Parquet into a table.""" del project_id, export_id from kumo_core.artifact_staging import selected_local_parquet_files - from kumo_snowflake.write import export_table_files selected = [str(path) for path in selected_local_parquet_files(files)] @@ -228,7 +226,6 @@ def write_artifacts_to_table(self, table_name, artifact_path, replace=False, from functools import partial from kumo_core.artifact_export import prepared_artifact_file - from kumo_snowflake.write import ( _upload_local_parquet_to_user_stage, write_artifacts_to_table, diff --git a/packages/kumo-snowflake/tests/test_artifact_identity.py b/packages/kumo-snowflake/tests/test_artifact_identity.py index 7fb242c12..be9f14067 100644 --- a/packages/kumo-snowflake/tests/test_artifact_identity.py +++ b/packages/kumo-snowflake/tests/test_artifact_identity.py @@ -11,7 +11,10 @@ import pytest from kumo_core.sources.principals import Principal -from kumoapi.data_source import SnowflakeAuthenticationKind, SnowflakeIdentityConfig +from kumoapi.data_source import ( + SnowflakeAuthenticationKind, + SnowflakeIdentityConfig, +) @pytest.fixture From ddaa097442f453e52564325beb0bc3d5b4dc94f2 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 20:02:06 +0000 Subject: [PATCH 06/10] Own Snowflake and BigQuery connections per engine connector --- .../src/kumo_bigquery/__init__.py | 6 +- .../src/kumo_bigquery/backend.py | 12 +- .../src/kumo_bigquery/session.py | 192 ++++---- .../kumo-bigquery/src/kumo_bigquery/sink.py | 15 +- .../tests/live/test_live_sink.py | 15 +- .../kumo-bigquery/tests/test_connection.py | 144 ++++++ packages/kumo-bigquery/tests/test_sink.py | 4 +- packages/kumo-core/README.md | 12 + .../src/kumo_core/sources/principals.py | 2 +- .../kumo/engine/connector/bigquery.py | 18 +- .../kumo/engine/connector/snowflake.py | 16 +- .../test/test_connector_connections.py | 110 +++++ packages/kumo-engine/test/test_identity.py | 14 +- .../test/test_snowflake_connector.py | 4 +- .../src/kumo_snowflake/__init__.py | 6 +- .../src/kumo_snowflake/artifacts.py | 418 +----------------- .../src/kumo_snowflake/backend.py | 6 +- .../src/kumo_snowflake/session.py | 143 +++--- .../src/kumo_snowflake/stage_fs.py | 2 +- .../tests/test_artifact_identity.py | 64 --- .../kumo-snowflake/tests/test_connection.py | 155 +++++++ packages/kumo-snowflake/tests/test_sink.py | 23 +- 22 files changed, 681 insertions(+), 700 deletions(-) create mode 100644 packages/kumo-bigquery/tests/test_connection.py create mode 100644 packages/kumo-engine/test/test_connector_connections.py delete mode 100644 packages/kumo-snowflake/tests/test_artifact_identity.py create mode 100644 packages/kumo-snowflake/tests/test_connection.py diff --git a/packages/kumo-bigquery/src/kumo_bigquery/__init__.py b/packages/kumo-bigquery/src/kumo_bigquery/__init__.py index ecccc7871..552714f02 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/__init__.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/__init__.py @@ -7,9 +7,8 @@ :class:`BigQuerySourceReader` implements ``kumo_core``'s ``SourceReader`` and is what the platform binds through. :class:`BigQuerySourceBackend` implements :class:`kumoapi.plugin.SourceBackend` and is what a ``LocalBackend`` registers -for ``DataSourceType.BIGQUERY``; the identity lifecycle beside it is the rest -of that plugin; it is in ``backend.py``, not ``source.py``, because that name -is already the platform reader's. :class:`BigQuerySinkBackend` writes +for ``DataSourceType.BIGQUERY``. It is in ``backend.py``, not ``source.py``, +because that name is already the platform reader's. :class:`BigQuerySinkBackend` writes prediction output. Nothing here imports ``kumoai_studio``. That is what lets one distribution serve @@ -33,7 +32,6 @@ _LAZY_EXPORTS = { "BigQuerySinkBackend": "sink", "BigQuerySourceBackend": "backend", - "close": "session", "probe": "session", } diff --git a/packages/kumo-bigquery/src/kumo_bigquery/backend.py b/packages/kumo-bigquery/src/kumo_bigquery/backend.py index 6175436c5..0d4de7a79 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/backend.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/backend.py @@ -18,9 +18,9 @@ from typing import Any, List, Mapping, Optional from kumo_bigquery.session import ( + BigQueryConnection, _BigQuerySessions, _billing_project, - _clients, _name, _qualified, _rows, @@ -58,6 +58,7 @@ class BigQuerySourceBackend(_BigQuerySessions): Args: identity: Principal used for all connections opened by this backend. + connection: Connector-owned clients; supply instead of identity. mode: The read mode every table is read under, or ``None`` to take whichever the reader offers first. staging_uri: A ``gs://`` prefix this run may export Parquet to. Without @@ -81,8 +82,10 @@ def __init__( identity: Optional[Principal] = None, mode: Optional[ReadMode] = None, staging_uri: Optional[str] = None, + *, + connection: Optional[BigQueryConnection] = None, ) -> None: - super().__init__(identity) + super().__init__(identity, connection=connection) self.mode = mode self.staging_uri = staging_uri @@ -264,16 +267,15 @@ def _reader(self, connector: SourceConnector) -> BigQuerySourceReader: r"""Built per call: the reader is a thin wrapper and cheap to build, even though the clients it wraps are now cached. """ - principal = self._principal(connector) credentials = self._credentials(connector) billing = _billing_project(connector) - storage = (_clients.storage_client(principal, project=billing) + storage = (self._connection.storage_client(project=billing) if self.staging_uri is not None else None) return BigQuerySourceReader( self._client(connector), project=_target_config(connector).project_id, dataset=_target_config(connector).dataset_id, - read_client=_clients.read_client(principal), + read_client=self._connection.read_client(), storage_client=storage, staging_uri=self.staging_uri, billing_project=_target_config(connector).billing_project_id, diff --git a/packages/kumo-bigquery/src/kumo_bigquery/session.py b/packages/kumo-bigquery/src/kumo_bigquery/session.py index 05a012b12..c7e49e0e1 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/session.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/session.py @@ -12,8 +12,11 @@ at all did not already cost. """ +from __future__ import annotations + import threading -from typing import Any, Dict, List, Optional, Tuple +from contextlib import ExitStack +from typing import Any, List import google.auth.transport.requests from google.auth.credentials import Credentials @@ -97,7 +100,7 @@ def probe(principal: Principal) -> None: r"""Proves an identity can authenticate. Half of the ``kumoai_studio.identities`` lifecycle. Deliberately not cached, and - not routed through :data:`_clients`: this is asked when a caller wants to + not routed through a connector: this is asked when a caller wants to know whether the credentials work *now*. """ credentials = _credentials_for(principal) @@ -105,22 +108,6 @@ def probe(principal: Principal) -> None: credentials.refresh(google.auth.transport.requests.Request()) -def close(identity_name: Optional[str] = None) -> None: - r"""Drops the cached clients built for :obj:`identity_name`, or all of - them. - - The other half of the ``kumoai_studio.identities`` lifecycle. A client built from - :data:`_clients` carries the credentials it was resolved from, so - rotating or deleting the identity underneath it must drop the client too - -- otherwise a rotated credential's caller would keep talking to BigQuery - as the identity that no longer exists, through a client already built - from the old material. There is nothing to close on a BigQuery client - itself; forgetting it is enough, and the next call rebuilds one from - whatever the identity now resolves to. - """ - _clients.close(identity_name) - - def _query_client(credentials: Credentials, *, project: str, location: str) -> Any: r"""``location`` is the connector's, because a job submitted without one @@ -143,94 +130,103 @@ def _storage_client(credentials: Credentials, *, project: str) -> Any: return storage.Client(credentials=credentials, project=project) -class _ClientCache: - r"""The BigQuery clients :func:`_query_client`, :func:`_read_client`, - :func:`_write_client` and :func:`_storage_client` build, by identity and - target. - - Module-level rather than per backend, for the reason - :class:`kumo_snowflake.session._SessionCache` is: a reader and a writer - over the same connector must not resolve to two different clients, and a - default backend instance is thrown away and rebuilt more often than the - identity it authenticates as changes. +class BigQueryConnection: + """Own lazy Google clients for one connector's authentication. - Keyed on ``(identity, project, location)`` rather than holding the - resolved credentials object the way an earlier version of this module - did: caching the credentials alone and rebuilding a client from them on - every call is not caching the client at all, and a client is what this - module is actually asked for on every read. + Args: + identity: Explicit principal used to authenticate every client. - Calls the module-level builders by name rather than inlining the - client construction, so a caller can still replace one of them (a test - stands in a fake client this way) and have every path that resolves a - client -- cached or not -- see the replacement. + Pickling retains only the principal; clients and locks are worker-local. """ - def __init__(self) -> None: + + def __init__(self, identity: Principal | None) -> None: + self._identity = identity self._lock = threading.RLock() - self._query: Dict[Tuple[str, ...], Any] = {} - self._read: Dict[str, Any] = {} - self._write: Dict[str, Any] = {} - self._storage: Dict[Tuple[str, ...], Any] = {} - - def query_client(self, principal: Principal, *, project: str, - location: str) -> Any: - key = (principal.name, project, location) + self._query: dict[tuple[str, str], Any] = {} + self._read: Any = None + self._write: Any = None + self._storage: dict[str, Any] = {} + + @property + def identity(self) -> Principal | None: + """Return the principal bound to this connection owner.""" + return self._identity + + def __reduce__( + self, + ) -> tuple[type[BigQueryConnection], tuple[Principal | None]]: + """Serialize authentication without live Google clients or locks.""" + return type(self), (self.identity,) + + def credentials(self) -> Credentials: + """Build credentials from this connection's explicit principal. + + Returns: + Google authentication credentials. + + Raises: + ValueError: The principal config is invalid for BigQuery. + TypeError: The principal is absent or credentials are unsupported. + """ + if not isinstance(self.identity, Principal): + raise TypeError( + "BigQuery backend needs a Principal containing " + "authentication configuration.") + credentials = _credentials_for(self.identity) + _require_credentials(credentials) + return credentials + + def query_client(self, *, project: str, location: str) -> Any: + """Return the cached query client for the given billing project and region.""" + key = (project, location) with self._lock: client = self._query.get(key) if client is None: - credentials = _credentials_for(principal) - _require_credentials(credentials) - client = _query_client(credentials, project=project, + client = _query_client(self.credentials(), project=project, location=location) self._query[key] = client return client - def read_client(self, principal: Principal) -> Any: + def read_client(self) -> Any: + """Return this connection's cached Storage Read API client.""" with self._lock: - client = self._read.get(principal.name) - if client is None: - credentials = _credentials_for(principal) - _require_credentials(credentials) - client = _read_client(credentials) - self._read[principal.name] = client - return client + if self._read is None: + self._read = _read_client(self.credentials()) + return self._read - def write_client(self, principal: Principal) -> Any: + def write_client(self) -> Any: + """Return this connection's cached Storage Write API client.""" with self._lock: - client = self._write.get(principal.name) - if client is None: - credentials = _credentials_for(principal) - _require_credentials(credentials) - client = _write_client(credentials) - self._write[principal.name] = client - return client + if self._write is None: + self._write = _write_client(self.credentials()) + return self._write - def storage_client(self, principal: Principal, *, project: str) -> Any: - key = (principal.name, project) + def storage_client(self, *, project: str) -> Any: + """Return the cached Cloud Storage client for the given billing project.""" with self._lock: - client = self._storage.get(key) + client = self._storage.get(project) if client is None: - credentials = _credentials_for(principal) - _require_credentials(credentials) - client = _storage_client(credentials, project=project) - self._storage[key] = client + client = _storage_client(self.credentials(), project=project) + self._storage[project] = client return client - def close(self, name: Optional[str] = None) -> None: - with self._lock: - for cache in (self._query, self._storage): - for key in [ - key for key in cache if name is None or key[0] == name - ]: - del cache[key] - for client_cache in (self._read, self._write): - for client_name in [ - key for key in client_cache if name is None or key == name - ]: - del client_cache[client_name] - + def close(self) -> None: + """Forget and close every owned client; subsequent calls reopen them. -_clients = _ClientCache() + Raises: + Exception: A client fails to close, after all closes run. + """ + with self._lock, ExitStack() as cleanup: + clients = [*self._query.values(), *self._storage.values()] + if self._read is not None: + clients.append(self._read) + if self._write is not None: + clients.append(self._write) + self._query.clear() + self._storage.clear() + self._read = self._write = None + for client in clients: + cleanup.callback(client.close) def _rows(client: Any, sql: str, job_config: Any = None) -> List[Any]: @@ -249,10 +245,20 @@ class _BigQuerySessions: Args: identity: Principal used for all connections opened by this backend. + connection: Connector-owned clients shared with its other backend. + Supply this instead of identity. """ - def __init__(self, identity: Optional[Principal] = None) -> None: - self._identity = identity + def __init__(self, identity: Principal | None = None, *, + connection: BigQueryConnection | None = None) -> None: + if identity is not None and connection is not None: + raise ValueError("Pass identity or connection, not both.") + self._connection = (connection if connection is not None + else BigQueryConnection(identity)) + + @property + def _identity(self) -> Principal | None: + return self._connection.identity def _credentials(self, connector: SourceConnector) -> Credentials: r"""Raw credentials for a connector, for the one caller that needs @@ -267,17 +273,17 @@ def _credentials(self, connector: SourceConnector) -> Credentials: imported ``_credentials_for`` directly would keep its own binding of the original function and miss the replacement. """ - credentials = _credentials_for(self._principal(connector)) - _require_credentials(credentials) - return credentials + self._principal(connector) + return self._connection.credentials() def table_location(self, connector: SourceConnector, table_name: str) -> str: return _name(connector, table_name) def _client(self, connector: SourceConnector) -> Any: - return _clients.query_client( - self._principal(connector), project=_billing_project(connector), + self._principal(connector) + return self._connection.query_client( + project=_billing_project(connector), location=_target_config(connector).location) def _principal(self, connector: SourceConnector) -> Principal: diff --git a/packages/kumo-bigquery/src/kumo_bigquery/sink.py b/packages/kumo-bigquery/src/kumo_bigquery/sink.py index 394d9952d..48895b817 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/sink.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/sink.py @@ -22,9 +22,9 @@ from kumo_bigquery import errors, staging, streaming, write from kumo_bigquery.session import ( + BigQueryConnection, _BigQuerySessions, _billing_project, - _clients, _target_config, ) from kumo_bigquery.staging import StagingLocation @@ -55,6 +55,7 @@ class BigQuerySinkBackend(_BigQuerySessions): Args: identity: Principal used for all connections opened by this backend. + connection: Connector-owned clients; supply instead of identity. staging_uri: Optional ``gs://`` prefix. Output is uploaded under ``/_kumo.export//``, loaded by one job and deleted. Without one, output is streamed through the Storage @@ -65,10 +66,11 @@ class BigQuerySinkBackend(_BigQuerySessions): def __init__(self, identity: Optional[Principal] = None, *, staging_uri: Optional[str] = None, - mode: Optional[ReadMode] = None) -> None: + mode: Optional[ReadMode] = None, + connection: Optional[BigQueryConnection] = None) -> None: if mode is ReadMode.STAGED and not staging_uri: raise ValueError('mode=STAGED needs a staging_uri') - super().__init__(identity) + super().__init__(identity, connection=connection) self.staging_uri = staging_uri self.mode = mode self._staging = (StagingLocation.parse(staging_uri) @@ -135,7 +137,7 @@ def write_files( extra_columns=extra_columns) else: write.streamed_write( - client, _clients.write_client(self._principal(connector)), + client, self._connection.write_client(), selected, ref, replace=replace, existing=existing, extra_columns=extra_columns, credentials=self._credentials(connector)) @@ -174,7 +176,7 @@ def _probe_stream(self, connector: SourceConnector, ref: str) -> None: from google.api_core.exceptions import Forbidden from google.cloud import bigquery - write_client = _clients.write_client(self._principal(connector)) + write_client = self._connection.write_client() table = bigquery.TableReference.from_string(ref) try: streaming.probe_write_stream( @@ -189,8 +191,7 @@ def _probe_stream(self, connector: SourceConnector, ref: str) -> None: f'staging_uri.', table=ref) from None def _storage(self, connector: SourceConnector) -> Any: - return _clients.storage_client(self._principal(connector), - project=_billing_project(connector)) + return self._connection.storage_client(project=_billing_project(connector)) def probe_staging(self, connector: SourceConnector) -> Capability: """As :meth:`BigQuerySourceReader.probe_staging`: answered once and diff --git a/packages/kumo-bigquery/tests/live/test_live_sink.py b/packages/kumo-bigquery/tests/live/test_live_sink.py index f8ea10220..5aedab7ba 100644 --- a/packages/kumo-bigquery/tests/live/test_live_sink.py +++ b/packages/kumo-bigquery/tests/live/test_live_sink.py @@ -90,8 +90,8 @@ def client(): @pytest.fixture(params=["staged", "streamed"]) def sink(request): if request.param == "streamed": - return BigQuerySinkBackend() - return BigQuerySinkBackend(staging_uri=STAGING_URI, mode=ReadMode.STAGED) + return BigQuerySinkBackend(identity=IDENTITY) + return BigQuerySinkBackend(identity=IDENTITY, staging_uri=STAGING_URI, mode=ReadMode.STAGED) def staged_objects(): @@ -281,9 +281,8 @@ def test_failed_load_leaves_table(client, sink, tmp_path, mode): def test_extra_columns_are_stamped(client, tmp_path): name = f"preds_{uuid.uuid4().hex[:6]}" - BigQuerySinkBackend().write_files(connector(), name, - shards(tmp_path, [2, 3]), - extra_columns={"RUN": "r1"}) + BigQuerySinkBackend(identity=IDENTITY).write_files( + connector(), name, shards(tmp_path, [2, 3]), extra_columns={"RUN": "r1"}) values = { row.RUN for row in client.query( @@ -311,7 +310,7 @@ def test_preflight_accepts_writable_destination(client, sink, tmp_path): def test_preflight_rejects_unusable_destinations(client): - sink = BigQuerySinkBackend() + sink = BigQuerySinkBackend(identity=IDENTITY) with pytest.raises(SourceNotFoundError, match="does not exist"): sink.preflight_write_files(connector(dataset=f"missing_{RUN}"), "preds") with pytest.raises(SourceNotFoundError, match="does not exist"): @@ -326,9 +325,9 @@ def test_preflight_rejects_unusable_destinations(client): sink.preflight_write_files(connector(), "other.preds") denied = "gs://gcp-public-data-landsat/kumo" with pytest.raises(UnsupportedReadModeError, match="offers streamed"): - BigQuerySinkBackend(staging_uri=denied, mode=ReadMode.STAGED).\ + BigQuerySinkBackend(identity=IDENTITY, staging_uri=denied, mode=ReadMode.STAGED).\ preflight_write_files(connector(), "preds") - fallback = BigQuerySinkBackend(staging_uri=denied) + fallback = BigQuerySinkBackend(identity=IDENTITY, staging_uri=denied) fallback.preflight_write_files(connector(), "preds") assert fallback.write_modes(connector()) == (ReadMode.STREAMED, ) with pytest.raises(NotFound): diff --git a/packages/kumo-bigquery/tests/test_connection.py b/packages/kumo-bigquery/tests/test_connection.py new file mode 100644 index 000000000..f8b2a4d34 --- /dev/null +++ b/packages/kumo-bigquery/tests/test_connection.py @@ -0,0 +1,144 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Connector-owned Google clients isolate authentication and worker state.""" + +import pickle +from concurrent.futures import ThreadPoolExecutor +from unittest.mock import Mock + +import pytest +from kumo_bigquery import session +from kumo_bigquery.backend import BigQuerySourceBackend +from kumo_bigquery.sink import BigQuerySinkBackend +from kumo_core.sources.principals import Principal +from kumoapi.data_source import ( + BigQueryIdentityConfig, + GoogleServiceAccountKeyAuthentication, + GoogleServiceAccountKeyCredentials, +) + + +@pytest.fixture +def principals() -> tuple[Principal, Principal]: + """Supply different credentials and accounts under the same display name.""" + + def principal(index: int) -> Principal: + return Principal( + "shared-name", + BigQueryIdentityConfig( + authentication=GoogleServiceAccountKeyAuthentication( + project_id="sample-project", + client_email=f"reader{index}@sample-project.iam.gserviceaccount.com", + client_id=str(index), + auth_uri="https://accounts.google.com/o/oauth2/auth", + token_uri="https://oauth2.googleapis.com/token", + ) + ), + GoogleServiceAccountKeyCredentials( + private_key_id=f"key-{index}", private_key=f"unused-{index}" + ), + ) + + return principal(1), principal(2) + + +@pytest.mark.parametrize("kind", ["query", "read", "write", "storage"]) +def test_clients_are_reused_only_within_their_owner( + monkeypatch: pytest.MonkeyPatch, + principals: tuple[Principal, Principal], + kind: str, +) -> None: + """Same-name principals never reuse another connector's authenticated client.""" + credentials = [Mock(token="first"), Mock(token="second")] + resolve = Mock(side_effect=credentials) + build = Mock(side_effect=lambda credential, **_: Mock(credentials=credential)) + monkeypatch.setattr(session, "_credentials_for", resolve) + monkeypatch.setattr(session, f"_{kind}_client", build) + first = session.BigQueryConnection(principals[0]) + second = session.BigQueryConnection(principals[1]) + options = {"project": "sample-project"} if kind in {"query", "storage"} else {} + if kind == "query": + options["location"] = "US" + + first_client = getattr(first, f"{kind}_client")(**options) + repeated = getattr(first, f"{kind}_client")(**options) + second_client = getattr(second, f"{kind}_client")(**options) + + assert repeated is first_client + assert second_client is not first_client + assert first_client.credentials is credentials[0] + assert second_client.credentials is credentials[1] + assert [call.args[0] for call in resolve.call_args_list] == list(principals) + + +def test_source_and_sink_share_owner_without_serializing_live_clients( + monkeypatch: pytest.MonkeyPatch, + principals: tuple[Principal, Principal], +) -> None: + """Worker deserialization preserves sharing but opens independent clients.""" + monkeypatch.setattr(session, "_credentials_for", lambda _: Mock(token="token")) + build = Mock(side_effect=lambda _: Mock()) + monkeypatch.setattr(session, "_read_client", build) + owner = session.BigQueryConnection(principals[0]) + source = BigQuerySourceBackend(connection=owner) + sink = BigQuerySinkBackend(connection=owner) + live = owner.read_client() + + restored_source, restored_sink = pickle.loads(pickle.dumps((source, sink))) + restored = restored_source._connection + + assert source._connection is sink._connection + assert restored is restored_sink._connection + assert restored is not owner + assert restored.identity == owner.identity + assert build.call_count == 1 + assert restored.read_client() is not live + assert build.call_count == 2 + live.close.assert_not_called() + + +def test_concurrent_calls_open_one_client_and_close_allows_reopening( + monkeypatch: pytest.MonkeyPatch, + principals: tuple[Principal, Principal], +) -> None: + """Concurrent users share one lazy client; close retires it exactly once.""" + monkeypatch.setattr(session, "_credentials_for", lambda _: Mock(token="token")) + build = Mock(side_effect=lambda _: Mock()) + monkeypatch.setattr(session, "_read_client", build) + owner = session.BigQueryConnection(principals[0]) + + with ThreadPoolExecutor(max_workers=4) as pool: + clients = list(pool.map(lambda _: owner.read_client(), range(8))) + owner.close() + owner.close() + reopened = owner.read_client() + + assert all(client is clients[0] for client in clients) + clients[0].close.assert_called_once_with() + assert reopened is not clients[0] + assert build.call_count == 2 + + +def test_close_attempts_every_client_after_a_failure( + monkeypatch: pytest.MonkeyPatch, + principals: tuple[Principal, Principal], +) -> None: + """Cleanup errors cannot leave other owned clients unclosed or cached.""" + monkeypatch.setattr(session, "_credentials_for", lambda _: Mock(token="token")) + read = Mock() + read.close.side_effect = RuntimeError("close failed") + write = Mock() + monkeypatch.setattr(session, "_read_client", lambda _: read) + monkeypatch.setattr(session, "_write_client", lambda _: write) + owner = session.BigQueryConnection(principals[0]) + owner.read_client() + owner.write_client() + + with pytest.raises(RuntimeError, match="close failed"): + owner.close() + + read.close.assert_called_once_with() + write.close.assert_called_once_with() + owner.close() + assert read.close.call_count == 1 diff --git a/packages/kumo-bigquery/tests/test_sink.py b/packages/kumo-bigquery/tests/test_sink.py index 198d226a6..d11ff1672 100644 --- a/packages/kumo-bigquery/tests/test_sink.py +++ b/packages/kumo-bigquery/tests/test_sink.py @@ -161,8 +161,8 @@ def close(self): lambda self, connector: SimpleNamespace(name='n')) monkeypatch.setattr(BigQuerySinkBackend, '_credentials', lambda self, connector: object()) - monkeypatch.setattr(session._clients, 'write_client', - lambda principal: write_client) + monkeypatch.setattr(session.BigQueryConnection, 'write_client', + lambda self: write_client) return BigQuerySinkBackend(**options), write_client return make diff --git a/packages/kumo-core/README.md b/packages/kumo-core/README.md index 90178c549..0c59b3948 100644 --- a/packages/kumo-core/README.md +++ b/packages/kumo-core/README.md @@ -126,3 +126,15 @@ A name or ID supplied without a principal raises a migration error. Leaving the identity unset still selects ambient authentication for backends that support it. The service SDK's remote identity-management API is separate from this local connection interface. + +Snowflake and BigQuery engine connectors each own their lazy authenticated +connections and share them between their source and sink backends. Separate +connectors never share sessions or clients, even with identical principal names. +Call `connector.close()` to release those resources; later operations reconnect. +Serialization retains authentication configuration and explicit credentials, but +not live connections or locks, so receiving workers open their own connections. +The provider-level global `close(name)` APIs are removed. + +Snowflake stage access uses the connector's sink filesystem, including snapshot +export/restore and MLOps artifacts. The unused `StageArtifactLocation` adapter is +removed; its shared stage-filesystem helpers remain. diff --git a/packages/kumo-core/src/kumo_core/sources/principals.py b/packages/kumo-core/src/kumo_core/sources/principals.py index 95cd46f9c..613187b19 100644 --- a/packages/kumo-core/src/kumo_core/sources/principals.py +++ b/packages/kumo-core/src/kumo_core/sources/principals.py @@ -15,7 +15,7 @@ class Principal: """Configuration and credentials used to open a provider connection. Args: - name: Stable connection-cache key, independent of credential contents. + name: Diagnostic label, independent of credentials and connection ownership. config: Provider account and authentication configuration. credentials: Explicit credentials, or None for worker-local authentication. """ diff --git a/packages/kumo-engine/kumo/engine/connector/bigquery.py b/packages/kumo-engine/kumo/engine/connector/bigquery.py index 24661a96b..22ef2e979 100644 --- a/packages/kumo-engine/kumo/engine/connector/bigquery.py +++ b/packages/kumo-engine/kumo/engine/connector/bigquery.py @@ -8,7 +8,7 @@ """ from functools import cached_property -from typing import Optional +from typing import Any, Optional from kumoapi.data_source import BigQueryConnectorResourceConfig, DataSourceType from kumoapi.source_table import BigQuerySourceTable @@ -77,13 +77,25 @@ def source_type(self) -> DataSourceType: def config(self) -> BigQueryConnectorResourceConfig: return self._config + @cached_property + def _connection(self) -> Any: + connection_type = import_provider( + "kumo_bigquery.session", "bigquery").BigQueryConnection + # cached_property may run concurrently on first access. + return self.__dict__.setdefault("_connection", connection_type(self._principal)) + + def close(self) -> None: + """Close this connector's clients; later operations reconnect lazily.""" + if "_connection" in self.__dict__: + self._connection.close() + @cached_property def source_backend(self): BigQuerySourceBackend = import_provider( "kumo_bigquery.backend", "bigquery").BigQuerySourceBackend from kumo_core.sources.types import ReadMode return BigQuerySourceBackend( - identity=self._principal, + connection=self._connection, staging_uri=self.staging_uri, mode=ReadMode.STAGED if self.require_staged else None, ) @@ -94,7 +106,7 @@ def sink_backend(self): "bigquery").BigQuerySinkBackend from kumo_core.sources.types import ReadMode return BigQuerySinkBackend( - identity=self._principal, + connection=self._connection, staging_uri=self.staging_uri, mode=ReadMode.STAGED if self.require_staged else None, ) diff --git a/packages/kumo-engine/kumo/engine/connector/snowflake.py b/packages/kumo-engine/kumo/engine/connector/snowflake.py index 1249aadaf..fb5b77a6e 100644 --- a/packages/kumo-engine/kumo/engine/connector/snowflake.py +++ b/packages/kumo-engine/kumo/engine/connector/snowflake.py @@ -79,6 +79,18 @@ def source_type(self) -> DataSourceType: def config(self) -> SnowflakeConnectorResourceConfig: return self._config + @cached_property + def _connection(self) -> Any: + connection_type = import_provider( + "kumo_snowflake.session", "snowflake").SnowflakeConnection + # cached_property may run concurrently on first access. + return self.__dict__.setdefault("_connection", connection_type(self._principal)) + + def close(self) -> None: + """Close this connector's clients; later operations reconnect lazily.""" + if "_connection" in self.__dict__: + self._connection.close() + @cached_property def source_backend(self) -> SourceBackend: # Lazily imported: kumo_snowflake is only installed with the @@ -87,7 +99,7 @@ def source_backend(self) -> SourceBackend: # installed. SnowflakeSourceBackend = import_provider( "kumo_snowflake.backend", "snowflake").SnowflakeSourceBackend - return SnowflakeSourceBackend(identity=self._principal) + return SnowflakeSourceBackend(connection=self._connection) @cached_property def sink_backend(self) -> ArtifactSink: @@ -98,7 +110,7 @@ def sink_backend(self) -> ArtifactSink: """ SnowflakeSinkBackend = import_provider("kumo_snowflake.sink", "snowflake").SnowflakeSinkBackend - return SnowflakeSinkBackend(identity=self._principal) + return SnowflakeSinkBackend(connection=self._connection) def session(self) -> Any: r"""The Snowpark session this connector reads through.""" diff --git a/packages/kumo-engine/test/test_connector_connections.py b/packages/kumo-engine/test/test_connector_connections.py new file mode 100644 index 000000000..925fc07a6 --- /dev/null +++ b/packages/kumo-engine/test/test_connector_connections.py @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Engine connectors own and share provider connections without global caches.""" + +import pickle +from unittest.mock import Mock + +import pytest + +from kumo.engine.connector import ( + BigQueryConnector, + BigQueryIdentity, + SnowflakeConnector, + SnowflakeIdentity, +) + + +@pytest.fixture(params=["bigquery", "snowflake"]) +def connectors( + request: pytest.FixtureRequest, +) -> tuple[ + BigQueryConnector | SnowflakeConnector, BigQueryConnector | SnowflakeConnector +]: + """Build distinct connectors using the same public identity and target.""" + if request.param == "bigquery": + identity = BigQueryIdentity() + first, second = ( + BigQueryConnector( + project_id="sample-project", + dataset_id="dataset", + identity=identity, + ) + for _ in range(2) + ) + return first, second + snowflake_identity = SnowflakeIdentity( + account="account", username="reader", password="unused" + ) + first, second = ( + SnowflakeConnector( + warehouse="WH", + database="DB", + schema_name="SCHEMA", + identity=snowflake_identity, + ) + for _ in range(2) + ) + return first, second + + +def test_connection_is_shared_by_backends_but_not_by_connectors( + connectors: tuple[ + BigQueryConnector | SnowflakeConnector, BigQueryConnector | SnowflakeConnector + ], +) -> None: + """Equal identity names and targets never merge separate connector owners.""" + first, second = connectors + + assert first._principal is not None and second._principal is not None + assert first._principal.name == second._principal.name + assert vars(first.source_backend)["_connection"] is getattr( + first.sink_backend, "_connection" + ) + assert vars(first.source_backend)["_connection"] is not getattr( + second.source_backend, "_connection" + ) + + +def test_initialized_connectors_pickle_with_one_fresh_owner( + connectors: tuple[ + BigQueryConnector | SnowflakeConnector, BigQueryConnector | SnowflakeConnector + ], +) -> None: + """Cached backend objects retain a shared worker-local owner after transport.""" + connector, _ = connectors + owner = vars(connector.source_backend)["_connection"] + assert vars(connector.sink_backend)["_connection"] is owner + + restored = pickle.loads(pickle.dumps(connector)) + + assert vars(restored.source_backend)["_connection"] is getattr( + restored.sink_backend, "_connection" + ) + assert vars(restored.source_backend)["_connection"] is restored._connection + assert restored._connection is not owner + assert restored._connection.identity == owner.identity + + +def test_close_is_lazy_and_closes_only_the_owned_connection( + connectors: tuple[ + BigQueryConnector | SnowflakeConnector, BigQueryConnector | SnowflakeConnector + ], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Closing an unused connector opens nothing and cannot close another owner.""" + first, second = connectors + first.close() + assert "_connection" not in first.__dict__ + first_owner = vars(first.source_backend)["_connection"] + second_owner = vars(second.source_backend)["_connection"] + first_close = Mock() + second_close = Mock() + monkeypatch.setattr(first_owner, "close", first_close) + monkeypatch.setattr(second_owner, "close", second_close) + + first.close() + + first_close.assert_called_once_with() + second_close.assert_not_called() diff --git a/packages/kumo-engine/test/test_identity.py b/packages/kumo-engine/test/test_identity.py index 06dd7be54..f5b356fee 100644 --- a/packages/kumo-engine/test/test_identity.py +++ b/packages/kumo-engine/test/test_identity.py @@ -77,7 +77,6 @@ def test_source_backends_use_explicit_principals(provider: str) -> None: assert principal == connector.identity.principal assert connector.sink_backend._identity is principal assert backend._principal(connector) is principal - backend._identity = principal assert ( backend._principal(SimpleNamespace(id="remote", identity_id="remote-id")) is principal @@ -86,13 +85,6 @@ def test_source_backends_use_explicit_principals(provider: str) -> None: other = Principal("other", principal.config, principal.credentials) assert backend._principal(SimpleNamespace(id="remote", identity=other)) is principal - backend._identity = None - if provider in {"s3", "gcs"}: - assert backend._principal(connector) is None - else: - with pytest.raises(ValueError, match="needs a Principal"): - backend._principal(connector) - - backend._identity = "legacy" - with pytest.raises(ValueError, match="lookup is no longer supported"): - backend._principal(connector) + if provider == "bigquery": + assert backend._connection is connector.sink_backend._connection + assert backend._connection is connector._connection diff --git a/packages/kumo-engine/test/test_snowflake_connector.py b/packages/kumo-engine/test/test_snowflake_connector.py index b2b9254c8..8f3564c5e 100644 --- a/packages/kumo-engine/test/test_snowflake_connector.py +++ b/packages/kumo-engine/test/test_snowflake_connector.py @@ -117,8 +117,8 @@ def test_session_is_the_readers_session(monkeypatch): schema_name='S') calls = [] monkeypatch.setattr( - sessions._sessions, 'get', - lambda principal, target, fresh=False: calls.append(target) or 'live') + sessions.SnowflakeConnection, 'get', + lambda self, target, fresh=False: calls.append(target) or 'live') monkeypatch.setattr(type(connector.source_backend), '_principal', lambda self, target: 'principal') assert connector.session() == 'live' diff --git a/packages/kumo-snowflake/src/kumo_snowflake/__init__.py b/packages/kumo-snowflake/src/kumo_snowflake/__init__.py index 3987847db..f344699d0 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/__init__.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/__init__.py @@ -7,8 +7,8 @@ :class:`SnowflakeSourceReader` implements ``kumo_core``'s ``SourceReader`` and is what the platform binds through. :class:`SnowflakeSourceBackend` implements :class:`kumoapi.plugin.SourceBackend` and is what a ``LocalBackend`` registers -for ``DataSourceType.SNOWFLAKE``; the sink, the stage artifact location and the -identity lifecycle beside it are the rest of that plugin. +for ``DataSourceType.SNOWFLAKE``; its sink handles tables, model registry +operations, and named-stage files through the connector's session. Nothing here imports ``kumoai_studio``. That is what lets one distribution serve both callers, and ``tests/test_package_boundary.py`` enforces it rather than leaving @@ -35,8 +35,6 @@ "SnowflakeSinkBackend": "sink", "SnowflakeSourceBackend": "backend", "SourceConnector": "session", - "StageArtifactLocation": "artifacts", - "close": "session", "probe": "session", } diff --git a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py index a6b11adc5..90cea5694 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/artifacts.py @@ -1,61 +1,21 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -r"""Durable DiskGraph snapshots in a Snowflake named internal stage. +"""Shared file operations for Snowflake named internal stages.""" -DiskGraph can only build and verify an index on a local filesystem. A -:class:`StageArtifactLocation` therefore keeps the active copy below -``Storage.scratch`` and translates the snapshot store's tree operations into -Snowflake file operations. The durable address remains the stage URI, so a -second process with an empty scratch directory can restore the same snapshot. - -Publication uses a unique temporary prefix and promotes its files with -``COPY FILES``. ``_SUCCESS`` is copied last and is the commit marker: a failed -or interrupted promotion is never considered restorable. Snowflake stages do -not represent empty directories, so a small transport manifest records them; -it is consumed on restore and never reaches DiskGraph's integrity verifier. -""" - -import hashlib -import json import posixpath import re -import shutil -import tempfile -import uuid -from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from functools import lru_cache from pathlib import Path -from typing import Callable, Dict, List, Optional, Sequence, Tuple, TypeVar +from typing import Dict, Optional, Tuple -from kumo_core.sources.principals import Principal from kumo_snowflake.session import ( SnowflakeSession, - _quoted_literal, _require_snowpark, _rows, - _sessions, resolved, ) -from kumoapi.plugin import IngestResult, SnapshotStore, _Handle - -_Item = TypeVar('_Item') -_Result = TypeVar('_Result') - - -def _in_parallel(work: Callable[[_Item], _Result], items: Sequence[_Item], - workers: int, name: str) -> List[_Result]: - r"""``pool.map`` re-raises the first failure on iteration, so a caller - that gets a list back knows every item succeeded. The pool is sized to the - work so that a two-file tree does not start sixteen threads. - """ - if not items: - return [] - with ThreadPoolExecutor(max_workers=min(workers, len(items)), - thread_name_prefix=name) as pool: - return list(pool.map(work, items)) - _IDENTIFIER = (r'(?:[A-Za-z_][A-Za-z0-9_$]*|"(?:[A-Za-z0-9_$ .-]|"")+")') _STAGE_LOCATION_BODY = (rf'(?P@(?P{_IDENTIFIER})\.' @@ -63,14 +23,6 @@ def _in_parallel(work: Callable[[_Item], _Result], items: Sequence[_Item], r'(?:/(?P[A-Za-z0-9_$=+.,/\-]+))?') _STAGE_LOCATION = re.compile(rf'^{_STAGE_LOCATION_BODY}$') -_TREE_MANIFEST = '.kumo-stage-tree.json' -_SUCCESS = '_SUCCESS' -_COPY_FILES_LIMIT = 1000 -# COPY FILES rejects source files larger than 5 GB. PUT accepts larger files, -# so fail before promotion instead of leaving a snapshot that can never be -# committed. Snowflake expresses that limit as 5,368,709,120 bytes. -_COPY_FILES_MAX_BYTES = 5 * 1024**3 - @lru_cache(maxsize=2048) def _split_normalized_stage_location(normalized: str) -> Tuple[str, str, str]: @@ -80,8 +32,7 @@ def _split_normalized_stage_location(normalized: str) -> Tuple[str, str, str]: raise ValueError( f"Snowflake stage location {normalized!r} must be a fully-qualified " "named stage such as '@DB.SCHEMA.KUMO_ARTIFACTS/prefix'. User " - "and table stages are not supported because COPY FILES cannot " - "promote snapshots through them.") + "and table stages are not supported.") prefix = match.group('prefix') or '' if any(part in ('', '.', '..') for part in prefix.split('/') if prefix): raise ValueError( @@ -123,14 +74,6 @@ def _safe_relative(value: str) -> str: return relative -def _sha256(path: Path) -> str: - digest = hashlib.sha256() - with path.open('rb') as source: - for chunk in iter(lambda: source.read(1024 * 1024), b''): - digest.update(chunk) - return digest.hexdigest() - - def _relative_stage_name(name: str, location: str) -> Optional[str]: r"""Returns a LIST row's name relative to the location being listed. @@ -169,11 +112,10 @@ class _StageObject: class _StageFiles: - r"""The file operations injected into ``LocalSnapshotStore``.""" - def __init__(self, session: SnowflakeSession, parallel: int) -> None: + """File operations shared by the stage filesystem.""" + def __init__(self, session: SnowflakeSession) -> None: _require_snowpark(session) self._session = session - self._parallel = parallel def _list(self, location: str, *, tree: bool = True) -> Dict[str, _StageObject]: @@ -185,7 +127,7 @@ def _list(self, location: str, *, if relative is None: continue # An exact-file LIST has an empty relative name. Preserve it for - # `exists`; a tree LIST never produces one. + # the filesystem's exact-file lookup. key = relative if not relative else _safe_relative(relative) if key in objects: raise ValueError( @@ -194,90 +136,6 @@ def _list(self, location: str, *, objects[key] = _StageObject(key, int(row[1])) return objects - def exists(self, location: str) -> bool: - r"""Whether exactly :obj:`location`, rather than its prefix, exists.""" - return '' in self._list(location, tree=False) - - def preflight(self, location: str) -> None: - r"""Checks stage type and every operation snapshot publication uses. - - The capability probe is deliberately operational: grants inherited - through role hierarchies are difficult to infer correctly from grant - metadata, while a tiny PUT/COPY/LIST/REMOVE cycle proves the effective - session can perform the actual workflow. Its UUID-scoped prefix is - removed in ``finally`` and never overlaps artifact data. A hard - process termination can leave that disposable prefix behind; it is - safe to remove because preflight never writes artifact data there. - """ - match = _STAGE_LOCATION.fullmatch(location) - assert match is not None - database_sql = match.group('database') - schema_sql = match.group('schema') - stage_name = resolved(match.group('name')) - database_name = resolved(database_sql) - schema_name = resolved(schema_sql) - self._session.sql( - f'SHOW STAGES IN SCHEMA {database_sql}.{schema_sql}').collect() - # SHOW output grows over time, so project stable named columns instead - # of relying on their positional indexes in Snowflake's row shape. - rows = _rows( - self._session, - 'SELECT "name", "database_name", "schema_name", "type" ' - 'FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))') - matches = [ - row for row in rows if len(row) == 4 and str(row[0]) == stage_name - and str(row[1]) == database_name and str(row[2]) == schema_name - ] - if not matches: - raise ValueError( - f'Snowflake stage {match.group("stage")!r} does not exist or ' - 'is not visible to the registered session role.') - stage_type = str(matches[0][3]).upper() - if 'INTERNAL' not in stage_type: - raise ValueError( - f'Snowflake stage {match.group("stage")!r} is {stage_type!r}; ' - 'StageArtifactLocation requires a named internal stage.') - - run_root = _stage_join(location, '.kumo-preflight', uuid.uuid4().hex) - source = _stage_join(run_root, 'source') - target = _stage_join(run_root, 'target') - with tempfile.TemporaryDirectory(prefix='kumo-stage-preflight-') as tmp: - probe = Path(tmp) / 'probe' - probe.write_bytes(b'kumo-stage-preflight\n') - try: - self._put(probe, source) - if not self.exists(_stage_join(source, probe.name)): - raise RuntimeError( - f'PUT to Snowflake stage {location!r} completed but ' - 'the probe was not visible to LIST.') - self._copy_files(source, target, [probe.name]) - copied = _stage_join(target, probe.name) - if not self.exists(copied): - raise RuntimeError( - f'COPY FILES in Snowflake stage {location!r} completed ' - 'but its target was not visible to LIST.') - downloaded = Path(tmp) / 'downloaded' / probe.name - self._get(copied, downloaded, probe.stat().st_size) - if downloaded.read_bytes() != probe.read_bytes(): - raise RuntimeError( - f'GET from Snowflake stage {location!r} returned ' - 'different probe contents.') - finally: - self.remove(run_root) - - def copy_tree(self, source: str, target: str) -> None: - r"""Uploads local-to-stage or downloads stage-to-local.""" - source_is_stage = str(source).startswith('@') - target_is_stage = str(target).startswith('@') - if source_is_stage == target_is_stage: - raise ValueError( - f'A stage tree copy needs one local and one stage path; got ' - f'{source!r} -> {target!r}.') - if target_is_stage: - self._upload_tree(Path(source), target) - else: - self._download_tree(source, Path(target)) - def _put(self, source: Path, target_dir: str) -> None: results = self._session.file.put(str(source), target_dir, parallel=1, auto_compress=False, @@ -288,270 +146,6 @@ def _put(self, source: Path, target_dir: str) -> None: f'Snowflake reported no result while uploading {source} to ' f'{target_dir}.') - def _upload_tree(self, source: Path, target: str) -> None: - if not source.is_dir(): - raise ValueError(f'No local artifact tree exists at {source}.') - root = source.resolve() - files: List[Tuple[str, Path]] = [] - directories: List[str] = [] - for path in sorted(source.rglob('*')): - relative = path.relative_to(source).as_posix() - if path.is_dir(): - directories.append(relative) - continue - if not path.is_file(): - continue - resolved = path.resolve() - if not resolved.is_relative_to(root): - raise ValueError( - f'Artifact file {path} resolves outside {source}; stage ' - 'publication does not follow escaping symlinks.') - files.append((_safe_relative(relative), path)) - - with tempfile.TemporaryDirectory(prefix='kumo-stage-manifest-') as tmp: - manifest = Path(tmp) / _TREE_MANIFEST - manifest.write_text( - json.dumps( - { - 'directories': directories, - 'files': { - relative: { - 'size': path.stat().st_size, - 'sha256': _sha256(path), - } - for relative, path in files - }, - }, sort_keys=True) + '\n', encoding='utf-8') - # Upload order is irrelevant: promotion copies `_SUCCESS` last, - # and readers treat only that marker as a committed snapshot. - entries = files + [(_TREE_MANIFEST, manifest)] - - def upload(entry: Tuple[str, Path]) -> None: - relative, path = entry - parent = posixpath.dirname(relative) - self._put(path, _stage_join(target, parent)) - - try: - _in_parallel(upload, entries, self._parallel, 'kumo-stage-put') - expected = { - relative: path.stat().st_size - for relative, path in entries - } - actual = { - name: obj.size - for name, obj in self._list(target).items() - } - if set(actual) != set(expected): - raise RuntimeError( - f'Uploading {source} to {target} produced a different ' - f'file set: expected {sorted(expected)}, got ' - f'{sorted(actual)}.') - except Exception: - self.remove(target) - raise - - def _get(self, source: str, target: Path, - expected_size: Optional[int] = None) -> None: - target.parent.mkdir(parents=True, exist_ok=True) - results = self._session.file.get(source, str(target.parent), parallel=1) - if not results: - raise RuntimeError( - f'Snowflake reported no result while downloading {source}.') - if not target.is_file(): - raise RuntimeError( - f'Snowflake reported a download for {source}, but no file ' - f'landed at {target}.') - if (expected_size is not None - and target.stat().st_size != expected_size): - raise RuntimeError( - f'Downloading {source} produced {target.stat().st_size} ' - f'bytes, but the stage reported {expected_size}.') - - def _download_tree(self, source: str, target: Path) -> None: - objects = self._list(source) - if not objects: - raise RuntimeError( - f'Snowflake stage tree {source!r} was present when restore ' - 'started but contains no files.') - if target.exists(): - shutil.rmtree(target) - target.mkdir(parents=True) - - def download(item: Tuple[str, _StageObject]) -> None: - relative, _ = item - if not relative: - raise ValueError( - f'Cannot restore exact stage object {source!r} as a tree.') - destination = target / _safe_relative(relative) - self._get(_stage_join(source, relative), destination) - - try: - _in_parallel(download, list(objects.items()), self._parallel, - 'kumo-stage-get') - manifest = target / _TREE_MANIFEST - if not manifest.is_file(): - raise RuntimeError( - f'Snowflake stage tree {source!r} has no ' - f'{_TREE_MANIFEST}; it was not published completely by ' - 'StageArtifactLocation.') - payload = json.loads(manifest.read_text(encoding='utf-8')) - expected = payload.get('files') or {} - actual = { - path.relative_to(target).as_posix(): { - 'size': path.stat().st_size, - 'sha256': _sha256(path), - } - for path in target.rglob('*') - if path.is_file() and path != manifest - } - if actual != expected: - changed = sorted(name for name in set(expected) | set(actual) - if expected.get(name) != actual.get(name)) - raise RuntimeError( - f'Restoring {source} failed its integrity check for: ' - f'{changed}.') - for relative in payload.get('directories') or []: - (target / _safe_relative(str(relative))).mkdir( - parents=True, exist_ok=True) - manifest.unlink() - except Exception: - shutil.rmtree(target, ignore_errors=True) - raise - - def replace_tree(self, source: str, target: str) -> None: - r"""Promotes a temporary stage prefix, committing `_SUCCESS` last.""" - if not source.startswith('@') or not target.startswith('@'): - raise ValueError('Snowflake stage promotion needs two stage paths.') - if self.exists(_stage_join(target, _SUCCESS)): - self.remove(source) - return - - objects = self._list(source) - if _SUCCESS not in objects: - raise RuntimeError( - f'Cannot publish {source!r}: it has no {_SUCCESS} marker.') - oversized = [ - name for name, obj in objects.items() - if obj.size > _COPY_FILES_MAX_BYTES - ] - if oversized: - self.remove(source) - raise ValueError( - 'Snowflake COPY FILES cannot promote files larger than 5 GB; ' - f'{source!r} contains oversized files: {oversized!r}.') - self.remove(target) - ordinary = [name for name in objects if name != _SUCCESS] - try: - self._copy_files(source, target, ordinary) - self._copy_files(source, target, [_SUCCESS]) - published = self._list(target) - expected = {name: obj.size for name, obj in objects.items()} - actual = {name: obj.size for name, obj in published.items()} - if actual != expected: - raise RuntimeError( - f'Publishing {target} produced a different file set: ' - f'expected {sorted(expected)}, got {sorted(actual)}.') - except Exception: - # Never remove a tree another publisher committed while this one - # was failing. Without a marker, the prefix is only our partial - # copy and is safe to clean up. - if not self.exists(_stage_join(target, _SUCCESS)): - self.remove(target) - raise - finally: - self.remove(source) - - def _copy_files(self, source: str, target: str, - relatives: List[str]) -> None: - for start in range(0, len(relatives), _COPY_FILES_LIMIT): - chunk = relatives[start:start + _COPY_FILES_LIMIT] - if not chunk: - continue - names = ', '.join("'" + _quoted_literal(name) + "'" - for name in chunk) - _rows( - self._session, - f'COPY FILES INTO {_stage_join(target, directory=True)} ' - f'FROM {_stage_join(source, directory=True)} FILES = ({names}) ' - 'DETAILED_OUTPUT = TRUE') - def remove(self, location: str) -> None: r"""Removes every object under a stage location.""" _rows(self._session, f'REMOVE {_stage_join(location, directory=True)}') - - -@dataclass(frozen=True) -class StageArtifactLocation: - r"""Publishes verified snapshots to a Snowflake named internal stage. - - Args: - root: Fully-qualified stage URI, optionally with a prefix, such as - ``@PROD.ML.KUMO_ARTIFACTS/local-backend``. The stage must already - exist. Its role needs database/schema usage plus stage read/write. - identity: A Principal with provider configuration and credentials. Its role - needs the stage privileges below. Names and IDs are not accepted. - parallel: Concurrent file transfers, from 1 through 99. - - The local working artifact directory is derived from ``Storage.scratch``; - callers never pass a stage URI to DiskGraph, pandas, Torch, or - ``kumo_core``. - """ - root: str - identity: Principal - parallel: int = 16 - - def __post_init__(self) -> None: - stage, prefix, _ = _split_stage_location(self.root) - object.__setattr__(self, 'root', - f'{stage}/{prefix}' if prefix else stage) - if not isinstance(self.parallel, int) or not 1 <= self.parallel <= 99: - raise ValueError('parallel must be an integer from 1 through 99') - - def local_root(self, scratch: str) -> str: - r"""Returns a cache keyed by a 12-hex SHA256 truncation of the URI.""" - key = hashlib.sha256(self.root.encode('utf-8')).hexdigest()[:12] - return str(Path(scratch) / 'artifacts' / f'snowflake-stage-{key}') - - def _session(self) -> SnowflakeSession: - r"""A session on the identity alone, with no connector target. - - A stage is addressed by its own fully-qualified name, so this - connection needs no database or schema of its own -- and must not - borrow a connector's, since a stage location is independent of - whatever table happened to be read last. - """ - if isinstance(self.identity, Principal): - session = _sessions.get(self.identity, None) - _require_snowpark(session) - return session - raise ValueError( - "Stage artifact storage needs a Principal. " - "Identity name, ID, and slug lookup is no longer supported.") - - def preflight(self) -> None: - r"""Validates stage type and effective transfer privileges.""" - _StageFiles(self._session(), self.parallel).preflight(self.root) - - def restore(self, store: SnapshotStore[_Handle], - handle: _Handle) -> Optional[IngestResult]: - files = _StageFiles(self._session(), self.parallel) - restored = store.restore(handle, self.root, exists=files.exists, - copy_tree=files.copy_tree) - if restored is None: - return None - from kumo_core.diskgraph.snapshot import rebased - return rebased(store, handle) - - def checkpoint(self, store: SnapshotStore[_Handle], - handle: _Handle) -> Optional[str]: - files = _StageFiles(self._session(), self.parallel) - return store.checkpoint(handle, self.root, exists=files.exists, - copy_tree=files.copy_tree, - replace_tree=files.replace_tree) - - def durable_path(self, store: SnapshotStore[_Handle], - handle: _Handle) -> Optional[str]: - return store.durable_path(handle, self.root) - - -__all__ = ['StageArtifactLocation'] diff --git a/packages/kumo-snowflake/src/kumo_snowflake/backend.py b/packages/kumo-snowflake/src/kumo_snowflake/backend.py index 5a73078e1..3d3e5999a 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/backend.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/backend.py @@ -31,6 +31,7 @@ from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumo_snowflake.session import ( + SnowflakeConnection, SnowflakeSession, _require_snowpark, _SnowflakeSessions, @@ -57,6 +58,7 @@ class SnowflakeSourceBackend(_SnowflakeSessions): Args: identity: Principal used for all connections opened by this backend. + connection: Connector-owned sessions; supply instead of identity. Example: >>> from kumo_core.sources.principals import Principal @@ -74,8 +76,10 @@ def __init__( self, identity: Optional[Principal] = None, mode: Optional[ReadMode] = None, + *, + connection: Optional[SnowflakeConnection] = None, ) -> None: - super().__init__(identity) + super().__init__(identity, connection=connection) #: Snowflake unloads and offers nothing else; the argument exists so #: one caller can name a mode whichever warehouse it reaches. self.mode = mode diff --git a/packages/kumo-snowflake/src/kumo_snowflake/session.py b/packages/kumo-snowflake/src/kumo_snowflake/session.py index eee0ddf21..e699e9184 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/session.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/session.py @@ -17,16 +17,14 @@ serialized with a lock, left the caller's session pointing somewhere it had not asked for, and could not apply ``role`` at all. -Sessions are cached per ``(identity, target)``. Two connectors that name the -same identity but different warehouses therefore get one connection each and -do not contend; two that name the same target share one. The target is in the -key because it is baked into the connection: a warehouse, role, database and -schema chosen at connect time are properties of that connection, so two -targets are necessarily two connections. +Each engine connector owns its sessions and shares them between its source +and sink backends. Independent connectors never share authenticated sessions. """ +from __future__ import annotations + import threading -from contextlib import contextmanager +from contextlib import ExitStack, contextmanager from typing import Any, Dict, Iterator, List, Optional, Tuple, TypeAlias, Union from kumo_core.sources.principals import Principal @@ -54,16 +52,8 @@ #: key pair reaches the driver as DER bytes while everything else is a string. _ConnectSettings = Dict[str, Union[str, bytes, bool]] -#: A target reduced to something hashable, so two connectors naming the same -#: warehouse, database, schema and role share one connection. _TargetKey = Tuple[Tuple[str, str], ...] -#: Identity name and target -- what a connection *is*. Nothing about the -#: credential's freshness belongs here: a session already open authenticates as -#: the same principal after a rotation as before, so the identity area closes -#: these by name instead, when it has a reason to. -_CacheKey = Tuple[str, _TargetKey] - def _target_config( connector: SourceConnector) -> SnowflakeConnectorResourceConfig: @@ -285,57 +275,73 @@ def _is_live(session: Session) -> bool: return False -class _SessionCache: - r"""Live sessions, by identity and target. +class SnowflakeConnection: + """Own lazy Snowflake sessions for one connector's authentication. + + Args: + identity: Explicit principal used to open every session. - Module-level rather than per backend: the source and the sink are separate - objects, and a reader that opened its own connection while the writer - beside it opened another would double the connections an account sees for - no gain. + Sessions are separated by target when a backend is used directly. Pickling + retains only the principal; receiving workers open their own sessions. """ - def __init__(self) -> None: + + def __init__(self, identity: Principal | None) -> None: + self._identity = identity self._lock = threading.RLock() - self._sessions: Dict[_CacheKey, Session] = {} + self._sessions: dict[_TargetKey, Session] = {} + + @property + def identity(self) -> Principal | None: + """Return the principal bound to this connection owner.""" + return self._identity + + def __reduce__( + self, + ) -> tuple[type[SnowflakeConnection], tuple[Principal | None]]: + """Serialize authentication without live sessions or locks.""" + return type(self), (self.identity,) + + def get(self, connector: SourceConnector | None, *, fresh: bool = False) -> Session: + """Return a live session for the target, opening or replacing it as needed. + + Args: + connector: Target database, schema, warehouse, and role. + fresh: Close and replace an existing session. + + Returns: + A session owned by this connection. - def get(self, principal: Principal, connector: Optional[SourceConnector], *, - fresh: bool = False) -> Session: - key: _CacheKey = (principal.name, _target_key(connector)) + Raises: + TypeError: No explicit principal was supplied. + RuntimeError: Snowflake authentication or connection creation fails. + """ + if not isinstance(self.identity, Principal): + raise TypeError( + "Snowflake backend needs a Principal containing " + "authentication configuration.") + key = _target_key(connector) with self._lock: session = self._sessions.get(key) if session is not None and not fresh and _is_live(session): return session if session is not None: del self._sessions[key] - try: - session.close() - except Exception: - pass - session = _connect(principal, connector) + session.close() + session = _connect(self.identity, connector) self._sessions[key] = session return session - def close(self, name: Optional[str] = None) -> None: - r"""Closes and forgets sessions, for one identity or for all. + def close(self) -> None: + """Forget and close all owned sessions; subsequent calls reopen them. - This module opens the connections, so it owns closing them. A caller - that never asks still leaks nothing indefinitely: Snowflake expires an - idle session on its own. + Raises: + Exception: A driver fails to close a session, after all closes run. """ - with self._lock: - keys = [ - key for key in self._sessions if name is None or key[0] == name - ] - for key in keys: - session = self._sessions.pop(key) - try: - session.close() - except Exception: - # Already gone server-side, most likely. Nothing here can - # act on it, and raising would mask the caller's own work. - pass - - -_sessions = _SessionCache() + with self._lock, ExitStack() as cleanup: + sessions = list(self._sessions.values()) + self._sessions.clear() + for session in sessions: + cleanup.callback(session.close) @contextmanager @@ -397,24 +403,6 @@ def probe(principal: Principal) -> None: pass -def close(identity_name: Optional[str] = None) -> None: - r"""Closes the sessions opened as :obj:`identity_name`, or all of them. - - The other half of the ``kumoai_studio.identities`` lifecycle, and the half only a - plugin that caches defines. The identity area calls it when material is - rotated or an identity is deleted -- neither of which this module can see - for itself, and neither of which it is subscribed to. - - Rotation is not a correctness problem for a session already open: it - authenticates as the same principal afterwards, since a rotation replaces - material and never the config. What it is is a *recovery* problem. A caller - who rotates has usually just been told a connection no longer - authenticates, and answering the retry from that very connection would - make the documented recovery impossible. - """ - _sessions.close(identity_name) - - class _SnowflakeSessions: r"""Resolving a connector to a live Snowpark session. @@ -427,10 +415,20 @@ class _SnowflakeSessions: Args: identity: Principal used for all connections opened by this backend. + connection: Connector-owned connection shared with its other backend. + Supply this instead of identity. """ - def __init__(self, identity: Optional[Principal] = None) -> None: - self._identity = identity + def __init__(self, identity: Principal | None = None, *, + connection: SnowflakeConnection | None = None) -> None: + if identity is not None and connection is not None: + raise ValueError("Pass identity or connection, not both.") + self._connection = (connection if connection is not None + else SnowflakeConnection(identity)) + + @property + def _identity(self) -> Principal | None: + return self._connection.identity @contextmanager def _session(self, connector: SourceConnector, *, @@ -441,7 +439,8 @@ def _session(self, connector: SourceConnector, *, ``(identity, target)`` pair, so no other caller can move it out from under the statements run here. """ - yield _sessions.get(self._principal(connector), connector, fresh=fresh) + self._principal(connector) + yield self._connection.get(connector, fresh=fresh) def _principal(self, connector: SourceConnector) -> Principal: if isinstance(self._identity, Principal): diff --git a/packages/kumo-snowflake/src/kumo_snowflake/stage_fs.py b/packages/kumo-snowflake/src/kumo_snowflake/stage_fs.py index 744809621..fe324f89c 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/stage_fs.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/stage_fs.py @@ -54,7 +54,7 @@ class StageFileSystemHandler(ChunkedFileHandler): def __init__(self, session: SnowflakeSession, root: str) -> None: self._stage = _split_stage_location(root)[0] self._session = session - self._files = _StageFiles(session, parallel=1) + self._files = _StageFiles(session) self._urls: Dict[str, str] = {} self._http = threading.local() self._downloads: Dict[str, Tuple[threading.Lock, list]] = {} diff --git a/packages/kumo-snowflake/tests/test_artifact_identity.py b/packages/kumo-snowflake/tests/test_artifact_identity.py deleted file mode 100644 index be9f14067..000000000 --- a/packages/kumo-snowflake/tests/test_artifact_identity.py +++ /dev/null @@ -1,64 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. -# All rights reserved. -# SPDX-License-Identifier: Apache-2.0 -"""Stage artifact authentication uses the caller's principal without a registry.""" - -import importlib.util -import sys -from pathlib import Path -from types import ModuleType -from unittest.mock import Mock - -import pytest -from kumo_core.sources.principals import Principal -from kumoapi.data_source import ( - SnowflakeAuthenticationKind, - SnowflakeIdentityConfig, -) - - -@pytest.fixture -def artifacts(monkeypatch: pytest.MonkeyPatch) -> ModuleType: - """Load the stage adapter with a mocked Snowpark session boundary.""" - session = ModuleType("kumo_snowflake.session") - session.SnowflakeSession = object - for name in ( - "_quoted_literal", - "_require_snowpark", - "_rows", - "_sessions", - "resolved", - ): - setattr(session, name, Mock()) - monkeypatch.setitem(sys.modules, session.__name__, session) - path = Path(__file__).parents[1] / "src/kumo_snowflake/artifacts.py" - spec = importlib.util.spec_from_file_location("_stage_artifact_identity_test", path) - assert spec is not None and spec.loader is not None - module = importlib.util.module_from_spec(spec) - monkeypatch.setitem(sys.modules, spec.name, module) - spec.loader.exec_module(module) - return module - - -def test_stage_uses_supplied_principal(artifacts: ModuleType) -> None: - """Explicit principals open target-free sessions without wrapper adapters.""" - principal = Principal( - "stage-test", - SnowflakeIdentityConfig( - account="account", - authentication=SnowflakeAuthenticationKind.OAUTH_TOKEN_FILE, - ), - None, - ) - location = artifacts.StageArtifactLocation("@DB.SCHEMA.ARTIFACTS/root", principal) - result = location._session() - artifacts._sessions.get.assert_called_once_with(principal, None) - artifacts._require_snowpark.assert_called_once_with(result) - - -def test_stage_rejects_name_lookup(artifacts: ModuleType) -> None: - """A removed name reference fails before opening any Snowflake connection.""" - location = artifacts.StageArtifactLocation("@DB.SCHEMA.ARTIFACTS", "old-name") - with pytest.raises(ValueError, match="lookup is no longer supported"): - location._session() - artifacts._sessions.get.assert_not_called() diff --git a/packages/kumo-snowflake/tests/test_connection.py b/packages/kumo-snowflake/tests/test_connection.py new file mode 100644 index 000000000..2e79b5ca2 --- /dev/null +++ b/packages/kumo-snowflake/tests/test_connection.py @@ -0,0 +1,155 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Connector-owned Snowpark sessions isolate accounts and worker state.""" + +import pickle +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from kumo_core.sources.principals import Principal +from kumo_snowflake import session +from kumo_snowflake.backend import SnowflakeSourceBackend +from kumo_snowflake.sink import SnowflakeSinkBackend +from kumoapi.data_source import ( + SnowflakeAuthenticationKind, + SnowflakeConnectorResourceConfig, + SnowflakeIdentityConfig, + SnowflakePasswordCredentials, +) +from kumoapi.plugin import SourceConnector + + +@pytest.fixture +def principals() -> tuple[Principal, Principal]: + """Supply two accounts with distinct credentials under one display name.""" + + def principal(index: int) -> Principal: + return Principal( + "shared-name", + SnowflakeIdentityConfig( + account=f"account-{index}", + username=f"reader-{index}", + authentication=SnowflakeAuthenticationKind.PASSWORD, + ), + SnowflakePasswordCredentials(password=f"unused-{index}"), + ) + + return principal(1), principal(2) + + +@pytest.fixture +def connector() -> SourceConnector: + """Supply a fixed warehouse target without any authentication fallback.""" + return SimpleNamespace( + id="connector", + config=SnowflakeConnectorResourceConfig( + warehouse="WH", database="DB", schema_name="SCHEMA" + ), + ) + + +@pytest.fixture +def connect(monkeypatch: pytest.MonkeyPatch) -> Mock: + """Mock Snowpark creation while keeping real owner and liveness behavior.""" + build = Mock( + side_effect=lambda *_: Mock(connection=SimpleNamespace(is_closed=lambda: False)) + ) + monkeypatch.setattr(session, "_connect", build) + return build + + +def test_same_name_principals_have_independent_sessions( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, +) -> None: + """Sharing a display name cannot cause cross-account session reuse.""" + first = session.SnowflakeConnection(principals[0]) + second = session.SnowflakeConnection(principals[1]) + + live = first.get(connector) + + assert first.get(connector) is live + assert second.get(connector) is not live + assert [call.args[0] for call in connect.call_args_list] == list(principals) + + +def test_source_and_sink_share_owner_without_serializing_live_sessions( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, +) -> None: + """Workers share their own source/sink owner without inheriting an open session.""" + owner = session.SnowflakeConnection(principals[0]) + source = SnowflakeSourceBackend(connection=owner) + sink = SnowflakeSinkBackend(connection=owner) + with source._session(connector) as live, sink._session(connector) as same: + assert same is live + + restored_source, restored_sink = pickle.loads(pickle.dumps((source, sink))) + restored = restored_source._connection + + assert restored is restored_sink._connection + assert restored is not owner + assert restored.identity == owner.identity + assert connect.call_count == 1 + with restored_source._session(connector) as worker_session: + assert worker_session is not live + assert connect.call_count == 2 + live.close.assert_not_called() + + +def test_concurrent_calls_open_one_session_and_close_allows_reopening( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, +) -> None: + """Concurrent backend operations reuse the owner's lazy session.""" + owner = session.SnowflakeConnection(principals[0]) + + with ThreadPoolExecutor(max_workers=4) as pool: + sessions = list(pool.map(lambda _: owner.get(connector), range(8))) + owner.close() + owner.close() + reopened = owner.get(connector) + + assert all(live is sessions[0] for live in sessions) + sessions[0].close.assert_called_once_with() + assert reopened is not sessions[0] + assert connect.call_count == 2 + + +def test_closed_session_is_replaced( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, +) -> None: + """A driver-closed session is never returned to a subsequent caller.""" + owner = session.SnowflakeConnection(principals[0]) + live = owner.get(connector) + live.connection.is_closed = lambda: True + + assert owner.get(connector) is not live + live.close.assert_called_once_with() + assert connect.call_count == 2 + + +def test_distinct_targets_never_reuse_session_context( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, +) -> None: + """Direct backend use cannot leak a warehouse or role across targets.""" + owner = session.SnowflakeConnection(principals[0]) + other = SimpleNamespace( + id="other", + config=SnowflakeConnectorResourceConfig( + warehouse="OTHER_WH", database="DB", schema_name="SCHEMA", role="OTHER_ROLE" + ), + ) + + assert owner.get(connector) is not owner.get(other) + assert connect.call_count == 2 diff --git a/packages/kumo-snowflake/tests/test_sink.py b/packages/kumo-snowflake/tests/test_sink.py index 7f95d0fc1..94276f099 100644 --- a/packages/kumo-snowflake/tests/test_sink.py +++ b/packages/kumo-snowflake/tests/test_sink.py @@ -6,9 +6,14 @@ from contextlib import contextmanager from types import SimpleNamespace +from kumo_core.sources.principals import Principal from kumo_snowflake import session, sink from kumo_snowflake.sink import SnowflakeSinkBackend from kumo_snowflake.write import write_artifacts_to_table +from kumoapi.data_source import ( + SnowflakeAuthenticationKind, + SnowflakeIdentityConfig, +) from kumoapi.jobs import WriteMode @@ -23,8 +28,9 @@ def close(self): def test_a_forced_session_refresh_discards_the_cached_connection(monkeypatch): opened = [] - cache = session._SessionCache() - principal = SimpleNamespace(name="oauth") + principal = Principal("oauth", SnowflakeIdentityConfig( + account="account", authentication=SnowflakeAuthenticationKind.OAUTH_TOKEN_FILE), None) + cache = session.SnowflakeConnection(principal) def connect(*_): value = _Session() @@ -33,8 +39,8 @@ def connect(*_): monkeypatch.setattr(session, "_connect", connect) - first = cache.get(principal, None) - second = cache.get(principal, None, fresh=True) + first = cache.get(None) + second = cache.get(None, fresh=True) assert first is opened[0] assert second is opened[1] @@ -43,8 +49,9 @@ def connect(*_): def test_an_owned_session_leaves_the_cached_connection_open(monkeypatch): opened = [] - cache = session._SessionCache() - principal = SimpleNamespace(name="oauth") + principal = Principal("oauth", SnowflakeIdentityConfig( + account="account", authentication=SnowflakeAuthenticationKind.OAUTH_TOKEN_FILE), None) + cache = session.SnowflakeConnection(principal) def connect(*_): value = _Session() @@ -52,14 +59,14 @@ def connect(*_): return value monkeypatch.setattr(session, "_connect", connect) - cached = cache.get(principal, None) + cached = cache.get(None) with session._owned_session(principal, None) as retry: assert retry is opened[1] assert cached.close_calls == 0 assert retry.close_calls == 1 - assert cache.get(principal, None) is cached + assert cache.get(None) is cached class _ExpiredTokenError(Exception): From e2c2d4689896bb0e556b26e042ff6acdad2ccba1 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 20:23:45 +0000 Subject: [PATCH 07/10] Remove Snowflake and BigQuery session adapter inheritance --- .../src/kumo_bigquery/backend.py | 47 ++++--- .../src/kumo_bigquery/session.py | 68 ++------- .../kumo-bigquery/src/kumo_bigquery/sink.py | 36 +++-- .../tests/live/test_live_sink.py | 19 ++- packages/kumo-bigquery/tests/test_backend.py | 3 +- .../kumo-bigquery/tests/test_connection.py | 34 ++++- packages/kumo-bigquery/tests/test_sink.py | 11 +- packages/kumo-core/README.md | 25 ++-- .../kumo/engine/connector/snowflake.py | 3 +- .../test/test_bigquery_connector.py | 4 +- packages/kumo-engine/test/test_identity.py | 9 +- .../test/test_snowflake_connector.py | 3 +- .../src/kumo_snowflake/backend.py | 132 ++++++++++-------- .../src/kumo_snowflake/registry.py | 44 ++---- .../src/kumo_snowflake/session.py | 75 ++-------- .../kumo-snowflake/src/kumo_snowflake/sink.py | 93 +++++++----- packages/kumo-snowflake/tests/test_backend.py | 7 +- .../kumo-snowflake/tests/test_connection.py | 30 +++- .../kumo-snowflake/tests/test_registry.py | 8 +- packages/kumo-snowflake/tests/test_sink.py | 27 ++-- .../kumo-snowflake/tests/test_stage_fs.py | 12 +- 21 files changed, 345 insertions(+), 345 deletions(-) diff --git a/packages/kumo-bigquery/src/kumo_bigquery/backend.py b/packages/kumo-bigquery/src/kumo_bigquery/backend.py index 0d4de7a79..e73ec988a 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/backend.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/backend.py @@ -19,7 +19,6 @@ from kumo_bigquery.session import ( BigQueryConnection, - _BigQuerySessions, _billing_project, _name, _qualified, @@ -37,7 +36,6 @@ ) from kumo_core.sources.errors import PermanentSourceError, SourceNotFoundError from kumo_core.sources.layout import staging_dir -from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumoapi.data_source import DataSourceType from kumoapi.plugin import PrepareIngestResult, SourceConnector @@ -53,12 +51,11 @@ logger = logging.getLogger(__name__) -class BigQuerySourceBackend(_BigQuerySessions): +class BigQuerySourceBackend: r"""Resolves source tables by querying BigQuery. Args: - identity: Principal used for all connections opened by this backend. - connection: Connector-owned clients; supply instead of identity. + connection: Connector-owned clients shared with the sink backend. mode: The read mode every table is read under, or ``None`` to take whichever the reader offers first. staging_uri: A ``gs://`` prefix this run may export Parquet to. Without @@ -68,27 +65,41 @@ class BigQuerySourceBackend(_BigQuerySessions): Example: >>> from kumo_core.sources.principals import Principal + >>> from kumo_bigquery.session import BigQueryConnection >>> from kumoapi.data_source import ( ... BigQueryIdentityConfig, GoogleAmbientAuthentication) >>> principal = Principal('prod-bq', BigQueryIdentityConfig( ... authentication=GoogleAmbientAuthentication()), None) - >>> backend = BigQuerySourceBackend(identity=principal) + >>> backend = BigQuerySourceBackend(BigQueryConnection(principal)) """ source_type = DataSourceType.BIGQUERY def __init__( self, - identity: Optional[Principal] = None, + connection: BigQueryConnection, mode: Optional[ReadMode] = None, staging_uri: Optional[str] = None, - *, - connection: Optional[BigQueryConnection] = None, ) -> None: - super().__init__(identity, connection=connection) + self._connection = connection self.mode = mode self.staging_uri = staging_uri + def table_location(self, connector: SourceConnector, table_name: str) -> str: + """Return the fully qualified BigQuery table location. + + Args: + connector: BigQuery target configuration. + table_name: Unqualified table identifier. + + Returns: + The table location used in diagnostics. + + Raises: + ValueError: The connector belongs to a different provider. + """ + return _name(connector, table_name) + # Source area ########################################################## def list_tables( @@ -100,7 +111,7 @@ def list_tables( config = _target_config(connector) dataset = f'{config.project_id}.{config.dataset_id}' return SourceTableListResponse( - table_names=table_names(self._client(connector), dataset)) + table_names=table_names(self._connection.query_client(connector), dataset)) def get_table_config( self, @@ -176,7 +187,7 @@ def get_sample( dataset=config.dataset_id, max_bytes_billed=SQL_SAMPLE_MAX_SCAN_BYTES, job_timeout_ms=_milliseconds(sample_timeout(timeout, query))) - rows = _rows(self._client(connector), statement, job_config) + rows = _rows(self._connection.query_client(connector), statement, job_config) return sampled_table(table_name, columns, rows) def _table_sample(self, connector: SourceConnector, table_name: str, @@ -184,7 +195,7 @@ def _table_sample(self, connector: SourceConnector, table_name: str, from kumo_core.custom_sql import sample_select columns = self._columns(connector, table_name) rows = _rows( - self._client(connector), + self._connection.query_client(connector), sample_select(_qualified(connector, table_name), sample_rows)) return sampled_table(table_name, columns, rows) @@ -267,12 +278,12 @@ def _reader(self, connector: SourceConnector) -> BigQuerySourceReader: r"""Built per call: the reader is a thin wrapper and cheap to build, even though the clients it wraps are now cached. """ - credentials = self._credentials(connector) + credentials = self._connection.credentials() billing = _billing_project(connector) storage = (self._connection.storage_client(project=billing) if self.staging_uri is not None else None) return BigQuerySourceReader( - self._client(connector), + self._connection.query_client(connector), project=_target_config(connector).project_id, dataset=_target_config(connector).dataset_id, read_client=self._connection.read_client(), @@ -290,7 +301,7 @@ def _table(self, connector: SourceConnector, table_name: str) -> Any: """ from google.api_core.exceptions import NotFound try: - return self._client(connector).get_table( + return self._connection.query_client(connector).get_table( _name(connector, table_name)) except NotFound as error: config = _target_config(connector) @@ -314,7 +325,7 @@ def _embeddable(self, connector: SourceConnector, def _plan(self, connector: SourceConnector, sql: str) -> QueryPlan: from kumo_bigquery.sql import query_plan - return query_plan(self._client(connector), sql, + return query_plan(self._connection.query_client(connector), sql, project=_target_config(connector).project_id, dataset=_target_config(connector).dataset_id) @@ -335,7 +346,7 @@ def dtype_for(field_type: str, mode: Optional[str] = None, return dtype_for(field_type, mode, precision, scale) def __repr__(self) -> str: - return f'BigQuerySourceBackend(identity={self._identity!r})' + return f'BigQuerySourceBackend(connection={self._connection!r})' def _milliseconds(seconds: Optional[int]) -> Optional[int]: diff --git a/packages/kumo-bigquery/src/kumo_bigquery/session.py b/packages/kumo-bigquery/src/kumo_bigquery/session.py index c7e49e0e1..42a9fa76d 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/session.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/session.py @@ -176,8 +176,17 @@ def credentials(self) -> Credentials: _require_credentials(credentials) return credentials - def query_client(self, *, project: str, location: str) -> Any: - """Return the cached query client for the given billing project and region.""" + def query_client(self, connector: SourceConnector) -> Any: + """Return the cached query client for a connector's billing target. + + Args: + connector: Dataset target, billing project, and region. + + Returns: + The query client owned by this connection for that target. + """ + project = _billing_project(connector) + location = _target_config(connector).location key = (project, location) with self._lock: client = self._query.get(key) @@ -237,58 +246,3 @@ def _rows(client: Any, sql: str, job_config: Any = None) -> List[Any]: from kumo_bigquery.sql import query_result return [tuple(row) for row in query_result(client.query, sql, job_config)] - - -class _BigQuerySessions: - r"""Resolving a connector to the BigQuery clients built from its - identity. - - Args: - identity: Principal used for all connections opened by this backend. - connection: Connector-owned clients shared with its other backend. - Supply this instead of identity. - """ - - def __init__(self, identity: Principal | None = None, *, - connection: BigQueryConnection | None = None) -> None: - if identity is not None and connection is not None: - raise ValueError("Pass identity or connection, not both.") - self._connection = (connection if connection is not None - else BigQueryConnection(identity)) - - @property - def _identity(self) -> Principal | None: - return self._connection.identity - - def _credentials(self, connector: SourceConnector) -> Credentials: - r"""Raw credentials for a connector, for the one caller that needs - them directly rather than a client built from them: - ``backend.py``'s reader construction hands a credentials object - straight to ``BigQuerySourceReader``. - - Defined here rather than inlined at the call site so that a test - replacing ``_credentials_for`` at the module level -- see - ``test/_identities.py``'s ``use_session`` -- is seen by every path - that resolves credentials, including this one. A module that - imported ``_credentials_for`` directly would keep its own binding of - the original function and miss the replacement. - """ - self._principal(connector) - return self._connection.credentials() - - def table_location(self, connector: SourceConnector, - table_name: str) -> str: - return _name(connector, table_name) - - def _client(self, connector: SourceConnector) -> Any: - self._principal(connector) - return self._connection.query_client( - project=_billing_project(connector), - location=_target_config(connector).location) - - def _principal(self, connector: SourceConnector) -> Principal: - if isinstance(self._identity, Principal): - return self._identity - raise ValueError( - f"Connector {connector.id!r} needs a Principal passed to its backend. " - "Identity name, ID, and slug lookup is no longer supported.") diff --git a/packages/kumo-bigquery/src/kumo_bigquery/sink.py b/packages/kumo-bigquery/src/kumo_bigquery/sink.py index 48895b817..4346fa05f 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/sink.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/sink.py @@ -23,14 +23,13 @@ from kumo_bigquery import errors, staging, streaming, write from kumo_bigquery.session import ( BigQueryConnection, - _BigQuerySessions, _billing_project, + _name, _target_config, ) from kumo_bigquery.staging import StagingLocation from kumo_core.sources.diagnostics import translated from kumo_core.sources.errors import SourceAccessDeniedError -from kumo_core.sources.principals import Principal from kumo_core.sources.protocol import require_mode, staged_first from kumo_core.sources.types import Capability, ReadMode from kumoapi.jobs import WriteMode @@ -49,13 +48,12 @@ class _LocalError(Exception): """Carries a local file error past the BigQuery error translation.""" -class BigQuerySinkBackend(_BigQuerySessions): +class BigQuerySinkBackend: r"""Writes prediction Parquet files to a table in the connector's dataset. Args: - identity: Principal used for all connections opened by this backend. - connection: Connector-owned clients; supply instead of identity. + connection: Connector-owned clients shared with the source backend. staging_uri: Optional ``gs://`` prefix. Output is uploaded under ``/_kumo.export//``, loaded by one job and deleted. Without one, output is streamed through the Storage @@ -64,19 +62,33 @@ class BigQuerySinkBackend(_BigQuerySessions): :meth:`write_modes` offers first. """ - def __init__(self, identity: Optional[Principal] = None, *, + def __init__(self, connection: BigQueryConnection, *, staging_uri: Optional[str] = None, - mode: Optional[ReadMode] = None, - connection: Optional[BigQueryConnection] = None) -> None: + mode: Optional[ReadMode] = None) -> None: if mode is ReadMode.STAGED and not staging_uri: raise ValueError('mode=STAGED needs a staging_uri') - super().__init__(identity, connection=connection) + self._connection = connection self.staging_uri = staging_uri self.mode = mode self._staging = (StagingLocation.parse(staging_uri) if staging_uri else None) self._staging_capability: Optional[Capability] = None + def table_location(self, connector: SourceConnector, table_name: str) -> str: + """Return the fully qualified BigQuery table location. + + Args: + connector: BigQuery target configuration. + table_name: Unqualified table identifier. + + Returns: + The table location used in diagnostics. + + Raises: + ValueError: The connector belongs to a different provider. + """ + return _name(connector, table_name) + def preflight_write_files( self, connector: SourceConnector, @@ -140,7 +152,7 @@ def write_files( client, self._connection.write_client(), selected, ref, replace=replace, existing=existing, extra_columns=extra_columns, - credentials=self._credentials(connector)) + credentials=self._connection.credentials()) return ref def write_table( @@ -168,7 +180,7 @@ def _dataset(self, connector: SourceConnector, f'{table_name!r}.') config = _target_config(connector) dataset = f'{config.project_id}.{config.dataset_id}' - client = self._client(connector) + client = self._connection.query_client(connector) write.require_dataset(client, dataset, config.location) return client, dataset @@ -250,5 +262,5 @@ def _translated(connector: SourceConnector, raise local.__cause__ from None # type: ignore[misc] def __repr__(self) -> str: - return (f'BigQuerySinkBackend(identity={self._identity!r}, ' + return (f'BigQuerySinkBackend(connection={self._connection!r}, ' f'staging_uri={self.staging_uri!r}, mode={self.mode!r})') diff --git a/packages/kumo-bigquery/tests/live/test_live_sink.py b/packages/kumo-bigquery/tests/live/test_live_sink.py index 5aedab7ba..278716419 100644 --- a/packages/kumo-bigquery/tests/live/test_live_sink.py +++ b/packages/kumo-bigquery/tests/live/test_live_sink.py @@ -39,6 +39,7 @@ import pyarrow.parquet as pq # noqa: E402 from google.api_core.exceptions import NotFound # noqa: E402 from google.cloud import bigquery, storage # noqa: E402 +from kumo_bigquery.session import BigQueryConnection # noqa: E402 from kumo_bigquery.sink import BigQuerySinkBackend # noqa: E402 from kumo_bigquery.write import OutputSchemaMismatchError # noqa: E402 from kumo_core.sources.errors import ( # noqa: E402 @@ -90,8 +91,10 @@ def client(): @pytest.fixture(params=["staged", "streamed"]) def sink(request): if request.param == "streamed": - return BigQuerySinkBackend(identity=IDENTITY) - return BigQuerySinkBackend(identity=IDENTITY, staging_uri=STAGING_URI, mode=ReadMode.STAGED) + return BigQuerySinkBackend(connection=BigQueryConnection(IDENTITY)) + return BigQuerySinkBackend( + connection=BigQueryConnection(IDENTITY), staging_uri=STAGING_URI, + mode=ReadMode.STAGED) def staged_objects(): @@ -281,7 +284,7 @@ def test_failed_load_leaves_table(client, sink, tmp_path, mode): def test_extra_columns_are_stamped(client, tmp_path): name = f"preds_{uuid.uuid4().hex[:6]}" - BigQuerySinkBackend(identity=IDENTITY).write_files( + BigQuerySinkBackend(connection=BigQueryConnection(IDENTITY)).write_files( connector(), name, shards(tmp_path, [2, 3]), extra_columns={"RUN": "r1"}) values = { row.RUN @@ -310,7 +313,7 @@ def test_preflight_accepts_writable_destination(client, sink, tmp_path): def test_preflight_rejects_unusable_destinations(client): - sink = BigQuerySinkBackend(identity=IDENTITY) + sink = BigQuerySinkBackend(connection=BigQueryConnection(IDENTITY)) with pytest.raises(SourceNotFoundError, match="does not exist"): sink.preflight_write_files(connector(dataset=f"missing_{RUN}"), "preds") with pytest.raises(SourceNotFoundError, match="does not exist"): @@ -325,9 +328,11 @@ def test_preflight_rejects_unusable_destinations(client): sink.preflight_write_files(connector(), "other.preds") denied = "gs://gcp-public-data-landsat/kumo" with pytest.raises(UnsupportedReadModeError, match="offers streamed"): - BigQuerySinkBackend(identity=IDENTITY, staging_uri=denied, mode=ReadMode.STAGED).\ - preflight_write_files(connector(), "preds") - fallback = BigQuerySinkBackend(identity=IDENTITY, staging_uri=denied) + BigQuerySinkBackend( + connection=BigQueryConnection(IDENTITY), staging_uri=denied, + mode=ReadMode.STAGED).preflight_write_files(connector(), "preds") + fallback = BigQuerySinkBackend( + connection=BigQueryConnection(IDENTITY), staging_uri=denied) fallback.preflight_write_files(connector(), "preds") assert fallback.write_modes(connector()) == (ReadMode.STREAMED, ) with pytest.raises(NotFound): diff --git a/packages/kumo-bigquery/tests/test_backend.py b/packages/kumo-bigquery/tests/test_backend.py index 5738b0f47..6998d583c 100644 --- a/packages/kumo-bigquery/tests/test_backend.py +++ b/packages/kumo-bigquery/tests/test_backend.py @@ -3,6 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 from types import SimpleNamespace +from unittest.mock import Mock import pytest from kumo_bigquery.backend import BigQuerySourceBackend @@ -19,7 +20,7 @@ def test_zero_row_read_is_an_empty_source(rows, tmp_path, monkeypatch): mode_used=ReadMode.STREAMED, num_rows=rows) monkeypatch.setattr("kumo_core.sources.prepare.read_table", lambda *args, **kwargs: staged) - backend = BigQuerySourceBackend() + backend = BigQuerySourceBackend(connection=Mock()) for name in ("_declared", "_reader"): monkeypatch.setattr(backend, name, lambda *args, **kwargs: {}) connector = SimpleNamespace(id="c") diff --git a/packages/kumo-bigquery/tests/test_connection.py b/packages/kumo-bigquery/tests/test_connection.py index f8b2a4d34..2f82bad87 100644 --- a/packages/kumo-bigquery/tests/test_connection.py +++ b/packages/kumo-bigquery/tests/test_connection.py @@ -5,6 +5,7 @@ import pickle from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace from unittest.mock import Mock import pytest @@ -13,6 +14,7 @@ from kumo_bigquery.sink import BigQuerySinkBackend from kumo_core.sources.principals import Principal from kumoapi.data_source import ( + BigQueryConnectorResourceConfig, BigQueryIdentityConfig, GoogleServiceAccountKeyAuthentication, GoogleServiceAccountKeyCredentials, @@ -57,9 +59,17 @@ def test_clients_are_reused_only_within_their_owner( monkeypatch.setattr(session, f"_{kind}_client", build) first = session.BigQueryConnection(principals[0]) second = session.BigQueryConnection(principals[1]) - options = {"project": "sample-project"} if kind in {"query", "storage"} else {} + options: dict[str, object] = ( + {"project": "sample-project"} if kind in {"query", "storage"} else {} + ) if kind == "query": - options["location"] = "US" + options = { + "connector": SimpleNamespace( + config=BigQueryConnectorResourceConfig( + project_id="sample-project", dataset_id="dataset", location="US" + ) + ) + } first_client = getattr(first, f"{kind}_client")(**options) repeated = getattr(first, f"{kind}_client")(**options) @@ -142,3 +152,23 @@ def test_close_attempts_every_client_after_a_failure( write.close.assert_called_once_with() owner.close() assert read.close.call_count == 1 + + +def test_backend_table_locations_use_the_data_project( + principals: tuple[Principal, Principal], +) -> None: + """Diagnostic locations identify source data independently of billing.""" + connector = SimpleNamespace( + config=BigQueryConnectorResourceConfig( + project_id="sample-project", + dataset_id="dataset", + location="US", + billing_project_id="billing-project", + ) + ) + owner = session.BigQueryConnection(principals[0]) + source = BigQuerySourceBackend(owner) + sink = BigQuerySinkBackend(owner) + + assert source.table_location(connector, "events") == "sample-project.dataset.events" + assert sink.table_location(connector, "events") == "sample-project.dataset.events" diff --git a/packages/kumo-bigquery/tests/test_sink.py b/packages/kumo-bigquery/tests/test_sink.py index d11ff1672..7eb7f268f 100644 --- a/packages/kumo-bigquery/tests/test_sink.py +++ b/packages/kumo-bigquery/tests/test_sink.py @@ -153,17 +153,16 @@ def close(self): monkeypatch.setattr( 'google.cloud.bigquery_storage_v1.writer.AppendRowsStream', AppendRowsStream) - monkeypatch.setattr(BigQuerySinkBackend, '_client', + monkeypatch.setattr(session.BigQueryConnection, 'query_client', lambda self, connector: warehouse) monkeypatch.setattr(BigQuerySinkBackend, '_storage', lambda self, connector: storage) - monkeypatch.setattr(BigQuerySinkBackend, '_principal', - lambda self, connector: SimpleNamespace(name='n')) - monkeypatch.setattr(BigQuerySinkBackend, '_credentials', - lambda self, connector: object()) + monkeypatch.setattr(session.BigQueryConnection, 'credentials', + lambda self: object()) monkeypatch.setattr(session.BigQueryConnection, 'write_client', lambda self: write_client) - return BigQuerySinkBackend(**options), write_client + return BigQuerySinkBackend(connection=session.BigQueryConnection(None), + **options), write_client return make diff --git a/packages/kumo-core/README.md b/packages/kumo-core/README.md index 0c59b3948..eaa158c00 100644 --- a/packages/kumo-core/README.md +++ b/packages/kumo-core/README.md @@ -97,17 +97,20 @@ Kumo is not yet a uv workspace. These commands operate on `packages/kumo-core` e ## Source identities -Source and sink backends accept `kumo_core.sources.principals.Principal` values. -Engine connectors convert convenience identities such as `S3Identity` into a -principal before constructing their backends. When calling a backend directly, -pass `identity.principal` or construct a `Principal` yourself. Configuration and -explicit credentials travel with that value; ambient credentials and token-file -contents are resolved on the receiving worker. Identity names, IDs, and objects -containing only a slug no longer resolve through a process-global registry. - -Pass a convenience identity on an engine connector, or supply `identity=principal` -to a backend when a hosted connector contains only credential-free metadata. For -example: +Provider authentication uses `kumo_core.sources.principals.Principal` values. +Engine connectors normalize convenience identities such as `S3Identity` before +constructing their backends. Configuration and explicit credentials travel with +that value; ambient credentials and token-file contents are resolved on the +receiving worker. Identity names, IDs, and slug-only metadata no longer resolve +through a process-global registry. + +Snowflake and BigQuery backends require a `SnowflakeConnection` or +`BigQueryConnection`, constructed by their engine connector and shared between its +backends. Direct provider callers must explicitly construct that owner from a +principal, for example `SnowflakeSourceBackend(SnowflakeConnection(principal))`. +These backends no longer accept an `identity` argument or create their own owner. + +Other provider backends accept `identity=principal`. For example: ```python from kumo_core.sources.principals import Principal diff --git a/packages/kumo-engine/kumo/engine/connector/snowflake.py b/packages/kumo-engine/kumo/engine/connector/snowflake.py index fb5b77a6e..433739585 100644 --- a/packages/kumo-engine/kumo/engine/connector/snowflake.py +++ b/packages/kumo-engine/kumo/engine/connector/snowflake.py @@ -114,8 +114,7 @@ def sink_backend(self) -> ArtifactSink: def session(self) -> Any: r"""The Snowpark session this connector reads through.""" - with self.source_backend._session(self) as session: - return session + return self._connection.get(self) def source_table_for(self, table_name: str) -> SnowflakeSourceTable: return SnowflakeSourceTable( diff --git a/packages/kumo-engine/test/test_bigquery_connector.py b/packages/kumo-engine/test/test_bigquery_connector.py index 952f911f5..33b70dffe 100644 --- a/packages/kumo-engine/test/test_bigquery_connector.py +++ b/packages/kumo-engine/test/test_bigquery_connector.py @@ -32,7 +32,7 @@ def test_read_configuration_reaches_the_cached_backend(staging_uri, backend = connector.source_backend assert connector.source_backend is backend - assert backend._identity == identity.principal + assert backend._connection.identity == identity.principal assert backend.staging_uri == staging_uri assert backend.mode is expected_mode @@ -63,7 +63,7 @@ def test_sink_backend_is_cached_and_carries_configuration(): assert connector.sink_backend is sink assert isinstance(sink, BigQuerySinkBackend) - assert sink._identity == identity.principal + assert sink._connection.identity == identity.principal assert sink.staging_uri == 'gs://staging/kumo' diff --git a/packages/kumo-engine/test/test_identity.py b/packages/kumo-engine/test/test_identity.py index f5b356fee..de8740978 100644 --- a/packages/kumo-engine/test/test_identity.py +++ b/packages/kumo-engine/test/test_identity.py @@ -72,6 +72,11 @@ def test_source_backends_use_explicit_principals(provider: str) -> None: } connector = connectors[provider]() backend = connector.source_backend + if provider == "bigquery": + principal = backend._connection.identity + assert principal == connector.identity.principal + assert connector.sink_backend._connection is backend._connection + return principal = backend._identity assert isinstance(principal, Principal) assert principal == connector.identity.principal @@ -84,7 +89,3 @@ def test_source_backends_use_explicit_principals(provider: str) -> None: other = Principal("other", principal.config, principal.credentials) assert backend._principal(SimpleNamespace(id="remote", identity=other)) is principal - - if provider == "bigquery": - assert backend._connection is connector.sink_backend._connection - assert backend._connection is connector._connection diff --git a/packages/kumo-engine/test/test_snowflake_connector.py b/packages/kumo-engine/test/test_snowflake_connector.py index 8f3564c5e..21c3570ef 100644 --- a/packages/kumo-engine/test/test_snowflake_connector.py +++ b/packages/kumo-engine/test/test_snowflake_connector.py @@ -119,7 +119,6 @@ def test_session_is_the_readers_session(monkeypatch): monkeypatch.setattr( sessions.SnowflakeConnection, 'get', lambda self, target, fresh=False: calls.append(target) or 'live') - monkeypatch.setattr(type(connector.source_backend), '_principal', - lambda self, target: 'principal') + assert connector.source_backend._connection is connector._connection assert connector.session() == 'live' assert calls == [connector] diff --git a/packages/kumo-snowflake/src/kumo_snowflake/backend.py b/packages/kumo-snowflake/src/kumo_snowflake/backend.py index 3d3e5999a..6aec3e19f 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/backend.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/backend.py @@ -28,13 +28,13 @@ ) from kumo_core.sources.errors import PermanentSourceError, SourceNotFoundError from kumo_core.sources.layout import staging_dir -from kumo_core.sources.principals import Principal from kumo_core.sources.types import ReadMode from kumo_snowflake.session import ( SnowflakeConnection, SnowflakeSession, + _qualified, _require_snowpark, - _SnowflakeSessions, + _table_location, _target_config, resolved, ) @@ -53,37 +53,51 @@ from kumoapi.typing import Dtype -class SnowflakeSourceBackend(_SnowflakeSessions): +class SnowflakeSourceBackend: r"""Resolves source tables by querying Snowflake. Args: - identity: Principal used for all connections opened by this backend. - connection: Connector-owned sessions; supply instead of identity. + connection: Connector-owned sessions shared with the sink backend. + mode: Explicit read mode, or None for the staged-only provider default. Example: >>> from kumo_core.sources.principals import Principal + >>> from kumo_snowflake.session import SnowflakeConnection >>> from kumoapi.data_source import ( ... SnowflakeAuthenticationKind, SnowflakeIdentityConfig) >>> principal = Principal('prod-sf', SnowflakeIdentityConfig( ... account='account', ... authentication=SnowflakeAuthenticationKind.OAUTH_TOKEN_FILE), None) - >>> backend = SnowflakeSourceBackend(identity=principal) + >>> backend = SnowflakeSourceBackend(SnowflakeConnection(principal)) """ source_type = DataSourceType.SNOWFLAKE def __init__( self, - identity: Optional[Principal] = None, + connection: SnowflakeConnection, mode: Optional[ReadMode] = None, - *, - connection: Optional[SnowflakeConnection] = None, ) -> None: - super().__init__(identity, connection=connection) + self._connection = connection #: Snowflake unloads and offers nothing else; the argument exists so #: one caller can name a mode whichever warehouse it reaches. self.mode = mode + def table_location(self, connector: SourceConnector, table_name: str) -> str: + """Return the diagnostic account and qualified table location. + + Args: + connector: Snowflake target configuration. + table_name: Unqualified table identifier. + + Returns: + The table location used in diagnostics. + + Raises: + ValueError: The connector belongs to a different provider. + """ + return _table_location(self._connection.identity, connector, table_name) + # Source area ########################################################## def list_tables( @@ -94,14 +108,14 @@ def list_tables( del project_id from kumo_snowflake.catalog import tables config = _target_config(connector) - with self._session(connector) as session: - _require_snowpark(session) - cursor = session.connection.cursor() - try: - names = tables(cursor, database=resolved(config.database), - schema=resolved(config.schema_name)) - finally: - cursor.close() + session = self._connection.get(connector) + _require_snowpark(session) + cursor = session.connection.cursor() + try: + names = tables(cursor, database=resolved(config.database), + schema=resolved(config.schema_name)) + finally: + cursor.close() return SourceTableListResponse(table_names=names) def get_table_config( @@ -151,16 +165,16 @@ def get_sample( del project_id query = self._embeddable(connector, sql) - source = (f'({query})' if query is not None else self._qualified( + source = (f'({query})' if query is not None else _qualified( connector, table_name)) # One span for both statements: the columns and the rows they name # have to come from the same warehouse. - with self._session(connector) as session: - columns = self._columns(connector, table_name, query) - from kumo_snowflake.results import sample - frame = sample(session.connection, source, sample_rows, - timeout=sample_timeout(timeout, query)) - rows = frame.itertuples(index=False, name=None) + session = self._connection.get(connector) + columns = self._columns(connector, table_name, query) + from kumo_snowflake.results import sample + frame = sample(session.connection, source, sample_rows, + timeout=sample_timeout(timeout, query)) + rows = frame.itertuples(index=False, name=None) return sampled_table(table_name, columns, rows) def get_download_urls( @@ -188,8 +202,8 @@ def get_data_version( unload that would otherwise establish it. """ del project_id # a local runtime has no projects - with self._session(connector) as session: - return self._reader(connector, session).data_version(table_name) + session = self._connection.get(connector) + return self._reader(connector, session).data_version(table_name) def prepare_ingest( self, @@ -224,11 +238,11 @@ def prepare_ingest( # Held for the whole unload, not just to select the warehouse: the # reader runs on the connection behind this session, so a connector # that took it mid-read would move the unload to its own warehouse. - with self._session(connector) as session: - staged = read_table( - self._reader(connector, session), table_name, str(destination), - columns=self._declared(connector, table_name, dtypes, query), - mode=self.mode, sql=query, version=data_version) + session = self._connection.get(connector) + staged = read_table( + self._reader(connector, session), table_name, str(destination), + columns=self._declared(connector, table_name, dtypes, query), + mode=self.mode, sql=query, version=data_version) if not staged.num_rows: raise PermanentSourceError( f'Unloading {table_name} returned no rows. An empty source ' @@ -267,15 +281,15 @@ def _reader(self, connector: SourceConnector, def _exists(self, connector: SourceConnector, table_name: str) -> bool: from kumo_snowflake.catalog import table_exists config = _target_config(connector) - with self._session(connector) as session: - _require_snowpark(session) - cursor = session.connection.cursor() - try: - return table_exists(cursor, database=resolved(config.database), - schema=resolved(config.schema_name), - table=table_name) - finally: - cursor.close() + session = self._connection.get(connector) + _require_snowpark(session) + cursor = session.connection.cursor() + try: + return table_exists(cursor, database=resolved(config.database), + schema=resolved(config.schema_name), + table=table_name) + finally: + cursor.close() def _embeddable(self, connector: SourceConnector, sql: Optional[str]) -> Optional[str]: @@ -296,14 +310,14 @@ def _embeddable(self, connector: SourceConnector, def _described(self, connector: SourceConnector, sql: str) -> List[SourceColumn]: - with self._session(connector) as session: - _require_snowpark(session) - cursor = session.connection.cursor() - try: - return source_columns( - describe_columns(cursor, f'SELECT * FROM ({sql})')) - finally: - cursor.close() + session = self._connection.get(connector) + _require_snowpark(session) + cursor = session.connection.cursor() + try: + return source_columns( + describe_columns(cursor, f'SELECT * FROM ({sql})')) + finally: + cursor.close() def _columns(self, connector: SourceConnector, table_name: str, sql: Optional[str] = None) -> List[SourceColumn]: @@ -312,15 +326,15 @@ def _columns(self, connector: SourceConnector, table_name: str, from kumo_snowflake.catalog import columns config = _target_config(connector) - with self._session(connector) as session: - _require_snowpark(session) - cursor = session.connection.cursor() - try: - metadata = columns(cursor, database=resolved(config.database), - schema=resolved(config.schema_name), - table=table_name) - finally: - cursor.close() + session = self._connection.get(connector) + _require_snowpark(session) + cursor = session.connection.cursor() + try: + metadata = columns(cursor, database=resolved(config.database), + schema=resolved(config.schema_name), + table=table_name) + finally: + cursor.close() if not metadata: raise SourceNotFoundError( f'Invalid table {table_name}: it has no columns in ' @@ -340,4 +354,4 @@ def dtype_for(data_type: str, return dtype_for(data_type, numeric_scale) def __repr__(self) -> str: - return f'SnowflakeSourceBackend(identity={self._identity!r})' + return f'SnowflakeSourceBackend(connection={self._connection!r})' diff --git a/packages/kumo-snowflake/src/kumo_snowflake/registry.py b/packages/kumo-snowflake/src/kumo_snowflake/registry.py index 6658d1ba7..3076d0267 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/registry.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/registry.py @@ -29,7 +29,6 @@ TYPE_CHECKING, Any, Callable, - ContextManager, Dict, Iterator, List, @@ -38,7 +37,7 @@ ) from kumo_snowflake.session import ( - SnowflakeSession, + SnowflakeConnection, _require_snowpark, _target_config, resolved, @@ -433,24 +432,9 @@ def _next_version(registry: Any, model_name: str) -> str: class SnowflakeModelRegistryMixin: - r"""The model half of :class:`SnowflakeSinkBackend`. - - Mixed in rather than written inline so the module holding it -- and the - ``snowflake.ml`` import it needs -- is loaded only when a model actually - moves. It reaches the warehouse through the same - :class:`~kumo_snowflake.session._SnowflakeSessions` - resolution the table path uses, so a model is published under the identity - its connector names and not some other one. - """ - if TYPE_CHECKING: - # The one thing this mixin needs from its host, declared rather than - # reached for blindly: every class that mixes it in also inherits - # `_SnowflakeSessions`, which supplies the implementation. - def _session( - self, - connector: SourceConnector, - ) -> ContextManager[SnowflakeSession]: - ... + """Model-registry operations using the sink's connector-owned connection.""" + + _connection: SnowflakeConnection def check_model_location(self, connector: SourceConnector, location: ModelRegistryLocation) -> None: @@ -468,13 +452,13 @@ def _registry(self, connector: SourceConnector) -> Iterator["Registry"]: r"""A registry statement is a session statement, so the caller keeps the warehouse for as long as it is asking the registry anything. """ - with self._session(connector) as session: - _require_snowpark(session) - yield _require_registry()( - session=session, - database_name=resolved(_target_config(connector).database), - schema_name=resolved(_target_config(connector).schema_name), - ) + session = self._connection.get(connector) + _require_snowpark(session) + yield _require_registry()( + session=session, + database_name=resolved(_target_config(connector).database), + schema_name=resolved(_target_config(connector).schema_name), + ) def publish_model( self, @@ -622,10 +606,8 @@ def fetch_model( 'ModelRegistryLocation.') destination = Path(local_dir) - with self._registry(connector) as registry, \ - self._session(connector) as session: - # Resolved before anything on disk is touched: a name the registry - # does not know must not cost the caller the bundle already there. + session = self._connection.get(connector) + with self._registry(connector) as registry: model = registry.get_model(location.model_name) if location.alias is not None: if resolved(location.alias) not in _alias_holders(model): diff --git a/packages/kumo-snowflake/src/kumo_snowflake/session.py b/packages/kumo-snowflake/src/kumo_snowflake/session.py index e699e9184..359e0d4df 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/session.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/session.py @@ -345,13 +345,15 @@ def close(self) -> None: @contextmanager -def _owned_session(principal: Principal, +def _owned_session(principal: Principal | None, connector: Optional[SourceConnector]) -> Iterator[Session]: """Open one uncached session and close it when the caller finishes. Recovery uses this instead of replacing a cache entry because another request can legitimately still be using that shared session. """ + if principal is None: + raise ValueError("Snowflake connection needs a Principal.") session = _connect(principal, connector) try: yield session @@ -403,64 +405,17 @@ def probe(principal: Principal) -> None: pass -class _SnowflakeSessions: - r"""Resolving a connector to a live Snowpark session. - - Shared by the two areas that talk to a warehouse -- - :class:`~kumo_snowflake.backend.SnowflakeSourceBackend` and - :class:`~kumo_snowflake.sink.SnowflakeSinkBackend` -- - because a session is resolved the same way whichever direction the data is - moving. A reader that resolved identities differently from the writer - beside it is the whole reason this class is not written twice. - - Args: - identity: Principal used for all connections opened by this backend. - connection: Connector-owned connection shared with its other backend. - Supply this instead of identity. - """ - - def __init__(self, identity: Principal | None = None, *, - connection: SnowflakeConnection | None = None) -> None: - if identity is not None and connection is not None: - raise ValueError("Pass identity or connection, not both.") - self._connection = (connection if connection is not None - else SnowflakeConnection(identity)) - - @property - def _identity(self) -> Principal | None: - return self._connection.identity - - @contextmanager - def _session(self, connector: SourceConnector, *, - fresh: bool = False) -> Iterator[SnowflakeSession]: - r"""Yields a session already pointed at this connector's target. +def _qualified(connector: SourceConnector, table_name: str) -> str: + """Return the quoted database, schema, and table identifier.""" + config = _target_config(connector) + return (f'{_quoted(resolved(config.database))}.' + f'{_quoted(resolved(config.schema_name))}.{_quoted(table_name)}') - No lock and nothing to restore: the session belongs to this - ``(identity, target)`` pair, so no other caller can move it out from - under the statements run here. - """ - self._principal(connector) - yield self._connection.get(connector, fresh=fresh) - def _principal(self, connector: SourceConnector) -> Principal: - if isinstance(self._identity, Principal): - return self._identity - raise ValueError( - f"Connector {connector.id!r} needs a Principal passed to its backend. " - "Identity name, ID, and slug lookup is no longer supported.") - - def table_location(self, connector: SourceConnector, - table_name: str) -> str: - """``account/"DB"."SCHEMA"."TABLE"``; the account when it resolves.""" - try: - account = _snowflake_config(self._principal(connector)).account - except Exception: - account = None - qualified = self._qualified(connector, table_name) - return f'{account}/{qualified}' if account else qualified - - @staticmethod - def _qualified(connector: SourceConnector, table_name: str) -> str: - return (f'{_quoted(resolved(_target_config(connector).database))}.' - f'{_quoted(resolved(_target_config(connector).schema_name))}.' - f'{_quoted(table_name)}') +def _table_location(principal: Principal | None, connector: SourceConnector, + table_name: str) -> str: + """Return an account-qualified diagnostic location when configured.""" + qualified = _qualified(connector, table_name) + if principal is not None and isinstance(principal.config, SnowflakeIdentityConfig): + return f'{principal.config.account}/{qualified}' + return qualified diff --git a/packages/kumo-snowflake/src/kumo_snowflake/sink.py b/packages/kumo-snowflake/src/kumo_snowflake/sink.py index ace2e55cf..14811b574 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/sink.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/sink.py @@ -9,6 +9,7 @@ the only real decision is what to do about a table already sitting there. """ +from contextlib import nullcontext from typing import Optional import numpy as np @@ -18,9 +19,11 @@ from kumo_snowflake.errors import is_lapsed_credential from kumo_snowflake.registry import SnowflakeModelRegistryMixin from kumo_snowflake.session import ( + SnowflakeConnection, _owned_session, + _qualified, _require_snowpark, - _SnowflakeSessions, + _table_location, _target_config, resolved, ) @@ -58,7 +61,9 @@ def _refuse_nested_columns(frame: pd.DataFrame) -> None: f"exporting.") -class _SnowflakeTables(SnowflakeModelRegistryMixin, _SnowflakeSessions): +class _SnowflakeTables(SnowflakeModelRegistryMixin): + """Table writes behind the sink's stage-file routing layer.""" + def write_table( self, connector: SourceConnector, @@ -94,27 +99,27 @@ def write_table( # hold one. A warehouse write is a single statement, so there is # nothing here for a rerun to recognise. del project_id, export_id - with self._session(connector) as session: - _require_snowpark(session) - _refuse_nested_columns(frame) - session.write_pandas( - frame, - table_name=table_name, - database=resolved(_target_config(connector).database), - schema=resolved(_target_config(connector).schema_name), - # Creates the table on first export and, with `overwrite`, on - # every later one. A prediction frame's schema is the model's - # output schema, so declaring it here would only restate what - # the frame already carries. - auto_create_table=True, - overwrite=write_mode == WriteMode.OVERWRITE, - quote_identifiers=True, - # Without it a tz-aware column lands as a number of nanoseconds - # rather than a timestamp, which is how an anchor time silently - # stops being a time. - use_logical_type=True, - ) - return self._qualified(connector, table_name) + session = self._connection.get(connector) + _require_snowpark(session) + _refuse_nested_columns(frame) + session.write_pandas( + frame, + table_name=table_name, + database=resolved(_target_config(connector).database), + schema=resolved(_target_config(connector).schema_name), + # Creates the table on first export and, with `overwrite`, on + # every later one. A prediction frame's schema is the model's + # output schema, so declaring it here would only restate what + # the frame already carries. + auto_create_table=True, + overwrite=write_mode == WriteMode.OVERWRITE, + quote_identifiers=True, + # Without it a tz-aware column lands as a number of nanoseconds + # rather than a timestamp, which is how an anchor time silently + # stops being a time. + use_logical_type=True, + ) + return _qualified(connector, table_name) def write_files(self, connector, table_name, files, write_mode=WriteMode.OVERWRITE, project_id=None, *, @@ -126,9 +131,9 @@ def write_files(self, connector, table_name, files, selected = [str(path) for path in selected_local_parquet_files(files)] def export(*, retry: bool = False) -> None: - session_context = (_owned_session(self._principal(connector), - connector) - if retry else self._session(connector)) + session_context = ( + _owned_session(self._connection.identity, connector) + if retry else nullcontext(self._connection.get(connector))) with session_context as session: _require_snowpark(session) target = _LocalArtifactConnection(session, connector, @@ -147,18 +152,34 @@ def export(*, retry: bool = False) -> None: # refreshed mounted token and repeat only this idempotent # overwrite export; never repeat training or prediction. export(retry=True) - return self._qualified(connector, table_name) + return _qualified(connector, table_name) class SnowflakeSinkBackend(FileStoreRouting, _SnowflakeTables): - r"""Writes artifacts to Snowflake tables and models to its Model Registry. - - Table identifiers are written as given, quoted. + """Write tables, stage files, and models through a connector-owned connection. Args: - identity: Principal used for all connections opened by this backend. + connection: Snowflake sessions shared with the source backend. """ + def __init__(self, connection: SnowflakeConnection) -> None: + self._connection = connection + + def table_location(self, connector: SourceConnector, table_name: str) -> str: + """Return the diagnostic account and qualified table location. + + Args: + connector: Snowflake target configuration. + table_name: Unqualified table identifier. + + Returns: + The table location used in diagnostics. + + Raises: + ValueError: The connector belongs to a different provider. + """ + return _table_location(self._connection.identity, connector, table_name) + def holds_files(self, connector, path): """Whether ``path`` names a named internal stage location.""" try: @@ -170,12 +191,12 @@ def holds_files(self, connector, path): def filesystem(self, connector, path): """A pyarrow filesystem for an ``@DB.SCHEMA.STAGE/prefix`` path.""" from kumo_snowflake.stage_fs import stage_filesystem - with self._session(connector) as session: - _require_snowpark(session) - return stage_filesystem(session, path) + session = self._connection.get(connector) + _require_snowpark(session) + return stage_filesystem(session, path) def __repr__(self) -> str: - return f'SnowflakeSinkBackend(identity={self._identity!r})' + return f'SnowflakeSinkBackend(connection={self._connection!r})' class _LocalArtifactConnection: @@ -186,7 +207,7 @@ def __init__(self, session, connector, extra_columns): self.extra_columns = extra_columns def _qualified_table_name(self, table_name): - return _SnowflakeSessions._qualified(self.connector, table_name) + return _qualified(self.connector, table_name) def execute_meta_query(self, context, statement, *, creds_clause=None): if creds_clause: diff --git a/packages/kumo-snowflake/tests/test_backend.py b/packages/kumo-snowflake/tests/test_backend.py index 8e7888547..2aa7450d4 100644 --- a/packages/kumo-snowflake/tests/test_backend.py +++ b/packages/kumo-snowflake/tests/test_backend.py @@ -2,8 +2,8 @@ # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -from contextlib import nullcontext from types import SimpleNamespace +from unittest.mock import Mock import pytest from kumo_core.sources.errors import PermanentSourceError @@ -20,11 +20,10 @@ def test_zero_row_read_is_an_empty_source(rows, tmp_path, monkeypatch): mode_used=ReadMode.STAGED, num_rows=rows) monkeypatch.setattr("kumo_core.sources.prepare.read_table", lambda *args, **kwargs: staged) - backend = SnowflakeSourceBackend() + backend = SnowflakeSourceBackend(connection=Mock()) for name in ("_declared", "_reader"): monkeypatch.setattr(backend, name, lambda *args, **kwargs: {}) - monkeypatch.setattr(backend, "_session", - lambda connector: nullcontext(None)) + monkeypatch.setattr(backend._connection, "get", lambda connector: None) connector = SimpleNamespace(id="c") def prepare(): diff --git a/packages/kumo-snowflake/tests/test_connection.py b/packages/kumo-snowflake/tests/test_connection.py index 2e79b5ca2..c23480780 100644 --- a/packages/kumo-snowflake/tests/test_connection.py +++ b/packages/kumo-snowflake/tests/test_connection.py @@ -86,8 +86,8 @@ def test_source_and_sink_share_owner_without_serializing_live_sessions( owner = session.SnowflakeConnection(principals[0]) source = SnowflakeSourceBackend(connection=owner) sink = SnowflakeSinkBackend(connection=owner) - with source._session(connector) as live, sink._session(connector) as same: - assert same is live + live = source._connection.get(connector) + assert sink._connection.get(connector) is live restored_source, restored_sink = pickle.loads(pickle.dumps((source, sink))) restored = restored_source._connection @@ -96,8 +96,7 @@ def test_source_and_sink_share_owner_without_serializing_live_sessions( assert restored is not owner assert restored.identity == owner.identity assert connect.call_count == 1 - with restored_source._session(connector) as worker_session: - assert worker_session is not live + assert restored_source._connection.get(connector) is not live assert connect.call_count == 2 live.close.assert_not_called() @@ -153,3 +152,26 @@ def test_distinct_targets_never_reuse_session_context( assert owner.get(connector) is not owner.get(other) assert connect.call_count == 2 + + +def test_backends_keep_account_qualified_table_locations( + principals: tuple[Principal, Principal], + connector: SourceConnector, +) -> None: + """Removing the base class preserves table quoting and diagnostic locations.""" + owner = session.SnowflakeConnection(principals[0]) + source = SnowflakeSourceBackend(owner) + sink = SnowflakeSinkBackend(owner) + expected = 'account-1/"DB"."SCHEMA"."table""name"' + + assert source.table_location(connector, 'table"name') == expected + assert sink.table_location(connector, 'table"name') == expected + + +def test_table_locations_without_credentials_remain_available( + connector: SourceConnector, +) -> None: + """Diagnostics do not need to authenticate or open a session.""" + source = SnowflakeSourceBackend(session.SnowflakeConnection(None)) + + assert source.table_location(connector, "events") == '"DB"."SCHEMA"."events"' diff --git a/packages/kumo-snowflake/tests/test_registry.py b/packages/kumo-snowflake/tests/test_registry.py index 108b15a01..cd78b562c 100644 --- a/packages/kumo-snowflake/tests/test_registry.py +++ b/packages/kumo-snowflake/tests/test_registry.py @@ -5,10 +5,10 @@ import json import re -from contextlib import contextmanager, nullcontext +from contextlib import contextmanager from pathlib import Path from types import SimpleNamespace -from unittest.mock import ANY +from unittest.mock import ANY, Mock import pandas as pd import pytest @@ -266,7 +266,7 @@ def registry(_): sink = SnowflakeModelRegistryMixin() monkeypatch.setattr(sink, '_registry', registry) - monkeypatch.setattr(sink, '_session', lambda _: nullcontext(files), + monkeypatch.setattr(sink, '_connection', SimpleNamespace(get=lambda _: files), raising=False) return sink @@ -283,7 +283,7 @@ def test_set_alias_moves_it_and_refuses_what_snowflake_cannot(monkeypatch): from kumo_snowflake.sink import SnowflakeSinkBackend from kumoapi.plugin import ModelAliasingSink - assert isinstance(SnowflakeSinkBackend(), ModelAliasingSink) + assert isinstance(SnowflakeSinkBackend(connection=Mock()), ModelAliasingSink) model = _Model({'V1': ['FIRST'], 'V2': ['LAST', 'DEFAULT'], 'V3': []}) sink = _sink(monkeypatch, get_model=lambda _: model) diff --git a/packages/kumo-snowflake/tests/test_sink.py b/packages/kumo-snowflake/tests/test_sink.py index 94276f099..f64b06916 100644 --- a/packages/kumo-snowflake/tests/test_sink.py +++ b/packages/kumo-snowflake/tests/test_sink.py @@ -5,6 +5,7 @@ from contextlib import contextmanager from types import SimpleNamespace +from unittest.mock import Mock from kumo_core.sources.principals import Principal from kumo_snowflake import session, sink @@ -76,15 +77,14 @@ class _ExpiredTokenError(Exception): def test_an_overwrite_retries_once_with_a_fresh_session_after_token_expiry( monkeypatch): - backend = SnowflakeSinkBackend() + backend = SnowflakeSinkBackend(connection=Mock(identity=object())) cached_sessions = [] retry_sessions = [] exports = [] - @contextmanager def open_session(_connector): cached_sessions.append(1) - yield _Session() + return _Session() @contextmanager def open_retry_session(_principal, _connector): @@ -106,10 +106,9 @@ def upload(*_args, **_kwargs) -> None: "PREDICTIONS", "/tmp/predictions.parquet", replace=True, upload_local=upload) - monkeypatch.setattr(backend, "_session", open_session) - monkeypatch.setattr(backend, "_principal", lambda _connector: object()) + monkeypatch.setattr(backend._connection, "get", open_session) monkeypatch.setattr(sink, "_owned_session", open_retry_session) - monkeypatch.setattr(backend, "_qualified", lambda *_: '"PREDICTIONS"') + monkeypatch.setattr(sink, "_qualified", lambda *_: '"PREDICTIONS"') monkeypatch.setattr(sink, "_require_snowpark", lambda _session: None) monkeypatch.setattr( "kumo_core.artifact_staging.selected_local_parquet_files", @@ -126,13 +125,12 @@ def upload(*_args, **_kwargs) -> None: def test_an_append_does_not_retry_after_token_expiry(monkeypatch): - backend = SnowflakeSinkBackend() + backend = SnowflakeSinkBackend(connection=Mock(identity=object())) - @contextmanager def open_session(_connector): - yield _Session() + return _Session() - monkeypatch.setattr(backend, "_session", open_session) + monkeypatch.setattr(backend._connection, "get", open_session) monkeypatch.setattr(sink, "_require_snowpark", lambda _session: None) monkeypatch.setattr( "kumo_core.artifact_staging.selected_local_parquet_files", @@ -155,15 +153,14 @@ def test_an_append_loads_files_stamped_with_extra_columns(monkeypatch, import pandas as pd import pyarrow.parquet as pq - backend = SnowflakeSinkBackend() + backend = SnowflakeSinkBackend(connection=Mock(identity=object())) artifact = tmp_path / "part-0.parquet" pd.DataFrame({"ENTITY": ["a"]}).to_parquet(artifact) - @contextmanager def open_session(_connector): - yield _Session() + return _Session() - monkeypatch.setattr(backend, "_session", open_session) + monkeypatch.setattr(backend._connection, "get", open_session) monkeypatch.setattr(sink, "_require_snowpark", lambda _session: None) loads = [] @@ -175,7 +172,7 @@ def load(target, table_name, path, replace, *, artifact_files, pq.read_table(staged).to_pydict())) monkeypatch.setattr("kumo_snowflake.write.write_artifacts_to_table", load) - monkeypatch.setattr(backend, "_qualified", lambda _c, name: name) + monkeypatch.setattr(sink, "_qualified", lambda _c, name: name) backend.write_files(SimpleNamespace(), "PREDICTIONS", [str(artifact)], WriteMode.APPEND, extra_columns={"PREDICTION_ID": "p1"}) diff --git a/packages/kumo-snowflake/tests/test_stage_fs.py b/packages/kumo-snowflake/tests/test_stage_fs.py index 408eb319e..b34bff3f2 100644 --- a/packages/kumo-snowflake/tests/test_stage_fs.py +++ b/packages/kumo-snowflake/tests/test_stage_fs.py @@ -5,8 +5,8 @@ import gc import os -from contextlib import contextmanager from types import SimpleNamespace +from unittest.mock import Mock import pytest from fakes import FakeStage @@ -34,13 +34,9 @@ def stage(monkeypatch, tmp_path): @pytest.fixture def sink(stage, monkeypatch): session = stage.session() - sink = SnowflakeSinkBackend() + sink = SnowflakeSinkBackend(connection=Mock()) - @contextmanager - def connected(connector): - yield session - - monkeypatch.setattr(sink, '_session', connected) + monkeypatch.setattr(sink._connection, 'get', lambda connector: session) return sink @@ -83,7 +79,7 @@ def test_the_sink_resolves_a_stage_path(filesystem, stage): ('@~/runs', False), ('@%USERS/runs', False)]) def test_only_named_stage_paths_are_file_locations(path, held): - sink = SnowflakeSinkBackend() + sink = SnowflakeSinkBackend(connection=Mock()) assert isinstance(sink, FileStoreSink) assert sink.holds_files(object(), path) is held From b10c64c7233f1261f875011bf80bc0310ad52b8d Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 20:32:54 +0000 Subject: [PATCH 08/10] Close BigQuery Storage API clients through their transports --- .../src/kumo_bigquery/session.py | 10 +-- .../kumo-bigquery/tests/test_connection.py | 80 ++++++++++++++----- 2 files changed, 64 insertions(+), 26 deletions(-) diff --git a/packages/kumo-bigquery/src/kumo_bigquery/session.py b/packages/kumo-bigquery/src/kumo_bigquery/session.py index 42a9fa76d..78130fb15 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/session.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/session.py @@ -226,16 +226,16 @@ def close(self) -> None: Exception: A client fails to close, after all closes run. """ with self._lock, ExitStack() as cleanup: - clients = [*self._query.values(), *self._storage.values()] + resources = [*self._query.values(), *self._storage.values()] if self._read is not None: - clients.append(self._read) + resources.append(self._read.transport) if self._write is not None: - clients.append(self._write) + resources.append(self._write.transport) self._query.clear() self._storage.clear() self._read = self._write = None - for client in clients: - cleanup.callback(client.close) + for resource in resources: + cleanup.callback(resource.close) def _rows(client: Any, sql: str, job_config: Any = None) -> List[Any]: diff --git a/packages/kumo-bigquery/tests/test_connection.py b/packages/kumo-bigquery/tests/test_connection.py index 2f82bad87..3dc4ceefb 100644 --- a/packages/kumo-bigquery/tests/test_connection.py +++ b/packages/kumo-bigquery/tests/test_connection.py @@ -9,6 +9,12 @@ from unittest.mock import Mock import pytest +from google.cloud.bigquery_storage_v1.services.big_query_read.transports.base import ( + BigQueryReadTransport, +) +from google.cloud.bigquery_storage_v1.services.big_query_write.transports.base import ( + BigQueryWriteTransport, +) from kumo_bigquery import session from kumo_bigquery.backend import BigQuerySourceBackend from kumo_bigquery.sink import BigQuerySinkBackend @@ -45,6 +51,19 @@ def principal(index: int) -> Principal: return principal(1), principal(2) +@pytest.fixture +def read_builder(monkeypatch: pytest.MonkeyPatch) -> Mock: + """Build strict Storage Read client mocks with transport-owned cleanup.""" + build = Mock( + side_effect=lambda _: Mock( + spec_set=session.bigquery_storage.BigQueryReadClient, + transport=Mock(spec_set=BigQueryReadTransport), + ) + ) + monkeypatch.setattr(session, "_read_client", build) + return build + + @pytest.mark.parametrize("kind", ["query", "read", "write", "storage"]) def test_clients_are_reused_only_within_their_owner( monkeypatch: pytest.MonkeyPatch, @@ -85,11 +104,10 @@ def test_clients_are_reused_only_within_their_owner( def test_source_and_sink_share_owner_without_serializing_live_clients( monkeypatch: pytest.MonkeyPatch, principals: tuple[Principal, Principal], + read_builder: Mock, ) -> None: """Worker deserialization preserves sharing but opens independent clients.""" monkeypatch.setattr(session, "_credentials_for", lambda _: Mock(token="token")) - build = Mock(side_effect=lambda _: Mock()) - monkeypatch.setattr(session, "_read_client", build) owner = session.BigQueryConnection(principals[0]) source = BigQuerySourceBackend(connection=owner) sink = BigQuerySinkBackend(connection=owner) @@ -102,20 +120,19 @@ def test_source_and_sink_share_owner_without_serializing_live_clients( assert restored is restored_sink._connection assert restored is not owner assert restored.identity == owner.identity - assert build.call_count == 1 + assert read_builder.call_count == 1 assert restored.read_client() is not live - assert build.call_count == 2 - live.close.assert_not_called() + assert read_builder.call_count == 2 + live.transport.close.assert_not_called() def test_concurrent_calls_open_one_client_and_close_allows_reopening( monkeypatch: pytest.MonkeyPatch, principals: tuple[Principal, Principal], + read_builder: Mock, ) -> None: """Concurrent users share one lazy client; close retires it exactly once.""" monkeypatch.setattr(session, "_credentials_for", lambda _: Mock(token="token")) - build = Mock(side_effect=lambda _: Mock()) - monkeypatch.setattr(session, "_read_client", build) owner = session.BigQueryConnection(principals[0]) with ThreadPoolExecutor(max_workers=4) as pool: @@ -125,33 +142,54 @@ def test_concurrent_calls_open_one_client_and_close_allows_reopening( reopened = owner.read_client() assert all(client is clients[0] for client in clients) - clients[0].close.assert_called_once_with() + clients[0].transport.close.assert_called_once_with() assert reopened is not clients[0] - assert build.call_count == 2 + assert read_builder.call_count == 2 -def test_close_attempts_every_client_after_a_failure( +@pytest.mark.parametrize("fail_cleanup", [False, True]) +def test_close_uses_sdk_cleanup_apis_and_attempts_every_client( monkeypatch: pytest.MonkeyPatch, principals: tuple[Principal, Principal], + read_builder: Mock, + fail_cleanup: bool, ) -> None: - """Cleanup errors cannot leave other owned clients unclosed or cached.""" + """Use each SDK's cleanup API, including when a transport fails to close.""" monkeypatch.setattr(session, "_credentials_for", lambda _: Mock(token="token")) - read = Mock() - read.close.side_effect = RuntimeError("close failed") - write = Mock() - monkeypatch.setattr(session, "_read_client", lambda _: read) + query = Mock(spec_set=session.bigquery.Client) + storage = Mock(spec_set=session.storage.Client) + write = Mock( + spec_set=session.bigquery_storage.BigQueryWriteClient, + transport=Mock(spec_set=BigQueryWriteTransport), + ) + monkeypatch.setattr(session, "_query_client", lambda *_, **__: query) + monkeypatch.setattr(session, "_storage_client", lambda *_, **__: storage) monkeypatch.setattr(session, "_write_client", lambda _: write) owner = session.BigQueryConnection(principals[0]) - owner.read_client() + connector = SimpleNamespace( + config=BigQueryConnectorResourceConfig( + project_id="sample-project", dataset_id="dataset", location="US" + ) + ) + owner.query_client(connector) + owner.storage_client(project="sample-project") + read = owner.read_client() owner.write_client() + if fail_cleanup: + read.transport.close.side_effect = RuntimeError("close failed") - with pytest.raises(RuntimeError, match="close failed"): + if fail_cleanup: + with pytest.raises(RuntimeError, match="close failed"): + owner.close() + else: owner.close() - - read.close.assert_called_once_with() - write.close.assert_called_once_with() owner.close() - assert read.close.call_count == 1 + + query.close.assert_called_once_with() + storage.close.assert_called_once_with() + read.transport.close.assert_called_once_with() + write.transport.close.assert_called_once_with() + assert read_builder.call_count == 1 def test_backend_table_locations_use_the_data_project( From 39b393e4c6d700f8e8478a9742f31a64493c820d Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 21:45:50 +0000 Subject: [PATCH 09/10] Finalize connector-owned resources and normalize ambient identities --- packages/kumo-adls/README.md | 11 +- packages/kumo-adls/docs/implementation.md | 18 ++- packages/kumo-adls/src/kumo_adls/backend.py | 4 +- .../kumo-adls/src/kumo_adls/native_output.py | 25 ++-- packages/kumo-adls/src/kumo_adls/session.py | 65 ++++++++--- packages/kumo-adls/src/kumo_adls/sink.py | 4 +- .../tests/live/test_live_filesystem.py | 6 +- packages/kumo-adls/tests/test_backend.py | 75 +++++++----- packages/kumo-adls/tests/test_coordinates.py | 28 +++-- packages/kumo-adls/tests/test_filesystem.py | 3 +- packages/kumo-adls/tests/test_native_auth.py | 18 ++- .../kumo-adls/tests/test_native_output.py | 22 ++-- packages/kumo-adls/tests/test_range_cache.py | 3 +- packages/kumo-adls/tests/test_session.py | 55 +++++++-- .../kumo-adls/tests/test_sink_preflight.py | 21 ++-- .../kumo-adls/tests/test_source_access.py | 11 +- packages/kumo-adls/tests/test_transfer.py | 21 +++- packages/kumo-api/kumoapi/data_source.py | 17 ++- .../test/test_adls_ambient_identity.py | 63 ++++++++++ .../src/kumo_bigquery/session.py | 17 ++- .../kumo-bigquery/tests/test_connection.py | 43 +++++++ packages/kumo-core/README.md | 36 ++++-- .../sources/object_store_sessions.py | 12 +- .../src/kumo_core/sources/principals.py | 11 +- .../kumo-core/tests/sources/identities.py | 21 ++++ .../tests/sources/unit/test_principals.py | 48 +++----- .../kumo-engine/kumo/engine/connector/adls.py | 3 +- .../kumo-engine/kumo/engine/connector/base.py | 5 +- .../kumo/engine/connector/bigquery.py | 7 +- .../kumo-engine/kumo/engine/connector/gcs.py | 3 +- .../kumo/engine/connector/identity.py | 34 ++++-- .../kumo-engine/kumo/engine/connector/s3.py | 3 +- .../kumo/engine/connector/snowflake.py | 7 +- .../test/test_ambient_identities.py | 86 ++++++++++++++ .../test/test_connector_connections.py | 2 +- packages/kumo-engine/test/test_identity.py | 68 +---------- packages/kumo-gcs/src/kumo_gcs/backend.py | 31 +++-- packages/kumo-s3/src/kumo_s3/backend.py | 35 +++--- packages/kumo-s3/tests/test_sink_delete.py | 3 +- .../src/kumo_snowflake/session.py | 26 ++++- .../kumo-snowflake/src/kumo_snowflake/sink.py | 2 +- .../src/kumo_snowflake/stage_fs.py | 30 ++++- .../kumo-snowflake/tests/test_connection.py | 110 ++++++++++++++++++ .../benchmarks/object_store/compare_live.py | 5 +- 44 files changed, 803 insertions(+), 315 deletions(-) create mode 100644 packages/kumo-api/test/test_adls_ambient_identity.py create mode 100644 packages/kumo-core/tests/sources/identities.py create mode 100644 packages/kumo-engine/test/test_ambient_identities.py diff --git a/packages/kumo-adls/README.md b/packages/kumo-adls/README.md index ed8ccac10..e07317f54 100644 --- a/packages/kumo-adls/README.md +++ b/packages/kumo-adls/README.md @@ -73,12 +73,13 @@ for validation, ownership, and Studio adoption follow-ups. ## Authentication and resources -Without an identity, requests use Azure's ambient credential chain. An explicit -`ADLSIdentity(tenant_id=..., client_id=..., cloud=...)` uses workload federation -with `AZURE_FEDERATED_TOKEN_FILE`. Secrets, storage keys, and SAS tokens are not -connector arguments. The identity cloud must match the public, US Government, +`ADLSIdentity()` selects Azure's ambient credential chain; connectors use this +identity when none is supplied. Its Azure cloud is inferred from the storage +endpoint unless explicitly constrained. Supplying tenant and client IDs to +`ADLSIdentity` selects workload federation with `AZURE_FEDERATED_TOKEN_FILE`. +Secrets, storage keys, and SAS tokens are not connector arguments. The identity cloud must match the public, US Government, or China URI endpoint. Native writes require the process's `AZURE_TENANT_ID` -and `AZURE_CLIENT_ID` to match an explicit identity and +and `AZURE_CLIENT_ID` to match the workload identity and `AZURE_FEDERATED_TOKEN_FILE` to name its projected token. Other per-connector identities remain read-only. Native writes also require `AZURE_AUTHORITY_HOST` to match the cloud (public is the default). Unsupported configurations fail diff --git a/packages/kumo-adls/docs/implementation.md b/packages/kumo-adls/docs/implementation.md index 99ca63539..ceb903372 100644 --- a/packages/kumo-adls/docs/implementation.md +++ b/packages/kumo-adls/docs/implementation.md @@ -104,8 +104,8 @@ A native filesystem is reused within one sink access, with thread-safe first construction; it is not cached across accesses or identities. The provider accepts pyarrow 16 through 24; CI runs its suite at both ends of that range. -Without an explicit identity, writes use Arrow's C++ ambient credential chain; -reads use Python Azure Identity. These chains can select different ambient +Explicit ambient principals use Arrow's C++ ambient credential chain for writes +and Python Azure Identity for reads. These chains can select different ambient credentials. Explicit workload writes require process `AZURE_TENANT_ID` and `AZURE_CLIENT_ID` to equal the selected identity, plus `AZURE_FEDERATED_TOKEN_FILE`. They select only Arrow's workload credential, @@ -189,3 +189,17 @@ Follow-ups: credential-bound functions and validate them individually. Existing SDK writer helpers are not the Studio default. SAS generation, multipart upload, and atomic promotion are separate work; native engine output is unchanged. + +### Explicit ambient configuration + +Engine connectors normalize an omitted identity to `ADLSIdentity()`. Its +`ADLSAmbientIdentityConfig` is local to provider connections and leaves the hosted +`ADLSIdentityConfig` workload contract unchanged. Ambient SDK credentials derive +the Azure authority from the selected storage endpoint. An optional cloud +constraint rejects mismatching endpoints. Standalone identity probing uses the +constraint or public Azure when no target endpoint is available. + +Provider backends and SDK-session helpers require an explicit `Principal` for +both ambient and workload authentication. Workload native writes continue to +require matching process identity settings; ambient native writes use Arrow's +ambient chain and retain the endpoint/authority checks. diff --git a/packages/kumo-adls/src/kumo_adls/backend.py b/packages/kumo-adls/src/kumo_adls/backend.py index f765b3529..fd766420f 100644 --- a/packages/kumo-adls/src/kumo_adls/backend.py +++ b/packages/kumo-adls/src/kumo_adls/backend.py @@ -95,7 +95,7 @@ def _source_access(self, connector, bucket, region): del region _, host = bucket.split('@', 1) account, suffix = host.split('.', 1) - client = session_for(self._principal(connector), account, suffix) + client = session_for(self._identity, account, suffix) return source_access(client, account, suffix) def _over(self, connector, bucket, root, region): @@ -140,7 +140,7 @@ class ADLSSourceBackend(ADLSSessions, ObjectStoreSourceBackend): uri_source = ADLSURISource source_table = ADLSSourceTable - def __init__(self, identity: Optional[Principal] = None, + def __init__(self, identity: Principal, storage_namespace: Optional[str] = None, mode: Optional[ReadMode] = None): super().__init__(identity, storage_namespace) diff --git a/packages/kumo-adls/src/kumo_adls/native_output.py b/packages/kumo-adls/src/kumo_adls/native_output.py index 1b09f0df7..0193df066 100644 --- a/packages/kumo-adls/src/kumo_adls/native_output.py +++ b/packages/kumo-adls/src/kumo_adls/native_output.py @@ -6,18 +6,21 @@ import threading from urllib.parse import urlencode, urlsplit +from kumo_core.sources.principals import Principal from kumoapi.adls import ( normalize_adls_endpoint_suffix, normalize_adls_filesystem, normalize_adls_storage_account, ) -from kumoapi.data_source import ADLSIdentityConfig +from kumoapi.data_source import ADLSAmbientIdentityConfig, ADLSIdentityConfig from pyarrow.fs import AzureFileSystem, FileSystem, FSSpecHandler from .clouds import CLOUDS -def validate_output_configuration(principal, account, suffix, container): +def validate_output_configuration( + principal: Principal, account: str, suffix: str, + container: str) -> tuple[str, str, str]: """Validate native output locally, without constructing storage clients.""" account = normalize_adls_storage_account(account) suffix = normalize_adls_endpoint_suffix(suffix) @@ -25,13 +28,12 @@ def validate_output_configuration(principal, account, suffix, container): cloud, (_, _, authority) = next((cloud, values) for cloud, values in CLOUDS.items() if values[0] == suffix) - if principal is not None: - config = principal.config - if not isinstance(config, ADLSIdentityConfig): - raise ValueError('The selected identity is not an ADLS identity') - if config.cloud != cloud: - raise ValueError( - 'ADLS endpoint does not match the selected identity cloud') + config = principal.config + if not isinstance(config, (ADLSIdentityConfig, ADLSAmbientIdentityConfig)): + raise ValueError('The selected identity is not an ADLS identity') + if config.cloud is not None and config.cloud != cloud: + raise ValueError('ADLS endpoint does not match the selected identity cloud') + if isinstance(config, ADLSIdentityConfig): if (os.environ.get('AZURE_TENANT_ID') != config.tenant_id or os.environ.get('AZURE_CLIENT_ID') != config.client_id or not os.environ.get('AZURE_FEDERATED_TOKEN_FILE', '').strip()): @@ -54,14 +56,15 @@ def validate_output_configuration(principal, account, suffix, container): return account, suffix, container -def filesystem_for(principal, account, suffix, container): +def filesystem_for(principal: Principal, account: str, suffix: str, + container: str) -> FileSystem: """Bind native output without changing or substituting an identity.""" account, suffix, container = validate_output_configuration( principal, account, suffix, container) options = dict( blob_storage_authority='.' + suffix.replace('dfs.', 'blob.', 1), dfs_storage_authority='.' + suffix) - if principal is None: + if isinstance(principal.config, ADLSAmbientIdentityConfig): return AzureFileSystem(account_name=account, **options) # Arrow's workload credential reads environment configuration at creation; diff --git a/packages/kumo-adls/src/kumo_adls/session.py b/packages/kumo-adls/src/kumo_adls/session.py index 98c56c72d..456193544 100644 --- a/packages/kumo-adls/src/kumo_adls/session.py +++ b/packages/kumo-adls/src/kumo_adls/session.py @@ -4,17 +4,39 @@ import atexit import threading +from typing import TypeAlias from azure.identity import DefaultAzureCredential, WorkloadIdentityCredential +from azure.storage.filedatalake import DataLakeServiceClient from kumo_core.sources.principals import Principal -from kumoapi.data_source import ADLSIdentityConfig +from kumoapi.data_source import ( + ADLSAmbientIdentityConfig, + ADLSIdentityConfig, + AzureCloud, +) from .client import create_client from .clouds import CLOUDS from .errors import translated +_AzureCredential: TypeAlias = DefaultAzureCredential | WorkloadIdentityCredential -def credential_for(principal: Principal | None, endpoint_suffix: str): + +def credential_for( + principal: Principal, endpoint_suffix: str, +) -> tuple[_AzureCredential, str]: + """Resolve credentials for the endpoint's Azure cloud. + + Args: + principal: Explicit ambient or workload identity configuration. + endpoint_suffix: Azure Data Lake endpoint suffix identifying the cloud. + + Returns: + An owned Azure credential and the storage audience. + + Raises: + ValueError: The endpoint is unsupported or conflicts with the identity. + """ cloud = next( (cloud for cloud, values in CLOUDS.items() if values[0] == endpoint_suffix), @@ -22,29 +44,44 @@ def credential_for(principal: Principal | None, endpoint_suffix: str): if cloud is None: raise ValueError('Unsupported ADLS endpoint suffix') _, audience, authority = CLOUDS[cloud] - if principal is None: - return DefaultAzureCredential(authority=authority), audience config = principal.config - if not isinstance(config, ADLSIdentityConfig): + if not isinstance(config, (ADLSIdentityConfig, ADLSAmbientIdentityConfig)): raise ValueError('The selected identity is not an ADLS identity') - if config.cloud != cloud: + if config.cloud is not None and config.cloud != cloud: raise ValueError( 'ADLS endpoint does not match the selected identity cloud') - # Explicit identities must never fall back to another ambient principal. + if isinstance(config, ADLSAmbientIdentityConfig): + return DefaultAzureCredential(authority=authority), audience + # Workload identities must never fall back to another ambient principal. return WorkloadIdentityCredential(tenant_id=config.tenant_id, client_id=config.client_id, authority=authority), audience _LOCK = threading.RLock() -_SESSIONS = {} +_SESSIONS: dict[tuple[str, str, str, str], + tuple[DataLakeServiceClient, _AzureCredential]] = {} + + +def session_for( + principal: Principal, account: str, suffix: str +) -> DataLakeServiceClient: + """Return a cached client bound to an explicit principal and storage account. + + Args: + principal: Ambient or workload authentication configuration. + account: Azure storage account name. + suffix: Data Lake endpoint suffix selecting the Azure cloud. + Returns: + The session cache's storage client. -def session_for(principal: Principal | None, account: str, suffix: str): + Raises: + ValueError: The identity and endpoint configuration are incompatible. + """ # Config participates in the key so a rotated identity cannot reuse a # client signed as its predecessor. Tokens refresh inside Azure Identity. - key = (principal.name if principal else None, - repr(principal.config) if principal else None, account, suffix) + key = (principal.name, repr(principal.config), account, suffix) with _LOCK: if key not in _SESSIONS: with translated(): @@ -82,10 +119,10 @@ def close(identity_name: str | None = None) -> None: def probe(principal: Principal) -> None: """Validate token acquisition; this does not attest storage permissions.""" config = principal.config - if not isinstance(config, ADLSIdentityConfig): + if not isinstance(config, (ADLSIdentityConfig, ADLSAmbientIdentityConfig)): raise ValueError('The selected identity is not an ADLS identity') + cloud = AzureCloud.PUBLIC if config.cloud is None else config.cloud with translated(): - credential, audience = credential_for(principal, - CLOUDS[config.cloud][0]) + credential, audience = credential_for(principal, CLOUDS[cloud][0]) with credential: credential.get_token(f'{audience}/.default') diff --git a/packages/kumo-adls/src/kumo_adls/sink.py b/packages/kumo-adls/src/kumo_adls/sink.py index 0d586cbae..be7f804da 100644 --- a/packages/kumo-adls/src/kumo_adls/sink.py +++ b/packages/kumo-adls/src/kumo_adls/sink.py @@ -35,7 +35,7 @@ def preflight_write_files(self, connector, table_name, bucket, path, region = self._resolved(connector, table_name) container, host = bucket.split('@', 1) account, suffix = host.split('.', 1) - validate_output_configuration(self._principal(connector), account, + validate_output_configuration(self._identity, account, suffix, container) if write_mode is None and table_name.endswith('/'): self._require_empty_destination( @@ -53,7 +53,7 @@ def _filesystem(self, connector, bucket, region): account, suffix = host.split('.', 1) # Model reads use this filesystem too; bind output credentials # only when a native output stream is actually requested. - native = partial(filesystem_for, self._principal(connector), + native = partial(filesystem_for, self._identity, account, suffix, container) return PyFileSystem( NativeOutputHandler(filesystem.handler.fs, diff --git a/packages/kumo-adls/tests/live/test_live_filesystem.py b/packages/kumo-adls/tests/live/test_live_filesystem.py index 493c77e9d..f4751cdb7 100644 --- a/packages/kumo-adls/tests/live/test_live_filesystem.py +++ b/packages/kumo-adls/tests/live/test_live_filesystem.py @@ -14,6 +14,7 @@ from kumo_adls.session import session_for from kumoapi.adls import normalize_adls_root_uri from pyarrow.fs import FileType, FSSpecHandler, PyFileSystem +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL ROOT = os.environ.get('KUMO_ADLS_LIVE_ROOT') if not ROOT: @@ -27,8 +28,9 @@ def live_directory(): parsed = urlsplit(normalize_adls_root_uri(ROOT)) _, host = parsed.netloc.split('@', 1) account, suffix = host.split('.', 1) - filesystem = ADLSFileSystem(session_for(None, account, suffix), account, - suffix) + filesystem = ADLSFileSystem( + session_for(AMBIENT_PRINCIPAL, account, suffix), account, suffix + ) path = parsed.netloc + unquote(parsed.path).rstrip('/') return filesystem, path diff --git a/packages/kumo-adls/tests/test_backend.py b/packages/kumo-adls/tests/test_backend.py index dcfcfe7da..df56fb530 100644 --- a/packages/kumo-adls/tests/test_backend.py +++ b/packages/kumo-adls/tests/test_backend.py @@ -11,12 +11,13 @@ from kumo_core.sources.errors import UnsupportedReadModeError from kumo_core.sources.types import ReadMode from kumoapi.source_table import ADLSRelativeSource, ADLSURISource +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL URI = 'abfss://curated@companylake.dfs.core.windows.net/orders/' def test_discovery_schema_sample_and_ingestion(service, connector, tmp_path): - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) target = connector() assert source.list_tables(target).table_names == ['events'] config = source.get_table_config(target, 'events').source_table @@ -39,7 +40,7 @@ def test_discovery_schema_sample_and_ingestion(service, connector, tmp_path): def test_rootless_exact_source_and_source_only_contract(service, connector): - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) target = connector(any_uri=True) uri = URI + 'events.parquet' config = source.get_table_config(target, uri).source_table @@ -48,12 +49,14 @@ def test_rootless_exact_source_and_source_only_contract(service, connector): with pytest.raises(NotImplementedError, match='cannot list'): source.list_tables(target) with pytest.raises(NotImplementedError, match='source-only'): - ADLSSinkBackend().write_table(target, uri, pd.DataFrame({'id': [1]})) + ADLSSinkBackend(AMBIENT_PRINCIPAL).write_table( + target, uri, pd.DataFrame({"id": [1]}) + ) def test_versions_separate_accounts_clouds_and_same_second_rewrites( service, connector): - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) first = source.get_data_version(connector(), 'events') assert first != source.get_data_version(connector(account='otherlake'), 'events') @@ -71,10 +74,11 @@ def test_versions_separate_accounts_clouds_and_same_second_rewrites( ]) def test_read_and_write_fences_before_storage_access(service, connector, path): with pytest.raises(ValueError): - ADLSSourceBackend().get_columns(connector(), path) + ADLSSourceBackend(AMBIENT_PRINCIPAL).get_columns(connector(), path) with pytest.raises(ValueError): - ADLSSinkBackend().write_table(connector(), path, - pd.DataFrame({'id': [1]})) + ADLSSinkBackend(AMBIENT_PRINCIPAL).write_table( + connector(), path, pd.DataFrame({"id": [1]}) + ) assert not service.created @@ -82,24 +86,28 @@ def test_read_and_write_fences_before_storage_access(service, connector, path): ['scores.parquet', 'scores.csv', 'scores/']) def test_output_roundtrip(service, connector, filename): target = connector() - uri = ADLSSinkBackend().write_table(target, filename, - pd.DataFrame({'id': [3, 4]})) + uri = ADLSSinkBackend(AMBIENT_PRINCIPAL).write_table( + target, filename, pd.DataFrame({"id": [3, 4]}) + ) assert uri.startswith(URI + filename.rstrip('/')) - sample = ADLSSourceBackend().get_sample(target, filename, 2).sample_rows + sample = ( + ADLSSourceBackend(AMBIENT_PRINCIPAL).get_sample(target, filename, 2).sample_rows + ) assert '3' in sample and '4' in sample def test_encoded_uri_paths_and_decoded_relative_paths(service, connector): service.files['curated/orders/space name.parquet'] = service.files[ 'curated/orders/events.parquet'] - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) assert source.get_download_urls( connector(), 'space name.parquet') == [URI + 'space%20name.parquet'] assert source.get_columns(connector(), URI + 'space%20name.parquet').cols assert source.get_columns(connector(any_uri=True), URI + 'space%20name.parquet').cols - uri = ADLSSinkBackend().write_table(connector(), 'new name.parquet', - pd.DataFrame({'id': [1]})) + uri = ADLSSinkBackend(AMBIENT_PRINCIPAL).write_table( + connector(), "new name.parquet", pd.DataFrame({"id": [1]}) + ) assert uri == URI + 'new%20name.parquet' @@ -107,7 +115,7 @@ def test_model_bundle_roundtrip(service, connector, tmp_path): bundle = tmp_path / 'bundle' bundle.mkdir() (bundle / 'model.bin').write_bytes(b'model-bytes') - sink = ADLSSinkBackend() + sink = ADLSSinkBackend(AMBIENT_PRINCIPAL) published = sink.publish_model(connector(), str(bundle), path='model bundle') assert published.uri == URI + 'model%20bundle' @@ -119,9 +127,11 @@ def test_model_bundle_roundtrip(service, connector, tmp_path): def test_rejects_sql_and_staged_reads(service, connector, tmp_path): with pytest.raises(UnsupportedReadModeError): - ADLSSourceBackend().get_columns(connector(), 'events', sql='SELECT 1') + ADLSSourceBackend(AMBIENT_PRINCIPAL).get_columns( + connector(), "events", sql="SELECT 1" + ) with pytest.raises(UnsupportedReadModeError): - ADLSSourceBackend(mode=ReadMode.STAGED).prepare_ingest( + ADLSSourceBackend(AMBIENT_PRINCIPAL, mode=ReadMode.STAGED).prepare_ingest( connector(), 'events', str(tmp_path / 'ingest')) @@ -131,7 +141,7 @@ def test_requested_version_is_stamped_without_refresh(service, connector, from kumo_adls.backend import ADLSSourceReader - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) target = connector() version = source.get_data_version(target, 'events') original = service.files['curated/orders/events.parquet'] @@ -171,8 +181,9 @@ def fetch_then_mutate(self, path, destination): monkeypatch.setattr(ADLSFileSystem, 'fetch', fetch_then_mutate) with pytest.raises(TransientSourceError, match='changed while'): - ADLSSourceBackend().prepare_ingest(connector(), 'events', - str(tmp_path / 'ingest')) + ADLSSourceBackend(AMBIENT_PRINCIPAL).prepare_ingest( + connector(), "events", str(tmp_path / "ingest") + ) assert not list((tmp_path / 'ingest').rglob('*.parquet')) @@ -181,14 +192,18 @@ def test_stream_file_export_and_retry_marker(service, connector, tmp_path): source = tmp_path / 'predictions.parquet' pq.write_table(pa.table({'score': [0.5, 0.75]}), source) - sink = ADLSSinkBackend() + sink = ADLSSinkBackend(AMBIENT_PRINCIPAL) target = connector() first = sink.write_files(target, 'predictions/', [str(source)], export_id='test-run') second = sink.write_files(target, 'predictions/', [str(source)], export_id='test-run') assert first == second - assert ADLSSourceBackend().get_sample(target, 'predictions', 2).sample_rows + assert ( + ADLSSourceBackend(AMBIENT_PRINCIPAL) + .get_sample(target, "predictions", 2) + .sample_rows + ) with pytest.raises(NotImplementedError): sink.write_table(target, 'predictions', pd.DataFrame({'score': [1.0]}), write_mode=WriteMode.APPEND) @@ -198,7 +213,7 @@ def test_declared_ingest_dtype_preserves_physical_source_type( service, connector, tmp_path): from kumoapi.typing import Dtype - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) target = connector() assert source.source_types(target, 'events') == { 'id': 'int64', @@ -218,7 +233,7 @@ def test_csv_ingestion_downloads_raw_files_before_local_conversion( name = 'curated/orders/csv_events.csv' service.files[name] = b'id,value\n1,10.5\n2,20.5\n' - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) target = connector() version = source.get_data_version(target, 'csv_events.csv') output = source.prepare_ingest( @@ -251,7 +266,7 @@ def test_hive_parquet_ingestion_preserves_partition_values( service.files[f'{directory}/part.parquet'] = buffer.getvalue( ).to_pybytes() - output = ADLSSourceBackend().prepare_ingest( + output = ADLSSourceBackend(AMBIENT_PRINCIPAL).prepare_ingest( connector(), 'partitioned', str(tmp_path / 'ingest'), dtypes={ 'id': Dtype.int64, 'region': Dtype.string @@ -284,8 +299,9 @@ def test_rootless_invalid_authority_fails_before_source_access( access = Mock(side_effect=AssertionError('must not access storage')) monkeypatch.setattr('kumo_adls.backend.source_access', access) with pytest.raises(ValueError): - ADLSSourceBackend().get_columns(connector(any_uri=True), - f'abfss://{authority}/events.parquet') + ADLSSourceBackend(AMBIENT_PRINCIPAL).get_columns( + connector(any_uri=True), f"abfss://{authority}/events.parquet" + ) access.assert_not_called() @@ -299,8 +315,9 @@ def test_full_uri_sibling_and_filesystem_escape_is_rejected( access = Mock(side_effect=AssertionError('must not access storage')) monkeypatch.setattr('kumo_adls.backend.source_access', access) with pytest.raises(ValueError, match='source is outside'): - ADLSSourceBackend().get_columns(connector(), path) + ADLSSourceBackend(AMBIENT_PRINCIPAL).get_columns(connector(), path) with pytest.raises(ValueError, match='destination is outside'): - ADLSSinkBackend().write_table(connector(), path, - pd.DataFrame({'id': [1]})) + ADLSSinkBackend(AMBIENT_PRINCIPAL).write_table( + connector(), path, pd.DataFrame({"id": [1]}) + ) access.assert_not_called() diff --git a/packages/kumo-adls/tests/test_coordinates.py b/packages/kumo-adls/tests/test_coordinates.py index 1245f3d5f..65ee5df42 100644 --- a/packages/kumo-adls/tests/test_coordinates.py +++ b/packages/kumo-adls/tests/test_coordinates.py @@ -7,6 +7,7 @@ from kumo_adls.backend import ADLSSourceBackend from kumo_adls.sink import ADLSSinkBackend from kumoapi.source_table import ADLSRelativeSource, ADLSURISource +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL URI = 'abfss://curated@companylake.dfs.core.windows.net/orders/' @@ -29,8 +30,8 @@ def test_full_uri_output_obeys_rooted_relative_policy_before_storage( native = Mock(side_effect=AssertionError('must not bind native output')) monkeypatch.setattr('kumo_adls.backend.source_access', access) monkeypatch.setattr('kumo_adls.sink.filesystem_for', native) - source = ADLSSourceBackend() - sink = ADLSSinkBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) + sink = ADLSSinkBackend(AMBIENT_PRINCIPAL) with pytest.raises(ValueError): source.get_table_config(target, uri) @@ -55,10 +56,11 @@ def test_valid_full_uri_export_roundtrips_through_source_schema( target = connector(prefix=prefix) root = URI.removesuffix('orders/') + (prefix + '/' if prefix else '') uri = root + quote(filename) - returned = ADLSSinkBackend().write_table(target, uri, - pd.DataFrame({'id': [3, 4]})) + returned = ADLSSinkBackend(AMBIENT_PRINCIPAL).write_table( + target, uri, pd.DataFrame({"id": [3, 4]}) + ) assert returned == uri - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) config = source.get_table_config(target, returned).source_table assert isinstance(config.source, ADLSRelativeSource) assert config.source.path == filename @@ -78,9 +80,11 @@ def test_empty_root_relative_output_fails_before_storage( access = Mock(side_effect=AssertionError('must not access storage')) monkeypatch.setattr('kumo_adls.backend.source_access', access) with pytest.raises(ValueError): - ADLSSourceBackend().get_table_config(target, uri) + ADLSSourceBackend(AMBIENT_PRINCIPAL).get_table_config(target, uri) with pytest.raises(ValueError): - ADLSSinkBackend().write_table(target, uri, pd.DataFrame({'id': [1]})) + ADLSSinkBackend(AMBIENT_PRINCIPAL).write_table( + target, uri, pd.DataFrame({"id": [1]}) + ) access.assert_not_called() @@ -88,7 +92,7 @@ def test_rootless_full_uri_keeps_exact_source_policy(service, connector): uri = URI + 'scores%23review.parquet' service.files['curated/orders/scores#review.parquet'] = service.files[ 'curated/orders/events.parquet'] - source = ADLSSourceBackend() + source = ADLSSourceBackend(AMBIENT_PRINCIPAL) target = connector(any_uri=True) config = source.get_table_config(target, uri).source_table assert isinstance(config.source, ADLSURISource) @@ -110,7 +114,7 @@ def test_full_root_model_directory_roundtrip(service, connector, tmp_path, (bundle / 'nested').mkdir(parents=True) (bundle / 'model.bin').write_bytes(b'model') (bundle / 'nested/weights.bin').write_bytes(b'weights') - sink = ADLSSinkBackend() + sink = ADLSSinkBackend(AMBIENT_PRINCIPAL) original_files = dict(service.files) published = sink.publish_model(target, str(bundle), path=root_uri) @@ -129,7 +133,7 @@ def test_full_root_model_directory_roundtrip(service, connector, tmp_path, with pytest.raises(ValueError): sink.write_table(target, root_uri, pd.DataFrame({'id': [1]})) with pytest.raises(ValueError): - ADLSSourceBackend().get_table_config(target, root_uri) + ADLSSourceBackend(AMBIENT_PRINCIPAL).get_table_config(target, root_uri) @pytest.mark.parametrize('coordinate', [ @@ -150,7 +154,7 @@ def test_model_directory_rejection_precedes_storage_and_local_replacement( destination.mkdir() retained = destination / 'retained.bin' retained.write_bytes(b'keep') - sink = ADLSSinkBackend() + sink = ADLSSinkBackend(AMBIENT_PRINCIPAL) with pytest.raises(ValueError): sink.publish_model(target, str(destination), path=coordinate) @@ -163,7 +167,7 @@ def test_model_directory_rejection_precedes_storage_and_local_replacement( def test_rootless_model_directory_remains_unsupported(connector, tmp_path): target = connector(any_uri=True) - sink = ADLSSinkBackend() + sink = ADLSSinkBackend(AMBIENT_PRINCIPAL) for operation in (sink.publish_model, sink.fetch_model): with pytest.raises(NotImplementedError, match='source-only'): operation(target, str(tmp_path / 'bundle'), path=URI) diff --git a/packages/kumo-adls/tests/test_filesystem.py b/packages/kumo-adls/tests/test_filesystem.py index 0fa605584..8c440687d 100644 --- a/packages/kumo-adls/tests/test_filesystem.py +++ b/packages/kumo-adls/tests/test_filesystem.py @@ -21,6 +21,7 @@ TransientSourceError, ) from pyarrow.fs import FileType, FSSpecHandler, PyFileSystem +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL AUTHORITY = 'curated@companylake.dfs.core.windows.net' @@ -128,7 +129,7 @@ def properties_with_header_spelling(self): arrow = PyFileSystem(FSSpecHandler(filesystem)) directory = AUTHORITY + '/orders' assert arrow.get_file_info(directory).type == FileType.Directory - assert ADLSSourceBackend().list_tables( + assert ADLSSourceBackend(AMBIENT_PRINCIPAL).list_tables( connector()).table_names == ['events'] with pytest.raises(ValueError, match='versioned file'): filesystem.object_identity(directory) diff --git a/packages/kumo-adls/tests/test_native_auth.py b/packages/kumo-adls/tests/test_native_auth.py index 3f5d2a646..f5d29fd42 100644 --- a/packages/kumo-adls/tests/test_native_auth.py +++ b/packages/kumo-adls/tests/test_native_auth.py @@ -12,6 +12,7 @@ from kumo_adls.session import CLOUDS from kumoapi.data_source import ADLSIdentityConfig, AzureCloud from pyarrow.fs import AzureFileSystem, FileSystem +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL TENANT = 'private-tenant-value' CLIENT = 'private-client-value' @@ -90,7 +91,9 @@ def test_ambient_native_construction_uses_selected_cloud_without_env_mutation( suffix, _, authority = CLOUDS[cloud] monkeypatch.setenv('AZURE_AUTHORITY_HOST', 'https://' + authority + '/') before = dict(os.environ) - filesystem = native_output.filesystem_for(None, ACCOUNT, suffix, CONTAINER) + filesystem = native_output.filesystem_for( + AMBIENT_PRINCIPAL, ACCOUNT, suffix, CONTAINER + ) assert_native_mapping(filesystem, suffix) assert dict(os.environ) == before @@ -166,9 +169,12 @@ def test_authority_rejected_before_any_factory_without_secret_echo( factory = forbid_construction(monkeypatch) before = dict(os.environ) with pytest.raises(ValueError) as error: - native_output.filesystem_for(None if selected is None else principal(), - ACCOUNT, CLOUDS[AzureCloud.PUBLIC][0], - CONTAINER) + native_output.filesystem_for( + AMBIENT_PRINCIPAL if selected is None else principal(), + ACCOUNT, + CLOUDS[AzureCloud.PUBLIC][0], + CONTAINER, + ) factory.assert_not_called() assert dict(os.environ) == before for secret in [ @@ -184,7 +190,9 @@ def test_sovereign_cloud_rejects_unset_public_default_authority( auth_environment, monkeypatch, cloud): factory = forbid_construction(monkeypatch) with pytest.raises(ValueError, match='AZURE_AUTHORITY_HOST'): - native_output.filesystem_for(None, ACCOUNT, CLOUDS[cloud][0], CONTAINER) + native_output.filesystem_for( + AMBIENT_PRINCIPAL, ACCOUNT, CLOUDS[cloud][0], CONTAINER + ) factory.assert_not_called() diff --git a/packages/kumo-adls/tests/test_native_output.py b/packages/kumo-adls/tests/test_native_output.py index c42670006..96ae218ab 100644 --- a/packages/kumo-adls/tests/test_native_output.py +++ b/packages/kumo-adls/tests/test_native_output.py @@ -15,6 +15,7 @@ PyFileSystem, SubTreeFileSystem, ) +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL AUTHORITY = 'curated@companylake.dfs.core.windows.net' @@ -120,7 +121,7 @@ def unexpected_upload(*args, **kwargs): monkeypatch.setattr(ADLSFileSystem, 'put_file', unexpected_upload) monkeypatch.setattr(FakeFile, 'upload_data', unexpected_upload) - backend = ADLSSinkBackend() + backend = ADLSSinkBackend(AMBIENT_PRINCIPAL) backend.write_table(connector(), 'result.' + extension, pd.DataFrame({'id': [1, 2]}), write_mode=WriteMode.OVERWRITE) @@ -155,7 +156,9 @@ def factory(*args): return FakeNativeFilesystem(service) monkeypatch.setattr('kumo_adls.sink.filesystem_for', factory) - filesystem, _ = ADLSSinkBackend()._destination(connector(), 'unused') + filesystem, _ = ADLSSinkBackend(AMBIENT_PRINCIPAL)._destination( + connector(), "unused" + ) with filesystem.open_input_file(AUTHORITY + '/orders/events.parquet') as stream: assert stream.read(4) == b'PAR1' @@ -183,7 +186,7 @@ def unsupported(*args): raise NotImplementedError('unsupported native output identity') monkeypatch.setattr('kumo_adls.sink.filesystem_for', unsupported) - backend = ADLSSinkBackend() + backend = ADLSSinkBackend(AMBIENT_PRINCIPAL) filesystem, path = backend._destination(connector(), 'events.parquet') output = tmp_path / 'model.parquet' backend._download_file(filesystem, path, str(output)) @@ -199,7 +202,7 @@ def test_sink_integrates_real_local_native_stream_and_shared_copy( native = SubTreeFileSystem(str(tmp_path), LocalFileSystem()) native.create_dir('curated/orders') monkeypatch.setattr('kumo_adls.sink.filesystem_for', lambda *args: native) - backend = ADLSSinkBackend() + backend = ADLSSinkBackend(AMBIENT_PRINCIPAL) filesystem, destination = backend._destination(connector(), 'native.bin') source = tmp_path / 'prepared.bin' source.write_bytes(b'native output') @@ -219,7 +222,7 @@ def test_export_metadata_fence_rejects_other_identity_before_native_open( source = tmp_path / 'source.parquet' pq.write_table(pa.table({'id': [1]}), source) - backend = ADLSSinkBackend() + backend = ADLSSinkBackend(AMBIENT_PRINCIPAL) backend.write_files(connector(), 'predictions/', [str(source)], export_id='first') marker = 'curated/orders/predictions/_KUMO_EXPORT' @@ -253,7 +256,7 @@ def unsupported(*args): initial_directories = set(service.directories) initial_files = dict(service.files) initial_created = list(service.created) - backend = ADLSSinkBackend() + backend = ADLSSinkBackend(AMBIENT_PRINCIPAL) source = tmp_path / 'source.parquet' pq.write_table(pa.table({'id': [1]}), source) bundle = tmp_path / 'bundle' @@ -291,7 +294,7 @@ def forbidden(*args, **kwargs): # Preparing this root must not attempt to create its ancestor "orders". target = connector(prefix='orders/team') prefix = 'curated/orders/team/' - backend = ADLSSinkBackend() + backend = ADLSSinkBackend(AMBIENT_PRINCIPAL) if operation == 'write_table': backend.write_table(target, 'new/results.parquet', pd.DataFrame({'id': [1]})) @@ -333,8 +336,9 @@ def factory(*args): return FakeNativeFilesystem(service) monkeypatch.setattr('kumo_adls.sink.filesystem_for', factory) - filesystem, path = ADLSSinkBackend()._destination(connector(), - 'new/nested/') + filesystem, path = ADLSSinkBackend(AMBIENT_PRINCIPAL)._destination( + connector(), "new/nested/" + ) initial_directories = set(service.directories) initial_files = dict(service.files) diff --git a/packages/kumo-adls/tests/test_range_cache.py b/packages/kumo-adls/tests/test_range_cache.py index 177d8f465..bbb67adbf 100644 --- a/packages/kumo-adls/tests/test_range_cache.py +++ b/packages/kumo-adls/tests/test_range_cache.py @@ -14,6 +14,7 @@ from kumo_adls.range_cache import MAX_BYTES, MAX_ENTRIES, RangeBytes from kumo_adls.sdk_filesystem import ADLSFileSystem from kumo_core.sources.errors import TransientSourceError +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL AUTHORITY = 'curated@companylake.dfs.core.windows.net' PATH = AUTHORITY + '/orders/events.parquet' @@ -59,7 +60,7 @@ def head(self): def test_open_snapshot_can_reuse_old_bytes_but_identity_guard_rejects_mutation( service, connector, cache, tmp_path): - reader, name = ADLSSourceBackend()._reader(connector(), 'events') + reader, name = ADLSSourceBackend(AMBIENT_PRINCIPAL)._reader(connector(), 'events') fs = reader.filesystem.handler.fs found = reader._objects(name, PATH) identities = reader._identities(found, 1) diff --git a/packages/kumo-adls/tests/test_session.py b/packages/kumo-adls/tests/test_session.py index 2961dbd61..7e8468fcf 100644 --- a/packages/kumo-adls/tests/test_session.py +++ b/packages/kumo-adls/tests/test_session.py @@ -9,7 +9,12 @@ from kumo_adls import client as client_module from kumo_adls import session from kumo_core.sources.principals import Principal -from kumoapi.data_source import ADLSIdentityConfig, AzureCloud +from kumoapi.data_source import ( + ADLSAmbientIdentityConfig, + ADLSIdentityConfig, + AzureCloud, +) +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL @pytest.fixture(autouse=True) @@ -55,8 +60,10 @@ def test_ambient_identity_session_reuse_and_cleanup(monkeypatch): factory = Mock() monkeypatch.setattr(session, 'DefaultAzureCredential', credential_factory) monkeypatch.setattr(client_module, 'DataLakeServiceClient', factory) - first = session.session_for(None, 'companylake', 'dfs.core.windows.net') - assert session.session_for(None, 'companylake', + first = session.session_for( + AMBIENT_PRINCIPAL, "companylake", "dfs.core.windows.net" + ) + assert session.session_for(AMBIENT_PRINCIPAL, 'companylake', 'dfs.core.windows.net') is first credential_factory.assert_called_once() factory.assert_called_once_with( @@ -111,7 +118,7 @@ def test_ambient_session_uses_common_storage_audience(monkeypatch, cloud, monkeypatch.setattr(session, 'DefaultAzureCredential', credential_factory) monkeypatch.setattr(client_module, 'DataLakeServiceClient', client_factory) - session.session_for(None, 'companylake', suffix) + session.session_for(AMBIENT_PRINCIPAL, 'companylake', suffix) credential_factory.assert_called_once_with(authority=authority) client_factory.assert_called_once_with( @@ -130,8 +137,8 @@ def test_cleanup_failure_does_not_leave_other_sessions_open( credential_factory = Mock(side_effect=credentials) monkeypatch.setattr(session, 'DefaultAzureCredential', credential_factory) monkeypatch.setattr(client_module, 'DataLakeServiceClient', factory) - session.session_for(None, 'firstlake', 'dfs.core.windows.net') - session.session_for(None, 'otherlake', 'dfs.core.windows.net') + session.session_for(AMBIENT_PRINCIPAL, 'firstlake', 'dfs.core.windows.net') + session.session_for(AMBIENT_PRINCIPAL, 'otherlake', 'dfs.core.windows.net') resource = clients[0] if failing_resource == 'client' else credentials[0] resource.close.side_effect = RuntimeError('already closed') @@ -150,6 +157,40 @@ def test_client_construction_failure_releases_engine_owned_credential( monkeypatch.setattr(session, 'create_client', Mock(side_effect=RuntimeError('construction failed'))) with pytest.raises(RuntimeError, match='construction failed'): - session.session_for(None, 'companylake', 'dfs.core.windows.net') + session.session_for(AMBIENT_PRINCIPAL, 'companylake', 'dfs.core.windows.net') credential.close.assert_called_once() assert not session._SESSIONS + + +@pytest.mark.parametrize('cloud,suffix,authority', CLOUD_CASES) +def test_ambient_cloud_constraint_rejects_other_endpoints( + monkeypatch, cloud, suffix, authority): + principal = Principal('ambient-constrained', + ADLSAmbientIdentityConfig(cloud=cloud), None) + factory = Mock() + monkeypatch.setattr(session, 'DefaultAzureCredential', factory) + other_suffix = next(value[0] for key, value in session.CLOUDS.items() + if key != cloud) + + with pytest.raises(ValueError, match='identity cloud'): + session.credential_for(principal, other_suffix) + factory.assert_not_called() + + session.credential_for(principal, suffix) + factory.assert_called_once_with(authority=authority) + + +@pytest.mark.parametrize('cloud', [None, *AzureCloud]) +def test_ambient_probe_uses_configured_or_public_authority(monkeypatch, cloud): + credential = Mock() + credential.__enter__ = Mock(return_value=credential) + credential.__exit__ = Mock() + factory = Mock(return_value=credential) + monkeypatch.setattr(session, 'DefaultAzureCredential', factory) + principal = Principal('ambient', ADLSAmbientIdentityConfig(cloud=cloud), None) + expected = AzureCloud.PUBLIC if cloud is None else cloud + + session.probe(principal) + + factory.assert_called_once_with(authority=session.CLOUDS[expected][2]) + credential.get_token.assert_called_once_with('https://storage.azure.com/.default') diff --git a/packages/kumo-adls/tests/test_sink_preflight.py b/packages/kumo-adls/tests/test_sink_preflight.py index 9ebd0f89b..324513758 100644 --- a/packages/kumo-adls/tests/test_sink_preflight.py +++ b/packages/kumo-adls/tests/test_sink_preflight.py @@ -10,8 +10,10 @@ from kumo_adls import native_output from kumo_adls.session import CLOUDS from kumo_adls.sink import ADLSSinkBackend +from kumo_core.sources.principals import Principal from kumoapi.data_source import ADLSIdentityConfig from kumoapi.jobs import WriteMode +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL @pytest.mark.parametrize('cloud', list(CLOUDS)) @@ -24,11 +26,16 @@ def test_supported_preflight_constructs_no_clients(monkeypatch, connector, monkeypatch.setenv('AZURE_TENANT_ID', 'tenant') monkeypatch.setenv('AZURE_CLIENT_ID', 'client') monkeypatch.setenv('AZURE_FEDERATED_TOKEN_FILE', '/projected/token') - principal = SimpleNamespace( - config=ADLSIdentityConfig(tenant_id='tenant', client_id='client', - cloud=cloud)) if explicit else None - backend = ADLSSinkBackend() - monkeypatch.setattr(backend, '_principal', lambda _: principal) + principal = ( + Principal( + "workload", + ADLSIdentityConfig(tenant_id="tenant", client_id="client", cloud=cloud), + None, + ) + if explicit + else AMBIENT_PRINCIPAL + ) + backend = ADLSSinkBackend(principal) forbidden = Mock( side_effect=AssertionError('preflight constructed a client')) monkeypatch.setattr('kumo_adls.backend.source_access', forbidden) @@ -51,7 +58,7 @@ def test_default_write_policy_checks_occupancy_but_overwrite_preserves_behavior( service, connector): from kumo_core.artifact_export import ArtifactDestinationConflict - backend = ADLSSinkBackend() + backend = ADLSSinkBackend(AMBIENT_PRINCIPAL) target = connector() backend.preflight_write_files(target, 'out/') service.files['curated/orders/out/part.parquet'] = b'data' @@ -69,7 +76,7 @@ def test_default_write_policy_checks_occupancy_but_overwrite_preserves_behavior( @pytest.mark.parametrize('path', ['out/', 'scores.parquet']) def test_preflight_resolves_once_and_only_opens_storage_for_occupancy( service, connector, monkeypatch, mode, path): - backend = ADLSSinkBackend() + backend = ADLSSinkBackend(AMBIENT_PRINCIPAL) target = connector() resolve = Mock(wraps=backend._resolved) filesystem = Mock(wraps=backend._filesystem) diff --git a/packages/kumo-adls/tests/test_source_access.py b/packages/kumo-adls/tests/test_source_access.py index ce4e73b22..260979701 100644 --- a/packages/kumo-adls/tests/test_source_access.py +++ b/packages/kumo-adls/tests/test_source_access.py @@ -21,6 +21,7 @@ from kumo_adls.backend import ADLSSourceBackend from kumo_adls.reader import ADLSSourceReader, source_reader from kumo_core.sources.types import ReadMode +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL from test_sdk_transfer import HEADERS, HTTPAdapter @@ -84,8 +85,10 @@ def download(request, context): selected = Mock(return_value=borrowed) monkeypatch.setattr('kumo_adls.backend.session_for', selected) shared = reader_for(borrowed) - engine, name = ADLSSourceBackend()._reader(connector(), 'events.parquet') - selected.assert_called_once_with(None, 'companylake', + engine, name = ADLSSourceBackend(AMBIENT_PRINCIPAL)._reader( + connector(), "events.parquet" + ) + selected.assert_called_once_with(AMBIENT_PRINCIPAL, 'companylake', 'dfs.core.windows.net') assert type(shared) is type(engine) is ADLSSourceReader version = shared.data_version(name) @@ -158,7 +161,7 @@ def test_engine_cleanup_does_not_close_injected_client(monkeypatch): (credential, 'https://storage.azure.com')) monkeypatch.setattr(session, 'create_client', lambda *args: owned) session.close() - session.session_for(None, 'ownedlake', 'dfs.core.windows.net') + session.session_for(AMBIENT_PRINCIPAL, 'ownedlake', 'dfs.core.windows.net') session.close() assert owned.closed credential.close.assert_called_once() @@ -172,7 +175,7 @@ def test_shared_reader_preserves_root_spelling(connector, monkeypatch, prefix): monkeypatch.setattr('kumo_adls.backend.session_for', lambda *args: client) shared = source_reader(client, 'companylake', filesystem='curated', prefix=prefix) - engine = ADLSSourceBackend()._discovery(connector(prefix=prefix)) + engine = ADLSSourceBackend(AMBIENT_PRINCIPAL)._discovery(connector(prefix=prefix)) assert shared.root == engine.root diff --git a/packages/kumo-adls/tests/test_transfer.py b/packages/kumo-adls/tests/test_transfer.py index 5e7f324de..1563d65ee 100644 --- a/packages/kumo-adls/tests/test_transfer.py +++ b/packages/kumo-adls/tests/test_transfer.py @@ -11,6 +11,7 @@ from kumo_adls import transfer from kumo_adls.sdk_filesystem import ADLSFileSystem from pyarrow.fs import FileSelector, FSSpecHandler, PyFileSystem +from sources.identities import AMBIENT_ADLS_PRINCIPAL as AMBIENT_PRINCIPAL AUTHORITY = 'curated@companylake.dfs.core.windows.net' @@ -224,9 +225,13 @@ def unexpected_upload(*args, **kwargs): monkeypatch.setattr(ADLSFileSystem, 'put_file', unexpected_upload) source = tmp_path / 'source.parquet' pq.write_table(pa.table({'id': [1, 2]}), source) - ADLSSinkBackend().write_files(connector(), 'predictions/', [str(source)], - extra_columns={'tag': - 'test'}, export_id='run') + ADLSSinkBackend(AMBIENT_PRINCIPAL).write_files( + connector(), + "predictions/", + [str(source)], + extra_columns={"tag": "test"}, + export_id="run", + ) outputs = [ name for name in service.files if '/predictions/' in name and name.endswith('.parquet') @@ -257,8 +262,10 @@ def transport(**kwargs): return item monkeypatch.setattr(client_module, 'RequestsTransport', transport) - client = session.session_for(None, 'companylake', 'dfs.core.windows.net') - assert session.session_for(None, 'companylake', + client = session.session_for( + AMBIENT_PRINCIPAL, "companylake", "dfs.core.windows.net" + ) + assert session.session_for(AMBIENT_PRINCIPAL, 'companylake', 'dfs.core.windows.net') is client assert transports[ 0].connection_config.data_block_size == transfer.NETWORK_BLOCK_BYTES @@ -396,7 +403,9 @@ def test_model_download_uses_conditional_bulk_fetch(service, connector, service.directories.add('curated/orders/bundle') service.files['curated/orders/bundle/model.bin'] = b'model contents' target = tmp_path / 'model' - ADLSSinkBackend().fetch_model(connector(), str(target), path='bundle') + ADLSSinkBackend(AMBIENT_PRINCIPAL).fetch_model( + connector(), str(target), path="bundle" + ) assert (target / 'model.bin').read_bytes() == b'model contents' _, offset, length, options = service.downloads[-1] assert offset == 0 and length == len(b'model contents') diff --git a/packages/kumo-api/kumoapi/data_source.py b/packages/kumo-api/kumoapi/data_source.py index 9e21532ec..352287a62 100644 --- a/packages/kumo-api/kumoapi/data_source.py +++ b/packages/kumo-api/kumoapi/data_source.py @@ -947,6 +947,21 @@ def strip_inputs(cls, value: str) -> str: return _normalize_required_provider_field(value) +@dataclass(frozen=True, config=_FORBID_EXTRA_CONFIG) +class ADLSAmbientIdentityConfig: + """Ambient Azure authentication for local provider connections. + + Args: + cloud: Optional cloud constraint; storage endpoints select the cloud + when omitted. Standalone credential probing defaults to public Azure. + mode: Ambient credential selection. + type: ADLS provider identifier. + """ + cloud: Optional[AzureCloud] = None + mode: Literal['ambient'] = 'ambient' + type: Literal[IdentityType.ADLS] = IdentityType.ADLS + + IdentityConfig = Union[ DatabricksIdentityConfig, SnowflakeIdentityConfig, @@ -1113,7 +1128,7 @@ def serialize_secret(self, value: SecretStr, info: SerializationInfo): def validate_identity_credentials_match( - config: IdentityConfig, + config: Union[IdentityConfig, ADLSAmbientIdentityConfig], credentials: Optional[IdentityCredentials], ) -> None: if isinstance(config, DatabricksIdentityConfig): diff --git a/packages/kumo-api/test/test_adls_ambient_identity.py b/packages/kumo-api/test/test_adls_ambient_identity.py new file mode 100644 index 000000000..cb748b16e --- /dev/null +++ b/packages/kumo-api/test/test_adls_ambient_identity.py @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Local ADLS ambient authentication preserves the hosted identity contract.""" + +from dataclasses import asdict + +import pytest +from pydantic import TypeAdapter, ValidationError + +from kumoapi.data_source import ( + ADLSAmbientIdentityConfig, + AzureCloud, + CreateIdentityArgs, + IdentityConfig, + IdentityType, + S3AccessKeyCredentials, + validate_identity_credentials_match, +) + + +def test_ambient_config_has_no_stored_credentials_or_default_cloud() -> None: + """Ambient authentication selects its authority from the storage endpoint.""" + config = ADLSAmbientIdentityConfig() + + validate_identity_credentials_match(config, None) + + assert config.type is IdentityType.ADLS + assert config.mode == "ambient" + assert config.cloud is None + + +@pytest.mark.parametrize("cloud", list(AzureCloud)) +def test_ambient_config_can_constrain_the_cloud(cloud: AzureCloud) -> None: + """Callers may require a specific Azure cloud explicitly.""" + assert ADLSAmbientIdentityConfig(cloud=cloud).cloud is cloud + + +def test_ambient_config_rejects_unused_stored_credentials() -> None: + """An ambient principal cannot silently ignore supplied secret material.""" + config = ADLSAmbientIdentityConfig() + credentials = S3AccessKeyCredentials( + access_key_id="unused", secret_access_key="unused" + ) + + with pytest.raises(ValueError, match="config and credential types must match"): + validate_identity_credentials_match(config, credentials) + + +def test_hosted_identity_schema_remains_workload_only() -> None: + """Local ambient ADLS configs do not expand hosted identity schemas.""" + schema = TypeAdapter(IdentityConfig).json_schema() + fields = schema["$defs"]["ADLSIdentityConfig"] + + assert set(fields["required"]) == {"tenant_id", "client_id", "cloud"} + assert "ADLSAmbientIdentityConfig" not in schema["$defs"] + with pytest.raises(ValidationError): + TypeAdapter(CreateIdentityArgs).validate_python( + { + "display_name": "ambient", + "config": asdict(ADLSAmbientIdentityConfig()), + } + ) diff --git a/packages/kumo-bigquery/src/kumo_bigquery/session.py b/packages/kumo-bigquery/src/kumo_bigquery/session.py index 78130fb15..a29f9ed31 100644 --- a/packages/kumo-bigquery/src/kumo_bigquery/session.py +++ b/packages/kumo-bigquery/src/kumo_bigquery/session.py @@ -14,11 +14,13 @@ from __future__ import annotations +import logging import threading from contextlib import ExitStack from typing import Any, List import google.auth.transport.requests +from google.api_core.exceptions import GoogleAPIError from google.auth.credentials import Credentials from google.cloud import bigquery, bigquery_storage, storage from kumo_bigquery.auth import google_credentials @@ -139,13 +141,26 @@ class BigQueryConnection: Pickling retains only the principal; clients and locks are worker-local. """ + _logger = logging.getLogger(__name__) + _CLOSE_ERRORS = (GoogleAPIError, OSError, RuntimeError, AttributeError) + def __init__(self, identity: Principal | None) -> None: self._identity = identity - self._lock = threading.RLock() self._query: dict[tuple[str, str], Any] = {} self._read: Any = None self._write: Any = None self._storage: dict[str, Any] = {} + self._lock = threading.RLock() + + def __del__(self) -> None: + """Release owned resources during normal garbage collection, best effort.""" + if not hasattr(self, "_lock"): + return + try: + self.close() + except self._CLOSE_ERRORS as error: + self._logger.error("BigQuery connection cleanup failed (%s).", + type(error).__name__) @property def identity(self) -> Principal | None: diff --git a/packages/kumo-bigquery/tests/test_connection.py b/packages/kumo-bigquery/tests/test_connection.py index 3dc4ceefb..f37a50b23 100644 --- a/packages/kumo-bigquery/tests/test_connection.py +++ b/packages/kumo-bigquery/tests/test_connection.py @@ -3,7 +3,10 @@ # SPDX-License-Identifier: Apache-2.0 """Connector-owned Google clients isolate authentication and worker state.""" +import gc +import logging import pickle +import weakref from concurrent.futures import ThreadPoolExecutor from types import SimpleNamespace from unittest.mock import Mock @@ -210,3 +213,43 @@ def test_backend_table_locations_use_the_data_project( assert source.table_location(connector, "events") == "sample-project.dataset.events" assert sink.table_location(connector, "events") == "sample-project.dataset.events" + + +def test_discarded_owner_closes_its_transport( + principals: tuple[Principal, Principal], + monkeypatch: pytest.MonkeyPatch, + read_builder: Mock, +) -> None: + """Dropping the owner releases clients even if callers never close explicitly.""" + monkeypatch.setattr(session, "_credentials_for", lambda _: Mock(token="token")) + owner = session.BigQueryConnection(principals[0]) + read = owner.read_client() + owner_ref = weakref.ref(owner) + + del owner + gc.collect() + + assert owner_ref() is None + read.transport.close.assert_called_once_with() + assert read_builder.call_count == 1 + + +def test_destructor_logs_cleanup_failure_without_secret_contents( + principals: tuple[Principal, Principal], + monkeypatch: pytest.MonkeyPatch, + read_builder: Mock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Best-effort finalization logs only the error type and does not raise.""" + monkeypatch.setattr(session, "_credentials_for", lambda _: Mock(token="token")) + owner = session.BigQueryConnection(principals[0]) + read = owner.read_client() + read.transport.close.side_effect = RuntimeError("sensitive credential detail") + caplog.set_level(logging.ERROR, logger=session.__name__) + + del owner + gc.collect() + + read.transport.close.assert_called_once_with() + assert "BigQuery connection cleanup failed (RuntimeError)" in caplog.text + assert "sensitive credential detail" not in caplog.text diff --git a/packages/kumo-core/README.md b/packages/kumo-core/README.md index eaa158c00..ca8882c0c 100644 --- a/packages/kumo-core/README.md +++ b/packages/kumo-core/README.md @@ -101,16 +101,19 @@ Provider authentication uses `kumo_core.sources.principals.Principal` values. Engine connectors normalize convenience identities such as `S3Identity` before constructing their backends. Configuration and explicit credentials travel with that value; ambient credentials and token-file contents are resolved on the -receiving worker. Identity names, IDs, and slug-only metadata no longer resolve -through a process-global registry. +receiving worker. Backends authenticate from explicit principals, +not from names, IDs, or slug-only metadata. Snowflake and BigQuery backends require a `SnowflakeConnection` or `BigQueryConnection`, constructed by their engine connector and shared between its backends. Direct provider callers must explicitly construct that owner from a principal, for example `SnowflakeSourceBackend(SnowflakeConnection(principal))`. -These backends no longer accept an `identity` argument or create their own owner. +These backends use the supplied connection owner for every operation. -Other provider backends accept `identity=principal`. For example: +Object-store connectors default to explicit ambient identities: `S3Identity()`, +`GCSIdentity()`, and `ADLSIdentity()`. Their backends require `identity=principal`, +including for ambient authentication; connector metadata does not select credentials. +For example: ```python from kumo_core.sources.principals import Principal @@ -125,19 +128,28 @@ principal = Principal( backend = S3SourceBackend(identity=principal) ``` -A name or ID supplied without a principal raises a migration error. Leaving the -identity unset still selects ambient authentication for backends that support it. -The service SDK's remote identity-management API is separate from this local -connection interface. +ADLS ambient principals use `ADLSAmbientIdentityConfig`, which selects Azure's +runtime credential chain and derives the cloud from the storage endpoint unless +explicitly constrained. `ADLSIdentity(tenant_id=..., client_id=...)` selects a +workload identity. Hosted ADLS identity configuration requires tenant, client, and +cloud bindings; the service SDK's identity-management API is separate. + +Missing principals and name/ID-only inputs are rejected before credential discovery. Snowflake and BigQuery engine connectors each own their lazy authenticated connections and share them between their source and sink backends. Separate connectors never share sessions or clients, even with identical principal names. -Call `connector.close()` to release those resources; later operations reconnect. +Connection owners release resources in `__del__` as best-effort garbage-collection +cleanup. Call `connector.close()` or `connection.close()` for prompt release; +later operations reconnect. Call `close()` from a `finally` block when cleanup +must run at a known lifetime boundary. Retain the connector or owner while using +borrowed SDK clients or raw Snowpark sessions. Stage filesystems retain their +connection owner for as long as the filesystem is referenced. Serialization retains authentication configuration and explicit credentials, but not live connections or locks, so receiving workers open their own connections. -The provider-level global `close(name)` APIs are removed. +ADLS separately maintains its provider-owned process cache and exposes +`kumo_adls.session.close()` for cleanup. Snowflake stage access uses the connector's sink filesystem, including snapshot -export/restore and MLOps artifacts. The unused `StageArtifactLocation` adapter is -removed; its shared stage-filesystem helpers remain. +export/restore and MLOps artifacts. Shared stage-filesystem helpers implement +the file operations. diff --git a/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py b/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py index 4d93a9916..7c2d48f99 100644 --- a/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py +++ b/packages/kumo-core/src/kumo_core/sources/object_store_sessions.py @@ -45,8 +45,11 @@ class ObjectStoreSessions(ABC): rooted: type[Any] resource_config: type[Any] - def __init__(self, identity: Optional[Principal] = None, + def __init__(self, identity: Principal, storage_namespace: Optional[str] = None) -> None: + if not isinstance(identity, Principal): + raise TypeError("Object-store backends require an explicit Principal, " + "including for ambient authentication.") self._identity = identity self.storage_namespace = storage_namespace or self.namespace @@ -163,10 +166,3 @@ def _destination(self, connector: SourceConnector, coordinate: str) -> Tuple[FileSystem, str]: bucket, path, region = self._resolved(connector, coordinate) return self._filesystem(connector, bucket, region), path - - def _principal(self, connector: SourceConnector) -> Optional[Principal]: - if self._identity is None or isinstance(self._identity, Principal): - return self._identity - raise ValueError( - f"Connector {connector.id!r} needs a Principal passed to its backend. " - "Identity name, ID, and slug lookup is no longer supported.") diff --git a/packages/kumo-core/src/kumo_core/sources/principals.py b/packages/kumo-core/src/kumo_core/sources/principals.py index 613187b19..a6da13cc4 100644 --- a/packages/kumo-core/src/kumo_core/sources/principals.py +++ b/packages/kumo-core/src/kumo_core/sources/principals.py @@ -1,11 +1,16 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Self-contained connection principals with no process-global identity registry.""" +"""Provider connection configuration and credentials.""" from dataclasses import dataclass -from kumoapi.data_source import IdentityConfig, IdentityCredentials, IdentityType +from kumoapi.data_source import ( + ADLSAmbientIdentityConfig, + IdentityConfig, + IdentityCredentials, + IdentityType, +) __all__ = ["Principal"] @@ -21,7 +26,7 @@ class Principal: """ name: str - config: IdentityConfig + config: IdentityConfig | ADLSAmbientIdentityConfig credentials: IdentityCredentials | None @property diff --git a/packages/kumo-core/tests/sources/identities.py b/packages/kumo-core/tests/sources/identities.py new file mode 100644 index 000000000..e4c0a7d14 --- /dev/null +++ b/packages/kumo-core/tests/sources/identities.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Explicit ambient principals for provider tests with mocked authentication.""" + +from kumo_core.sources.principals import Principal +from kumoapi.data_source import ( + ADLSAmbientIdentityConfig, + GCSIdentityConfig, + GoogleAmbientAuthentication, + S3AmbientAuthentication, + S3IdentityConfig, +) + +AMBIENT_S3_PRINCIPAL = Principal( + "ambient-s3", S3IdentityConfig(authentication=S3AmbientAuthentication()), None +) +AMBIENT_GCS_PRINCIPAL = Principal( + "ambient-gcs", GCSIdentityConfig(authentication=GoogleAmbientAuthentication()), None +) +AMBIENT_ADLS_PRINCIPAL = Principal("ambient-adls", ADLSAmbientIdentityConfig(), None) diff --git a/packages/kumo-core/tests/sources/unit/test_principals.py b/packages/kumo-core/tests/sources/unit/test_principals.py index 71125d887..c8d7eadd5 100644 --- a/packages/kumo-core/tests/sources/unit/test_principals.py +++ b/packages/kumo-core/tests/sources/unit/test_principals.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Principals carry explicit authentication without registry lookup or fallback.""" +"""Explicit principals carry provider configuration and credential material.""" import pickle from types import SimpleNamespace @@ -54,44 +54,24 @@ def test_ambient_principal_needs_no_stored_credentials() -> None: assert principal.credentials is None -@pytest.mark.parametrize("connector_identity", [None, "legacy", "other-principal"]) -def test_object_store_uses_only_backend_principal( - principal: Principal, - connector_identity: object, -) -> None: - """Connector identity metadata cannot override the backend's credentials.""" - other = Principal("other", principal.config, principal.credentials) - connector = SimpleNamespace( - id="source", - identity=other - if connector_identity == "other-principal" - else connector_identity, +def test_object_store_accepts_explicit_ambient_principal() -> None: + """An ambient configuration is still an explicit authentication choice.""" + principal = Principal( + "ambient", S3IdentityConfig(authentication=S3AmbientAuthentication()), None ) - backend = cast(ObjectStoreSessions, SimpleNamespace(_identity=principal)) - - assert ObjectStoreSessions._principal(backend, connector) is principal + backend = cast(ObjectStoreSessions, SimpleNamespace(namespace="s3")) + ObjectStoreSessions.__init__(backend, principal) -def test_object_store_without_principal_uses_ambient_authentication( - principal: Principal, -) -> None: - """A principal on a connector cannot replace an unset backend principal.""" - connector = SimpleNamespace(id="source", identity=principal) - backend = cast(ObjectStoreSessions, SimpleNamespace(_identity=None)) - - assert ObjectStoreSessions._principal(backend, connector) is None + assert backend._identity is principal @pytest.mark.parametrize( - "identity", ["name", "identity-id", "", SimpleNamespace(slug="slug")] + "identity", [None, "name", "identity-id", "", SimpleNamespace(slug="slug")] ) -def test_invalid_backend_identity_is_rejected( - principal: Principal, - identity: object, -) -> None: - """Invalid backend credentials fail even when a connector has a principal.""" - connector = SimpleNamespace(id="source", identity=principal) - backend = cast(ObjectStoreSessions, SimpleNamespace(_identity=identity)) +def test_missing_or_invalid_backend_identity_is_rejected(identity: object) -> None: + """Missing principals fail before credential discovery or connector lookup.""" + backend = cast(ObjectStoreSessions, SimpleNamespace(namespace="s3")) - with pytest.raises(ValueError, match="lookup is no longer supported"): - ObjectStoreSessions._principal(backend, connector) + with pytest.raises(TypeError, match="explicit Principal"): + ObjectStoreSessions.__init__(backend, cast(Principal, identity)) diff --git a/packages/kumo-engine/kumo/engine/connector/adls.py b/packages/kumo-engine/kumo/engine/connector/adls.py index 946a6437a..f8876e7d8 100644 --- a/packages/kumo-engine/kumo/engine/connector/adls.py +++ b/packages/kumo-engine/kumo/engine/connector/adls.py @@ -35,7 +35,8 @@ class ADLSConnector(Connector): """ def __init__(self, *, root_dir: Optional[str] = None, identity: Optional[ADLSIdentity] = None) -> None: - super().__init__(identity=identity) + super().__init__( + identity=identity if identity is not None else ADLSIdentity()) if root_dir is None: target = ADLSAnyURIConnectorTarget() else: diff --git a/packages/kumo-engine/kumo/engine/connector/base.py b/packages/kumo-engine/kumo/engine/connector/base.py index ba2761165..38e446e97 100644 --- a/packages/kumo-engine/kumo/engine/connector/base.py +++ b/packages/kumo-engine/kumo/engine/connector/base.py @@ -50,9 +50,8 @@ class Connector(ABC): Args: identity: Credentials to authenticate as -- an `Identity` object (e.g. `SnowflakeIdentity`, `S3Identity`), passed directly rather - than by name/id. `None` defers to whatever the underlying plugin - package treats as its ambient default (e.g. the local AWS/GCP - credential chain for S3/GCS). + than by name/id. Concrete connectors select an ambient identity by default where + supported; Snowflake requires a configured identity to connect. """ def __init__(self, identity: Optional[Identity] = None) -> None: self.identity = identity diff --git a/packages/kumo-engine/kumo/engine/connector/bigquery.py b/packages/kumo-engine/kumo/engine/connector/bigquery.py index 22ef2e979..c41ab49d0 100644 --- a/packages/kumo-engine/kumo/engine/connector/bigquery.py +++ b/packages/kumo-engine/kumo/engine/connector/bigquery.py @@ -28,8 +28,8 @@ class BigQueryConnector(Connector): Args: project_id: Google Cloud project containing the dataset. dataset_id: BigQuery dataset ID. - identity: A `BigQueryIdentity`, passed directly. `None` defers to - `kumo_bigquery`'s own ambient-credential resolution. + identity: A `BigQueryIdentity`, passed directly. None selects + `BigQueryIdentity()` for ambient Google credentials. location: BigQuery dataset location, e.g. `"US"` or `"europe-west1"`. billing_project_id: Optional Google Cloud project to bill for @@ -55,7 +55,8 @@ def __init__( ) -> None: if require_staged and not staging_uri: raise ValueError("require_staged needs a staging_uri") - super().__init__(identity=identity) + super().__init__( + identity=identity if identity is not None else BigQueryIdentity()) self._config = BigQueryConnectorResourceConfig( project_id=project_id, dataset_id=dataset_id, diff --git a/packages/kumo-engine/kumo/engine/connector/gcs.py b/packages/kumo-engine/kumo/engine/connector/gcs.py index 202f47fa2..f16078c87 100644 --- a/packages/kumo-engine/kumo/engine/connector/gcs.py +++ b/packages/kumo-engine/kumo/engine/connector/gcs.py @@ -65,7 +65,8 @@ def __init__( identity: Optional[GCSIdentity] = None, requester_pays_project: Optional[str] = None, ) -> None: - super().__init__(identity=identity) + super().__init__( + identity=identity if identity is not None else GCSIdentity()) target: GCSConnectorTarget if root_dir is None: target = GCSAnyURIConnectorTarget() diff --git a/packages/kumo-engine/kumo/engine/connector/identity.py b/packages/kumo-engine/kumo/engine/connector/identity.py index 1bcd02c46..0af6f01b4 100644 --- a/packages/kumo-engine/kumo/engine/connector/identity.py +++ b/packages/kumo-engine/kumo/engine/connector/identity.py @@ -12,6 +12,7 @@ from kumo_core.sources.principals import Principal from kumoapi.data_source import ( + ADLSAmbientIdentityConfig, ADLSIdentityConfig, AzureCloud, BigQueryIdentityConfig, @@ -52,7 +53,7 @@ class Identity: def __init__( self, - config: IdentityConfig, + config: IdentityConfig | ADLSAmbientIdentityConfig, credentials: Optional[IdentityCredentials] = None, ) -> None: validate_identity_credentials_match(config, credentials) @@ -271,15 +272,28 @@ def __init__( class ADLSIdentity(Identity): - """An Azure application authenticated through a projected workload token. + """Azure authentication through ambient credentials or a workload token. - ``AZURE_FEDERATED_TOKEN_FILE`` supplies the assertion. No secrets are - stored. Omit the connector identity to use Azure's ambient credentials. - Identity probing validates token acquisition, not storage permissions. + Args: + tenant_id: Workload tenant, supplied together with client_id. Omit both + to select the ambient Azure credential chain. + client_id: Workload application, supplied together with tenant_id. + cloud: Optional cloud constraint for ambient authentication. Workload + identities default to public Azure. Ambient storage connections + infer the cloud from their target endpoint when this is omitted. + + Raises: + ValueError: Only one workload identifier is supplied, or fields are invalid. """ - def __init__(self, *, tenant_id: str, client_id: str, - cloud: AzureCloud = AzureCloud.PUBLIC) -> None: - super().__init__( - ADLSIdentityConfig(tenant_id=tenant_id, client_id=client_id, - cloud=cloud)) + def __init__(self, *, tenant_id: str | None = None, + client_id: str | None = None, + cloud: AzureCloud | None = None) -> None: + if tenant_id is None and client_id is None: + super().__init__(ADLSAmbientIdentityConfig(cloud=cloud)) + return + if tenant_id is None or client_id is None: + raise ValueError("tenant_id and client_id must be supplied together.") + super().__init__(ADLSIdentityConfig( + tenant_id=tenant_id, client_id=client_id, + cloud=AzureCloud.PUBLIC if cloud is None else cloud)) diff --git a/packages/kumo-engine/kumo/engine/connector/s3.py b/packages/kumo-engine/kumo/engine/connector/s3.py index 3cd8be66b..3a6fb7fd2 100644 --- a/packages/kumo-engine/kumo/engine/connector/s3.py +++ b/packages/kumo-engine/kumo/engine/connector/s3.py @@ -72,7 +72,8 @@ def __init__( identity: Optional[S3Identity] = None, region: Optional[str] = None, ) -> None: - super().__init__(identity=identity) + super().__init__( + identity=identity if identity is not None else S3Identity()) if root_dir is None: if region is not None: raise ValueError( diff --git a/packages/kumo-engine/kumo/engine/connector/snowflake.py b/packages/kumo-engine/kumo/engine/connector/snowflake.py index 433739585..31301631c 100644 --- a/packages/kumo-engine/kumo/engine/connector/snowflake.py +++ b/packages/kumo-engine/kumo/engine/connector/snowflake.py @@ -46,8 +46,9 @@ class SnowflakeConnector(Connector): warehouse: Snowflake virtual warehouse used for queries. database: Snowflake database containing the target schema. schema_name: Schema within `database`. - identity: A `SnowflakeIdentity`, passed directly. `None` defers to - `kumo_snowflake`'s own ambient-session resolution. + identity: A `SnowflakeIdentity` is required to connect. Use + `from_spcs_env()` or `from_connection_toml()` to construct a + connector with an identity from the execution environment. role: Optional Snowflake role to activate for this target. """ def __init__( @@ -113,7 +114,7 @@ def sink_backend(self) -> ArtifactSink: return SnowflakeSinkBackend(connection=self._connection) def session(self) -> Any: - r"""The Snowpark session this connector reads through.""" + """Return the borrowed Snowpark session; retain this connector while using it.""" return self._connection.get(self) def source_table_for(self, table_name: str) -> SnowflakeSourceTable: diff --git a/packages/kumo-engine/test/test_ambient_identities.py b/packages/kumo-engine/test/test_ambient_identities.py new file mode 100644 index 000000000..104bfa599 --- /dev/null +++ b/packages/kumo-engine/test/test_ambient_identities.py @@ -0,0 +1,86 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""No-argument object-store identities select ambient authentication explicitly.""" + +import pickle + +import pytest +from kumoapi.data_source import ( + ADLSAmbientIdentityConfig, + ADLSIdentityConfig, + AzureCloud, +) + +from kumo.engine.connector import ( + ADLSConnector, + ADLSIdentity, + BigQueryConnector, + BigQueryIdentity, + GCSConnector, + GCSIdentity, + S3Connector, + S3Identity, +) + + +@pytest.mark.parametrize( + "connector_type,identity_type", + [ + (S3Connector, S3Identity), + (GCSConnector, GCSIdentity), + (ADLSConnector, ADLSIdentity), + ], +) +def test_omitted_identity_normalizes_to_explicit_ambient_principal( + connector_type: type[S3Connector] | type[GCSConnector] | type[ADLSConnector], + identity_type: type[S3Identity] | type[GCSIdentity] | type[ADLSIdentity], +) -> None: + """Default connectors pass one ambient principal to both provider backends.""" + connector = connector_type() + + assert isinstance(connector.identity, identity_type) + assert connector._principal is not None + assert connector._principal.credentials is None + assert connector.source_backend._identity is connector._principal + assert connector.sink_backend._identity is connector._principal + + +def test_ambient_adls_identity_survives_worker_transport() -> None: + """Serialization retains ambient selection while deferring credential lookup.""" + identity = pickle.loads(pickle.dumps(ADLSIdentity())) + + principal = identity.principal + assert isinstance(principal.config, ADLSAmbientIdentityConfig) + assert principal.config.cloud is None + assert principal.credentials is None + + +def test_workload_adls_identity_keeps_public_cloud_default() -> None: + """Existing workload identity calls retain their original configuration.""" + identity = ADLSIdentity(tenant_id="tenant", client_id="client") + + assert identity.principal.config == ADLSIdentityConfig( + tenant_id="tenant", client_id="client", cloud=AzureCloud.PUBLIC + ) + + +@pytest.mark.parametrize("tenant_id,client_id", [("tenant", None), (None, "client")]) +def test_partial_workload_identity_does_not_select_ambient_auth( + tenant_id: str | None, + client_id: str | None, +) -> None: + """Incomplete workload credentials fail instead of selecting another identity.""" + with pytest.raises(ValueError, match="supplied together"): + ADLSIdentity(tenant_id=tenant_id, client_id=client_id) + + +def test_bigquery_omitted_identity_uses_ambient_principal() -> None: + """Default BigQuery authentication is explicit and resolved only on use.""" + connector = BigQueryConnector(project_id="sample-project", dataset_id="dataset") + + assert isinstance(connector.identity, BigQueryIdentity) + assert connector._principal is not None + assert connector._principal.credentials is None + assert connector.source_backend._connection.identity is connector._principal + assert connector.sink_backend._connection is connector.source_backend._connection diff --git a/packages/kumo-engine/test/test_connector_connections.py b/packages/kumo-engine/test/test_connector_connections.py index 925fc07a6..37e8034b5 100644 --- a/packages/kumo-engine/test/test_connector_connections.py +++ b/packages/kumo-engine/test/test_connector_connections.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Engine connectors own and share provider connections without global caches.""" +"""Engine source and sink backends share connector-owned provider connections.""" import pickle from unittest.mock import Mock diff --git a/packages/kumo-engine/test/test_identity.py b/packages/kumo-engine/test/test_identity.py index de8740978..5fc0c2cbb 100644 --- a/packages/kumo-engine/test/test_identity.py +++ b/packages/kumo-engine/test/test_identity.py @@ -1,18 +1,14 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Direct credentials resolve without process-local registration.""" +"""Provider identities retain credentials across transport.""" import pickle -import uuid - -import pytest -from kumo_core.sources.principals import Principal from kumo.engine.connector.identity import S3Identity -def test_direct_identity_survives_pickle_without_store() -> None: +def test_identity_retains_credentials_across_pickle() -> None: """Transported convenience identities supply explicit connection principals.""" original = S3Identity(access_key_id="example", secret_access_key="secret") identity = pickle.loads(pickle.dumps(original)) @@ -29,63 +25,3 @@ def test_random_slugs_do_not_encode_credentials() -> None: for _ in range(5) ] assert len({identity.slug for identity in identities}) == 5 - - -def test_colliding_slugs_do_not_alias_credentials( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """Direct resolution uses the supplied principal even with identical names.""" - monkeypatch.setattr(uuid, "uuid4", lambda: uuid.UUID(int=1)) - first = S3Identity(access_key_id="first", secret_access_key="secret1") - second = S3Identity(access_key_id="second", secret_access_key="secret2") - assert first.slug == second.slug - assert second.principal.credentials.access_key_id.get_secret_value() == "second" - - -@pytest.mark.parametrize("provider", ["s3", "gcs", "bigquery", "databricks"]) -def test_source_backends_use_explicit_principals(provider: str) -> None: - """Provider authentication paths consume supplied identities without lookup.""" - from types import SimpleNamespace - - from kumo.engine.connector import ( - BigQueryConnector, - BigQueryIdentity, - DatabricksConnector, - DatabricksIdentity, - GCSConnector, - GCSIdentity, - S3Connector, - ) - - connectors = { - "s3": lambda: S3Connector(identity=S3Identity()), - "gcs": lambda: GCSConnector(identity=GCSIdentity()), - "bigquery": lambda: BigQueryConnector( - project_id="test-project", dataset_id="dataset", identity=BigQueryIdentity() - ), - "databricks": lambda: DatabricksConnector( - catalog="catalog", - schema_name="schema", - warehouse_id="warehouse", - identity=DatabricksIdentity(), - ), - } - connector = connectors[provider]() - backend = connector.source_backend - if provider == "bigquery": - principal = backend._connection.identity - assert principal == connector.identity.principal - assert connector.sink_backend._connection is backend._connection - return - principal = backend._identity - assert isinstance(principal, Principal) - assert principal == connector.identity.principal - assert connector.sink_backend._identity is principal - assert backend._principal(connector) is principal - assert ( - backend._principal(SimpleNamespace(id="remote", identity_id="remote-id")) - is principal - ) - - other = Principal("other", principal.config, principal.credentials) - assert backend._principal(SimpleNamespace(id="remote", identity=other)) is principal diff --git a/packages/kumo-gcs/src/kumo_gcs/backend.py b/packages/kumo-gcs/src/kumo_gcs/backend.py index 44e770a9a..4bdf0e155 100644 --- a/packages/kumo-gcs/src/kumo_gcs/backend.py +++ b/packages/kumo-gcs/src/kumo_gcs/backend.py @@ -40,7 +40,7 @@ class GCSSessions(ObjectStoreSessions): Args: identity: Principal used for all connections opened by this backend. - None selects ambient authentication. + Use an ambient principal for runtime credential discovery. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a table contributes. Defaults to Google Cloud Storage; name a compatible service explicitly, or its @@ -63,9 +63,8 @@ def _source_access(self, connector: Any, bucket: str, from .source_access import source_access config = self._target_config(connector) - principal = self._principal(connector) - credentials = (_gcs_session_for(principal) - if principal is not None else None) + principal = self._identity + credentials = _gcs_session_for(principal) if isinstance(credentials, fs.GcsFileSystem): if getattr(config, 'requester_pays_project', None) is not None: raise ValueError('A prebuilt GcsFileSystem cannot send ' @@ -99,9 +98,8 @@ def _filesystem(self, connector: Any, bucket: str, f"'userProject' a requester-pays bucket needs on every " f"request. Unset requester_pays_project, or read from a " f"bucket its owner pays for.") - principal = self._principal(connector) - session = (_gcs_session_for(principal) - if principal is not None else None) + principal = self._identity + session = _gcs_session_for(principal) if isinstance(session, fs.GcsFileSystem): return session if session is None: @@ -115,13 +113,13 @@ class GCSSourceBackend(GCSSessions, ObjectStoreSourceBackend): r"""Resolves source tables by reading Google Cloud Storage in this process. - Install with ``pip install 'kumoai-studio[gcs]'``. Without a named identity, - reads use Application Default Credentials. Arrow serves metadata and + Install with ``pip install 'kumo-engine[gcs]'``. Ambient principals use + Application Default Credentials. Arrow serves metadata and the shared downloader handles native and SDK transfers. Args: identity: Principal used for all connections opened by this backend. - None selects ambient authentication. + Use an ambient principal for runtime credential discovery. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a GCS table contributes. Defaults to Google Cloud Storage. @@ -129,12 +127,11 @@ class GCSSourceBackend(GCSSessions, ObjectStoreSourceBackend): store offers only ``streamed``, so this exists to assert that. Example: - >>> import kumoai_studio as kumo # doctest: +SKIP - >>> from kumo_gcs import GCSSourceBackend # doctest: +SKIP - >>> kumo.set_backend(kumo.LocalBackend( # doctest: +SKIP - ... sources={kumo.DataSourceType.GCS: GCSSourceBackend()})) - >>> events = kumo.GCSConnector( # doctest: +SKIP - ... name='events', root_dir='gs://company-data/events/') + >>> from kumo_core.sources.principals import Principal + >>> from kumoapi.data_source import GCSIdentityConfig, GoogleAmbientAuthentication + >>> principal = Principal('ambient', GCSIdentityConfig( + ... authentication=GoogleAmbientAuthentication()), None) + >>> backend = GCSSourceBackend(identity=principal) """ source_type = DataSourceType.GCS @@ -145,7 +142,7 @@ class GCSSourceBackend(GCSSessions, ObjectStoreSourceBackend): def __init__( self, - identity: Optional[Principal] = None, + identity: Principal, storage_namespace: Optional[str] = None, mode: Optional[ReadMode] = None, ) -> None: diff --git a/packages/kumo-s3/src/kumo_s3/backend.py b/packages/kumo-s3/src/kumo_s3/backend.py index c7419ad0e..385f32a5b 100644 --- a/packages/kumo-s3/src/kumo_s3/backend.py +++ b/packages/kumo-s3/src/kumo_s3/backend.py @@ -49,7 +49,7 @@ class S3Sessions(ObjectStoreSessions): Args: identity: Principal used for all connections opened by this backend. - None selects ambient authentication. + Use an ambient principal for runtime credential discovery. storage_namespace: The storage system this process reaches, recorded in every graph coordinate a table contributes. Defaults to ordinary AWS S3; name an S3-compatible service explicitly, or its @@ -70,15 +70,12 @@ class S3Sessions(ObjectStoreSessions): def _resolved_session( self, connector: Any, bucket: str ) -> tuple[S3Session, bool, Optional[S3ConnectionConfig]]: - principal = self._principal(connector) + principal = self._identity with kumo_s3.translated(f'Signing for {bucket}', table=bucket): - session = (_session_for(principal) - if principal is not None else kumo_s3.ambient_session()) - connection = (principal.config.connection if principal is not None - and isinstance(principal.config, S3IdentityConfig) else - None) - return session, principal is None or _is_ambient( - principal.config), connection + session = _session_for(principal) + connection = (principal.config.connection + if isinstance(principal.config, S3IdentityConfig) else None) + return session, _is_ambient(principal.config), connection def _source_access(self, connector: Any, bucket: str, region: Optional[str]) -> ObjectStoreAccess: @@ -157,7 +154,7 @@ class S3SourceBackend(S3Sessions, ObjectStoreSourceBackend): Args: identity: Principal used for all connections opened by this backend. - None selects ambient authentication. + Use an ambient principal for runtime credential discovery. storage_namespace: The storage system this process reaches, recorded in every graph coordinate an S3 table contributes. Defaults to ordinary AWS S3; name an S3-compatible service explicitly, or its @@ -166,12 +163,11 @@ class S3SourceBackend(S3Sessions, ObjectStoreSourceBackend): store offers only ``streamed``, so this exists to assert that. Example: - >>> import kumoai_studio as kumo # doctest: +SKIP - >>> from kumo_s3 import S3SourceBackend # doctest: +SKIP - >>> kumo.set_backend(kumo.LocalBackend( # doctest: +SKIP - ... sources={kumo.DataSourceType.S3: S3SourceBackend()})) - >>> events = kumo.S3Connector( # doctest: +SKIP - ... name='events', root_dir='s3://company-data/events/') + >>> from kumo_core.sources.principals import Principal + >>> from kumoapi.data_source import S3IdentityConfig, S3AmbientAuthentication + >>> principal = Principal('ambient', S3IdentityConfig( + ... authentication=S3AmbientAuthentication()), None) + >>> backend = S3SourceBackend(identity=principal) """ source_type = DataSourceType.S3 @@ -182,7 +178,7 @@ class S3SourceBackend(S3Sessions, ObjectStoreSourceBackend): def __init__( self, - identity: Optional[Principal] = None, + identity: Principal, storage_namespace: Optional[str] = None, mode: Optional[ReadMode] = None, ) -> None: @@ -256,7 +252,7 @@ def _optional(value: Optional[SecretStr]) -> Optional[str]: def _is_ambient(config: Any) -> bool: r"""Whether an identity carries no material of its own, and so resolves - to exactly what an unset identity does. + through the runtime credential chain. """ return isinstance(config, S3IdentityConfig) and isinstance( config.authentication, S3AmbientAuthentication) @@ -268,8 +264,7 @@ def _require_credentials(session: S3Session) -> None: raise TypeError( f"An S3 session must be a 'pyarrow.fs.S3FileSystem' or a " f"'boto3.session.Session'; got {type(session).__name__!r}. " - f"Leaving the identity unset is also supported: the reader then " - f"signs with the ambient AWS credential chain.") + f"Use an ambient principal for the runtime AWS credential chain.") #: STS's answers that mean the material itself is unusable, rather than STS diff --git a/packages/kumo-s3/tests/test_sink_delete.py b/packages/kumo-s3/tests/test_sink_delete.py index cc727db78..34580eff3 100644 --- a/packages/kumo-s3/tests/test_sink_delete.py +++ b/packages/kumo-s3/tests/test_sink_delete.py @@ -5,6 +5,7 @@ from fakes import FakeSession from kumo_s3.sink import S3SinkBackend +from sources.identities import AMBIENT_S3_PRINCIPAL as AMBIENT_PRINCIPAL def test_deleting_an_object_deletes_only_that_key(monkeypatch): @@ -13,7 +14,7 @@ def test_deleting_an_object_deletes_only_that_key(monkeypatch): session.client = lambda service, endpoint_url=None: SimpleNamespace( delete_object=lambda **kwargs: calls.append((service, endpoint_url, kwargs))) - sink = S3SinkBackend() + sink = S3SinkBackend(AMBIENT_PRINCIPAL) monkeypatch.setattr(sink, '_resolved_session', lambda connector, bucket: (session, True, None)) diff --git a/packages/kumo-snowflake/src/kumo_snowflake/session.py b/packages/kumo-snowflake/src/kumo_snowflake/session.py index 359e0d4df..8d29f2089 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/session.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/session.py @@ -23,6 +23,7 @@ from __future__ import annotations +import logging import threading from contextlib import ExitStack, contextmanager from typing import Any, Dict, Iterator, List, Optional, Tuple, TypeAlias, Union @@ -39,7 +40,9 @@ ) from kumoapi.plugin import SourceConnector from pydantic import SecretStr +from snowflake.connector.errors import Error as SnowflakeConnectorError from snowflake.snowpark import Session +from snowflake.snowpark.exceptions import SnowparkClientException #: What this module builds and hands upward. SnowflakeSession: TypeAlias = Session @@ -285,10 +288,24 @@ class SnowflakeConnection: retains only the principal; receiving workers open their own sessions. """ + _logger = logging.getLogger(__name__) + _CLOSE_ERRORS = (SnowparkClientException, SnowflakeConnectorError, + OSError, RuntimeError, AttributeError) + def __init__(self, identity: Principal | None) -> None: self._identity = identity - self._lock = threading.RLock() self._sessions: dict[_TargetKey, Session] = {} + self._lock = threading.RLock() + + def __del__(self) -> None: + """Release owned resources during normal garbage collection, best effort.""" + if not hasattr(self, "_lock"): + return + try: + self.close() + except self._CLOSE_ERRORS as error: + self._logger.error("Snowflake connection cleanup failed (%s).", + type(error).__name__) @property def identity(self) -> Principal | None: @@ -326,7 +343,12 @@ def get(self, connector: SourceConnector | None, *, fresh: bool = False) -> Sess return session if session is not None: del self._sessions[key] - session.close() + try: + session.close() + except self._CLOSE_ERRORS as error: + self._logger.error( + "Could not close stale Snowflake session (%s); reconnecting.", + type(error).__name__) session = _connect(self.identity, connector) self._sessions[key] = session return session diff --git a/packages/kumo-snowflake/src/kumo_snowflake/sink.py b/packages/kumo-snowflake/src/kumo_snowflake/sink.py index 14811b574..78e3841b7 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/sink.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/sink.py @@ -193,7 +193,7 @@ def filesystem(self, connector, path): from kumo_snowflake.stage_fs import stage_filesystem session = self._connection.get(connector) _require_snowpark(session) - return stage_filesystem(session, path) + return stage_filesystem(session, path, owner=self._connection) def __repr__(self) -> str: return f'SnowflakeSinkBackend(connection={self._connection!r})' diff --git a/packages/kumo-snowflake/src/kumo_snowflake/stage_fs.py b/packages/kumo-snowflake/src/kumo_snowflake/stage_fs.py index fe324f89c..53d93fe20 100644 --- a/packages/kumo-snowflake/src/kumo_snowflake/stage_fs.py +++ b/packages/kumo-snowflake/src/kumo_snowflake/stage_fs.py @@ -20,7 +20,7 @@ _stage_join, _StageFiles, ) -from kumo_snowflake.session import SnowflakeSession, _rows +from kumo_snowflake.session import SnowflakeConnection, SnowflakeSession, _rows from kumo_snowflake.staging import ( DOWNLOAD_TIMEOUT, _download_session, @@ -51,7 +51,9 @@ def _remove_pattern(relative: str) -> str: class StageFileSystemHandler(ChunkedFileHandler): part_bytes = 4 << 30 - def __init__(self, session: SnowflakeSession, root: str) -> None: + def __init__(self, session: SnowflakeSession, root: str, *, + owner: Optional[SnowflakeConnection] = None) -> None: + self._owner = owner self._stage = _split_stage_location(root)[0] self._session = session self._files = _StageFiles(session) @@ -226,9 +228,25 @@ def _read(path: Path, offset: int, length: int) -> bytes: return reader.read(length) -def stage_filesystem(session: SnowflakeSession, - location: str) -> Tuple[PyFileSystem, str]: - r"""A filesystem for ``@DB.SCHEMA.STAGE/prefix`` and its normalized path.""" +def stage_filesystem( + session: SnowflakeSession, + location: str, + *, + owner: Optional[SnowflakeConnection] = None, +) -> Tuple[PyFileSystem, str]: + """Build a named-stage filesystem while retaining its connection owner. + + Args: + session: Authenticated Snowpark session used for file operations. + location: Fully qualified named stage and optional path prefix. + owner: Optional connection owner to retain while the filesystem is in use. + + Returns: + The filesystem and normalized stage path. + + Raises: + ValueError: The location is not a supported named-stage path. + """ stage, prefix, _ = _split_stage_location(location) root = f'{stage}/{prefix}' if prefix else stage - return PyFileSystem(StageFileSystemHandler(session, root)), root + return PyFileSystem(StageFileSystemHandler(session, root, owner=owner)), root diff --git a/packages/kumo-snowflake/tests/test_connection.py b/packages/kumo-snowflake/tests/test_connection.py index c23480780..672671cf8 100644 --- a/packages/kumo-snowflake/tests/test_connection.py +++ b/packages/kumo-snowflake/tests/test_connection.py @@ -3,7 +3,10 @@ # SPDX-License-Identifier: Apache-2.0 """Connector-owned Snowpark sessions isolate accounts and worker state.""" +import gc +import logging import pickle +import weakref from concurrent.futures import ThreadPoolExecutor from types import SimpleNamespace from unittest.mock import Mock @@ -175,3 +178,110 @@ def test_table_locations_without_credentials_remain_available( source = SnowflakeSourceBackend(session.SnowflakeConnection(None)) assert source.table_location(connector, "events") == '"DB"."SCHEMA"."events"' + + +@pytest.mark.parametrize("fresh", [False, True]) +def test_failed_stale_session_cleanup_still_reconnects( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, + caplog: pytest.LogCaptureFixture, + fresh: bool, +) -> None: + """Cleanup errors do not prevent replacing an unusable or forced-fresh session.""" + owner = session.SnowflakeConnection(principals[0]) + stale = owner.get(connector) + stale.connection.is_closed = lambda: not fresh + stale.close.side_effect = RuntimeError("sensitive credential detail") + caplog.set_level(logging.ERROR, logger=session.__name__) + + replacement = owner.get(connector, fresh=fresh) + + assert replacement is not stale + assert owner.get(connector) is replacement + stale.close.assert_called_once_with() + assert connect.call_count == 2 + assert "reconnecting" in caplog.text + assert "sensitive credential detail" not in caplog.text + + +def test_reconnection_failure_is_not_hidden_by_cleanup_handling( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, +) -> None: + """Connection creation errors still propagate after stale-session cleanup fails.""" + owner = session.SnowflakeConnection(principals[0]) + stale = owner.get(connector) + stale.connection.is_closed = lambda: True + stale.close.side_effect = RuntimeError("old session cleanup failed") + connect.side_effect = RuntimeError("replacement connection failed") + + with pytest.raises(RuntimeError, match="replacement connection failed"): + owner.get(connector) + + +def test_discarded_owner_closes_its_sessions( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, +) -> None: + """Snowpark's session registry does not keep an otherwise unused owner alive.""" + owner = session.SnowflakeConnection(principals[0]) + live = owner.get(connector) + owner_ref = weakref.ref(owner) + + del owner + gc.collect() + + assert owner_ref() is None + live.close.assert_called_once_with() + assert connect.call_count == 1 + + +def test_stage_filesystem_retains_its_connection_owner( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A borrowed filesystem keeps its owner alive after the connector is discarded.""" + monkeypatch.setattr("kumo_snowflake.sink._require_snowpark", lambda _: None) + monkeypatch.setattr("kumo_snowflake.artifacts._require_snowpark", lambda _: None) + owner = session.SnowflakeConnection(principals[0]) + live = owner.get(connector) + backend = SnowflakeSinkBackend(owner) + filesystem, _ = backend.filesystem(connector, "@DB.SCHEMA.STAGE/root") + owner_ref = weakref.ref(owner) + + del owner, backend + gc.collect() + assert owner_ref() is not None + live.close.assert_not_called() + + del filesystem + gc.collect() + assert owner_ref() is None + live.close.assert_called_once_with() + assert connect.call_count == 1 + + +def test_destructor_logs_cleanup_failure_without_secret_contents( + principals: tuple[Principal, Principal], + connector: SourceConnector, + connect: Mock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Finalization reports failure without leaking credentials or raising.""" + owner = session.SnowflakeConnection(principals[0]) + live = owner.get(connector) + live.close.side_effect = RuntimeError("sensitive credential detail") + caplog.set_level(logging.ERROR, logger=session.__name__) + + del owner + gc.collect() + + live.close.assert_called_once_with() + assert connect.call_count == 1 + assert "Snowflake connection cleanup failed (RuntimeError)" in caplog.text + assert "sensitive credential detail" not in caplog.text diff --git a/scripts/benchmarks/object_store/compare_live.py b/scripts/benchmarks/object_store/compare_live.py index 831f1ffed..dd8796b30 100644 --- a/scripts/benchmarks/object_store/compare_live.py +++ b/scripts/benchmarks/object_store/compare_live.py @@ -293,11 +293,14 @@ def make_reader(provider, manifest, args): from kumo_adls import session, transfer from kumo_adls.backend import ADLSSourceReader from kumo_adls.source_access import source_access + from kumo_core.sources.principals import Principal + from kumoapi.data_source import ADLSAmbientIdentityConfig if transfer.CONNECTIONS != args.worker_count: raise ValueError( 'ADLS transfer ceiling differs from the file-worker ceiling') suffix = manifest.get('endpoint_suffix', 'dfs.core.windows.net') - client = session.session_for(None, manifest['adls_account'], suffix) + principal = Principal('benchmark-adls', ADLSAmbientIdentityConfig(), None) + client = session.session_for(principal, manifest['adls_account'], suffix) access = source_access(client, manifest['adls_account'], suffix) authority = f'{manifest["filesystem"]}@{manifest["adls_account"]}.{suffix}' reader = ADLSSourceReader(access.filesystem, From b66084bb5bf83a88eba370b59835c4108f1d0586 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 21:51:53 +0000 Subject: [PATCH 10/10] Fix API ambient identity test formatting and credential types --- .../test/test_adls_ambient_identity.py | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/kumo-api/test/test_adls_ambient_identity.py b/packages/kumo-api/test/test_adls_ambient_identity.py index cb748b16e..b7b385685 100644 --- a/packages/kumo-api/test/test_adls_ambient_identity.py +++ b/packages/kumo-api/test/test_adls_ambient_identity.py @@ -6,7 +6,7 @@ from dataclasses import asdict import pytest -from pydantic import TypeAdapter, ValidationError +from pydantic import SecretStr, TypeAdapter, ValidationError from kumoapi.data_source import ( ADLSAmbientIdentityConfig, @@ -39,11 +39,11 @@ def test_ambient_config_can_constrain_the_cloud(cloud: AzureCloud) -> None: def test_ambient_config_rejects_unused_stored_credentials() -> None: """An ambient principal cannot silently ignore supplied secret material.""" config = ADLSAmbientIdentityConfig() - credentials = S3AccessKeyCredentials( - access_key_id="unused", secret_access_key="unused" - ) + credentials = S3AccessKeyCredentials(access_key_id=SecretStr("unused"), + secret_access_key=SecretStr("unused")) - with pytest.raises(ValueError, match="config and credential types must match"): + with pytest.raises(ValueError, + match="config and credential types must match"): validate_identity_credentials_match(config, credentials) @@ -55,9 +55,9 @@ def test_hosted_identity_schema_remains_workload_only() -> None: assert set(fields["required"]) == {"tenant_id", "client_id", "cloud"} assert "ADLSAmbientIdentityConfig" not in schema["$defs"] with pytest.raises(ValidationError): - TypeAdapter(CreateIdentityArgs).validate_python( - { - "display_name": "ambient", - "config": asdict(ADLSAmbientIdentityConfig()), - } - ) + TypeAdapter(CreateIdentityArgs).validate_python({ + "display_name": + "ambient", + "config": + asdict(ADLSAmbientIdentityConfig()), + })