Repository navigation
feat(delta): Databricks tables by name through Unity Catalog - #1901
Conversation
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this all looks good and holds up under my review. The only headline note I'll make (besides full review below) is that, although it's possibly beyond the scope of this PR, I still think we'd have issues for Databricks + GCP, which I believe is a fairly common pattern. store:open doesn't support the gs:// protocol that would very likely be used. I'm partially only elevating this because it was on my mind with one of our prospective clients as they were very explicitly asking about "vended Iceberg within GCP" and may very well have been referring to this exact scenario.
This is really nice — it turns the old "export three AWS variables and remap within the hour" workaround into a standing Databricks source, and it does it at the right altitude: a Unity client for placement and vending, credentials renewed inside the object store so the handle and its caches survive rotation, and everything underneath (auth providers, the SSRF-hardened client, secret handling, the env-var allowlist) shared with the Iceberg catalog rather than copied. Building a separate Unity client instead of forcing it through SendCatalogClient seems right to me, since that trait and VendedCredentials are Iceberg-REST- and S3-shaped and this needs Azure SAS too. I checked the mocks against Databricks' REST reference (temporary-table-credentials request/response fields and expiration_time in epoch ms; tables/{full_name} placement, row_filter and columns[].mask) and they match. Nothing blocking; the notes above are the refresh margin's behaviour when Unity misbehaves inside it, a Unity refusal surfacing as 400 InvalidQuery rather than a typed 403 like Iceberg's, and two docs/help nits.
Adherence to repo commitments:
- Patterns/abstractions: ✔ extends
DeltaGsConfig/store::open/the shared handle cache and reuses the Iceberg crate'sAuthConfig,netandConfigValue; the newUnityClientand credential cache are justified by Iceberg's catalog/credential types being Iceberg-REST- and AWS-only. - Performance (speed first, memory second): ✔ no engine or hot-path change; one uncontended async lock +
Arcclone per object-store request on Unity tables, path tables unchanged — no performance-degradation risk. - Testing: ✔ wiremock suite faithful to Unity's documented shapes, a real-signature stamp through the S3 store, route/config/cache-key/CLI tests; CI ran
nextest --workspace --all-featureson69e3ad8ae(13133 passed, all new tests by name); renewal and refusal-extraction mutation-checked. Azure is unit-only, as the body says. - Conventions: ✔ thorough multi-line bodies, clippy/fmt green, docs updated (Delta page, platform guide, CLI and endpoint references);
⚠️ delta map --helpstill describes path-only placement.
Verified locally at branch HEAD: cargo nextest run -p fluree-db-delta -p fluree-db-r2rml (202 passed, in the #1902 worktree whose renewal/refusal code is byte-identical), two mutations each caught by the tests named above; CI test/clippy/fmt green on 69e3ad8ae.
Approving so you can merge when ready, but maybe worth considering the margin fallback and the 403 mapping first.
| .unity | ||
| .read_credentials(&self.table) | ||
| .await | ||
| .map_err(refused)?; |
There was a problem hiding this comment.
Optional (robustness) — The five-minute refresh margin turns into a hard edge when Unity misbehaves inside it.
Inside the margin usable() (:288-290) is false, so every get_credential goes to read_credentials while holding the mutex. If that call errors — a 429, a 5xx, or a hang up to REQUEST_TIMEOUT (60 s) — .map_err(refused)? fails the S3 request even though held is still valid for up to five more minutes, and every concurrent read queues behind the same timeout. Separately, the body notes Unity "hands back a set it already issued, with its remaining life"; if it ever answers an in-margin request by re-serving a set that is itself inside the margin, usable() stays false and each subsequent S3 request re-asks Unity serially until the set actually expires (credentials_are_kept_until_they_near_expiry pins "inside the refresh margin, every request asks again", so that's the designed behaviour today).
Concretely: a scan that happens to run in minute 56 of a set's life during a brief Unity blip fails outright, where it would have finished on the credentials it already had.
Maybe fall back to the held set while it is still genuinely valid:
None => match self.unity.read_credentials(&self.table).await {
Ok(fresh) => {
tracing::info!(/* as now */);
*held = Some(fresh.clone());
fresh
}
// Only inside the margin, not expired: keep reading with what we hold.
Err(e) => match held.as_ref().filter(|v| SystemTime::now() < v.expires) {
Some(still) => {
tracing::warn!(table = %self.table.full_name, error = %e, "Unity Catalog did not renew table credentials; using the held set");
still.clone()
}
None => return Err(refused(e)),
},
},For the re-served case, a fresh set that is already inside the margin could be treated as usable until expires minus a small skew rather than re-asked on every request. This is minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in 65f3b6f. The re-served in-margin case is left as designed: with the fallback, it now costs extra Unity requests rather than failed reads.
| @@ -376,11 +480,15 @@ impl DeltaSource { | |||
| .snapshot(version_selector(table_name, pin)?) | |||
| .await | |||
| .map_err(|e| self.query_error(table_name, e))?; | |||
There was a problem hiding this comment.
fluree-db-api/src/graph_source/delta.rs:637
Optional (error mapping) — A Unity refusal at query time reaches the client as 400 err:db/InvalidQuery.
DeltaError::Catalog is new and typed, and catalog_refusal goes to real trouble to dig it back out of Kernel — but delta_query_error's catch-all (delta.rs:637) flattens it into QueryError::Internal, and the server maps that through the generic ApiError::Query(_) arm to BAD_REQUEST / errors::INVALID_QUERY (fluree-db-server/src/error.rs:166, :320). So "User does not have SELECT on Table 'main.sales.orders'. (403 Forbidden)" tells the client its query is invalid. Iceberg's equivalent refusals are 403 with distinct @types (err:storage/AccessDenied, err:catalog/CredentialsNotVended) precisely so Solo's UI can branch on them without matching prose.
Path-based Delta has the same 400 shape for an S3 403 — that's #1899's, not this PR's — but here the status is already in hand in UnityClient::send (unity.rs:235, :256) and gets folded into the message string.
Minimally we could carry Unity's status on the variant (Catalog { table, message, status: Option<u16> }) and have delta_query_error lift 401/403 to a 403-class QueryError. The one real decision is which @type that wears — CatalogCredentialsNotVended's Display text is Iceberg-specific ("…or set vended_credentials=false"), so it probably wants its own code — and if you'd rather that naming go through its own PR, that's the one case where a follow-up makes sense. Otherwise I'd rather see it land here while the catalog error is fresh.
Commenting here because fluree-db-api/src/graph_source/delta.rs:637 is not in this diff.
| /// in Unity Catalog (catalog.schema.table), which says where each lives | ||
| /// and issues the credentials that read it. Excludes --root | ||
| #[arg(long, value_name = "URL", conflicts_with = "root")] | ||
| pub unity_uri: Option<String>, |
There was a problem hiding this comment.
fluree-db-cli/src/cli.rs:3183
Optional (docs nit) — fluree delta map --help still describes path-only placement.
fluree delta map --help still opens with "Tables are named by path. Each rr:tableName in the mapping resolves to its --table entry, else to a directory under --root…" (cli.rs:3183-3192), and both examples are path-based, so the help for the command this PR extends never mentions Unity.
Something like "Tables are named by path (--root, --table) or, with --unity-uri, by their Unity Catalog name (catalog.schema.table)" plus the --unity-uri … --oauth2-client-secret-env … example from the PR body would do it. Minor — if you agree, I'd rather see it in this PR than lost in the backlog.
Commenting here because fluree-db-cli/src/cli.rs:3183 is not in this diff.
| `--table raw.events=s3://lake/raw/events` is read by path, with the | ||
| process's own credentials. | ||
|
|
||
| Only Delta tables with files of their own are read. A view, a table in another |
There was a problem hiding this comment.
Optional (docs + message) — Databricks on Google Cloud (gs://) is refused, and neither the docs nor the refusal message say why.
This is more of a question than a suggestion. Databricks on Google Cloud places Unity tables at gs://…. As far as I can trace, store::open refuses that at validate_location with "unsupported Delta table location 'gs://…': expected s3://, abfss://, file:// or an absolute path" (fluree-db-delta/src/config.rs:305-307), which is a DeltaError::Config, so create_delta_graph_source fails the whole delta map (delta.rs:349).
Refusing is right — the question is just whether we want the docs to say GCP workspaces aren't covered by this route (the platform table and the Unity section currently read as cloud-agnostic apart from the region note), and the message to name the actual reason for a catalog-placed table (something like "Unity Catalog placed this table on Google Cloud Storage, which the Delta reader does not read") rather than suggest file://, which store::open refuses for catalog placements anyway. Small either way — if you agree, I'd rather see it folded in now.
| //! | ||
| //! Unity issues credentials per table, scoped to that table's path and valid | ||
| //! for about an hour. They are handed to the object store as a | ||
| //! [`CredentialProvider`], which the store asks on every request — so a |
There was a problem hiding this comment.
Praise — Renewing credentials inside the object store is the right altitude.
Renewing credentials inside the object store through a CredentialProvider, instead of rebuilding the store per credential set, is the right altitude: the handle and #1899's log/footer caches outlive any one set, and the single-flight mutex means eight concurrent reads cost one vend. And s3_requests_are_signed_with_the_issued_credentials reading Credential=KEY1/ then KEY2/ off the requests the S3 store actually sent is exactly the stamp this needed.
I dropped REFRESH_MARGIN from usable(); that test and credentials_are_kept_until_they_near_expiry both go red.
| // The endpoint override reaches an outbound HTTP client. | ||
| super::iceberg_ssrf::guard_connection_urls(None, None, req.s3_endpoint.as_deref())?; | ||
| // Each of these reaches an outbound HTTP client. | ||
| super::iceberg_ssrf::guard_connection_urls( |
There was a problem hiding this comment.
Praise — Catalog auth is shared with the Iceberg catalog rather than copied.
Reusing the Iceberg catalog's auth providers, hardened client, secret handling and the FLUREE_GRAPH_SOURCE_SECRET_ENV_VARS check (rather than a Unity-flavoured copy) means catalog auth behaves identically on both source types, and guarding unity_uri / oauth2_token_url at the route and again in UnityConfig::validate covers records that arrive by paths other than HTTP.
Refusing a catalog-placed local path before the local-root allowlist is even consulted (store.rs:44-50) is a nice touch.
| /// A catalog's refusal reaches Kernel through the object store that asked it | ||
| /// for credentials, and says more than the layers it came through. Kernel | ||
| /// holds the store's error without naming it as its source, so it is matched. | ||
| fn catalog_refusal(error: &delta_kernel::Error) -> Option<DeltaError> { |
There was a problem hiding this comment.
Praise — The catalog's refusal is pulled back out of Kernel's error.
Pulling the catalog's refusal back out of Kernel's ObjectStore error so the user reads Unity's words instead of "Error interacting with object store: Generic UnityCatalog error" is the kind of thing that saves a support thread.
Mutating the extraction off turns a_refusal_met_while_reading_is_reported_as_the_catalogs red.
69e3ad8 to
74958ac
Compare
…that read it A Databricks managed table lives at a path Unity Catalog owns, readable only with credentials Unity issues: per table, scoped to that table's path, valid for an hour. One ambient credential per process cannot serve two such tables, or one for longer than that. `DeltaTable::open_in_unity` asks Unity where a `catalog.schema.table` lives and opens a store whose credentials come from a provider that asks Unity for them, keeps them until five minutes before they expire, and shares one refresh among concurrent requests. The object store consults the provider on every request, so the store — and the table handle's log and footer caches with it — outlives any one set of credentials. AWS keys and Azure SAS tokens are handled; anything else is refused. What the catalog says is not taken on trust: only a Delta table with a storage location is placed (a view or another format is refused by name), and a location on the local filesystem is refused whatever the local-root allowlist permits. Catalog auth, the SSRF-hardened client and secret handling are the Iceberg REST catalog's. `DeltaGsConfig` gains a `unity` block (workspace URI, auth, optional default catalog and schema) and `placement`: a table with a `tables` entry is read by path as before, any other through Unity. Nothing above the crate uses it yet.
Registration and query-time resolution go through `DeltaGsConfig::placement`: a table with a `tables` entry is opened by path as before, any other through the source's Unity Catalog. `DeltaCreateConfig` carries the catalog (`in_unity`), and a catalog secret that cannot be resolved is a registration error like the Azure one. The shared table handle is keyed on the catalog block as stored, so two sources naming one table with different catalog credentials get a handle each — the credentials are what reads it — while a rotated secret behind a reference or variable does not re-key it. The cache's TTL is what re-resolves a table dropped and recreated elsewhere. A catalog table's snapshot watermark names the location Unity gave; a path-placed table's is unchanged. Also restores the build of the crates above `fluree-db-delta`, which the previous commit's new `DeltaGsConfig` field broke.
`fluree delta map --unity-uri <workspace>` (request field `unity_uri`) names tables as Databricks does, `catalog.schema.table`; `--unity-catalog` and `--unity-schema` complete shorter names, and a `--table` entry is still read by path, so one source can mix the two. `--root` and `--unity-uri` exclude each other. Catalog auth takes the options `iceberg map` has: a service principal (`--oauth2-client-id` with `--oauth2-client-secret[-env]`), whose token is renewed, or a token (`--auth-bearer[-env]`). The token URL and scope default to the workspace's own endpoint and `all-apis`, so a service principal needs only its workspace, id and secret. Over HTTP a secret named by variable is held to `FLUREE_GRAPH_SOURCE_SECRET_ENV_VARS` exactly as on `iceberg/map` — the two routes share the check — and the workspace and token URLs are guarded against internal hosts, at the route and again when the config is validated. The platform guide now leads its Databricks section with this route: managed and external Delta tables by name, any number per source, credentials renewed. The Delta page gains a Unity Catalog section; catalog browsing and mapping generation are listed as not available.
One line per request to Unity — the table, whether it renews a held set, and how long the new one is valid — so an operator can see renewal happen and how much of the hour Unity actually grants. The Delta page now says what bounds a table handle's life: the catalog-client TTL (15 minutes by default), which rebuilds the handle so a rotated secret takes effect, and with it the remembered log state and a Unity name's placement.
…refused over HTTP Through the real route: a workspace or token URL aimed at an internal host, a secret in a variable the operator did not list, a catalog beside a root, and a catalog with no way to authenticate — each a 4xx that registers nothing.
…ng ledger The query routes and `/info` try a name as a ledger first and as a graph source second. The ledger loader reported its miss — an ERROR "ledger not found" line, and on `/info` an `error:NotFound` span code — before the second step had been tried, so every successful graph-source query, on every source type, read as a failure in logs and traces. The loader now has a form that returns a clean not-found unreported, used by the four callers that fall back; each reports it only once the name has turned out to be neither. A name that is nothing is reported exactly as before, and a load failure that is not a not-found is untouched. The test captures ERROR events and span error codes through all four routes, in its own process as the other instrumentation tests are. Reverting any one caller, or dropping any one caller's report, fails it on that route.
…n plain words
Unity Catalog enforces row filters and column masks only in its own compute,
and issues no credentials to read such a table's files — not even to the
table's owner — so the rules cannot be bypassed from here. But its refusal
("… not supported on assigned clusters", 400) surfaced as a generic
object-store error at the first read. The table record already says whether a
table carries either rule; the table is now refused by name when it is placed,
saying which rule it has and why that stops the read.
Checked against a live workspace: both kinds are refused for the owner and for
a service principal alike, and an ordinary table — whose record carries the
same fields as nulls — still reads.
…response `ApiError` has two forms for a ledger that does not exist — `NotFound`, and the ledger loader's own `Ledger(LedgerError::NotFound)` — and `is_not_found()` names both. The API crate's status mapping answers 404 for either, but the server consults its own table, which knew only the first: the second fell through to 500 `err:system/InternalError`. SPARQL with a dataset clause on a name that does not exist returns the loader's error unconverted, so it answered 500 where every other query route answered 404. The server's status and `@type` tables now ask `is_not_found()`, so any route that returns the loader's error is covered rather than this one alone.
…ision The previous commit refused a table with a row filter or column mask when it was placed, because Unity Catalog issues no credentials for one. That wrote Unity's present policy into the reader: were Unity to start issuing them — to a principal a filter does not apply to, say — the reader would go on refusing a table it could read. The table is now placed like any other and Unity is asked. Only if it refuses does the rule the table carries explain the refusal, ahead of Unity's own words (which are about cluster modes). A test serves both outcomes for both rules. A catalog's refusal reaches the reader through the object store that asked for credentials and then through Kernel, which holds the store's error without naming it as a source; it arrived as "Delta table …: Error interacting with object store: Generic UnityCatalog error: …". It is now reported as the catalog error it is — for this refusal and any other met while reading, a missing privilege included.
74958ac to
206d9bf
Compare
# Conflicts: # fluree-db-delta/src/error.rs
Credentials are renewed from five minutes before they expire. If that renewal failed (a 429, a 5xx, a timeout), the S3 or Azure request failed, even though the held set was still valid. A scan that ran into a brief Unity blip inside that window failed outright. The held set is now used until it actually expires, with a warning logged; only with nothing valid held is the renewal failure the request's. The test fails with the fallback removed.
…ssDenied
A Unity refusal at query time ("User does not have SELECT on Table …")
was flattened into QueryError::Internal and reached the client as
400 err:db/InvalidQuery. DeltaError::Catalog now carries whether Unity
answered 401/403 (`denied`). delta_query_error maps a denial to the new
QueryError::CatalogAccessDenied, which the API and server serve as 403
with its own @type, err:catalog/AccessDenied, alongside Iceberg's
err:storage/AccessDenied and err:catalog/CredentialsNotVended. The
governed-table refusal keeps the status of the answer it rewords. Other
catalog failures keep their old mapping.
Tests at each layer; each fails with its part reverted.
…acements - `fluree delta map --help` described path-only placement. It now covers --unity-uri and Unity Catalog table names, with an example. - A table Unity Catalog places on Google Cloud Storage (Databricks on GCP) was refused with the path-source message suggesting file://. It now says Unity placed the table on GCS, which the reader does not read yet. The platform guide says the same. Follow-up: #1914
Stacked on #1899 (→ #1897 → #1896); re-target as those merge.
What
Databricks tables as Delta graph sources by name, read with credentials Unity Catalog issues and renews.
Why
#1899 reads every table Databricks writes, but only by path with the process's own storage credentials. A Databricks managed table — the default kind — lives at a path Unity Catalog owns and is readable only with credentials Unity issues: per table, scoped to that table's path, short-lived. One ambient credential per process cannot serve two such tables, or one for long. Unity's Iceberg REST endpoint is no substitute: it serves only tables with UniForm switched on, which the common form of cannot be combined with deletion vectors (Databricks' default).
How
fluree-db-delta/src/unity.rs).object_store's S3 and Azure builders accept aCredentialProviderconsulted on every request. One provider per table asks Unity for credentials, keeps them until five minutes before they expire, and shares one refresh among concurrent requests. The store — and the table handle's log and footer caches with it — therefore outlives any one set. AWS keys and Azure SAS tokens are handled; anything else is refused.FLUREE_ICEBERG_LOCAL_ROOTSallows. The workspace and token URLs go through the SSRF guard at the route and again at config validation.FLUREE_GRAPH_SOURCE_SECRET_ENV_VARS(the two routes now share that check).DeltaGsConfiggains aunityblock (workspace URI, auth, optional default catalog and schema) andplacement(): a table with atablesentry is read by path exactly as before, any other through Unity;rootandunityexclude each other. The token URL and scope default to the workspace's own endpoint andall-apis, so a service principal needs only its workspace, id and secret.fluree delta map --unity-uri …with the auth flagsiceberg maphas; the same fields onPOST /delta/map. Oneinfoline per credential issue (table, whether it renews, validity).Shared fixes carried here
Neither is Delta-specific; either can be split out against
mainif preferred.fix(server): a query that names a graph source no longer logs a missing ledger— the query routes and/infotry a name as a ledger first and as a graph source second, and the ledger loader reported its miss (anERROR ledger not foundline; on/infoanerror:NotFoundspan code) before the second step ran. Every successful graph-source query, on every source type, therefore read as a failure in logs and traces — which is what made the renewal run above hard to read. The four callers that fall back now get a clean not-found unreported and report it only when the name is nothing at all; a genuinely missing name is reported exactly as before. The test captures ERROR events and span codes through all four routes in its own process; eight mutations — each caller reverted, each caller's report dropped — are each caught on their own route.fix(server): a missing ledger is a 404 however the error reaches the response—ApiErrorhas two forms for a ledger that does not exist,NotFoundand the loader's ownLedger(LedgerError::NotFound);is_not_found()names both and the API crate maps both to 404, but the server's own status and@typetables knew only the first, so the second fell through to 500err:system/InternalError. SPARQL with a dataset clause returns the loader's error unconverted, soFROM <missing>answered 500 where every other query route answered 404. Both tables now askis_not_found(), which covers any route that returns the loader's error. Pinned over HTTP (status and@type), each table mutation-checked; every server test group passes.Seen while probing and left alone, identical on the base: the query routes never stamp
error:NotFoundon the request span (they hand the loader an inner span with noerror_codefield); only/infodoes.Verified
unity.rsagainst a mock catalog: placement; refusal of a view, a non-Delta format and a missing location; Unity's own message reaching the error for a missing table and a missing privilege; a rejected catalog token refreshed once; credentials reused until the margin and replaced inside it; eight concurrent requests sharing one refresh; SAS decoding; Azure credentials not passing for AWS; credentials for an unsupported store; a catalog-supplied local path.rootxorunity, stored shape, the handle-cache key, the all-or-nothing Unity fields and their defaults, the env allowlist on the Delta route, clap conflicts; over HTTP, five unhonourable requests each return 4xx and register nothing.tests/unity_live.rs(ignored, env-driven) repeats the crate-level read against any workspace.renewed=true— and answered that query and every later one correctly, the handle and its caches kept throughout. A second server on the default 15-minute handle lifetime rebuilt its handle, and fetched credentials afresh, every 15 minutes; its answers were equally correct.Not verified / not built
fluree-db-deltacan mock Unity; API-level coverage is the cache key, the stored shape and the live runs.--s3-region/AWS_REGIONis required on AWS and a wrong one surfaces as S3's redirect error (documented).Note for reviewers
The shared table-handle cache uses the Iceberg REST client TTL (
FLUREE_ICEBERG_REST_CLIENT_TTL_SECS, 15 minutes). By default a handle — with #1899's remembered log state, and here a Unity name's placement and credentials — is rebuilt that often, so in-store renewal matters for a longer TTL or a scan that outlasts a credential set. The Delta page now says so. Whether Delta handles deserve their own, longer setting is left open.