Repository navigation
feat(delta): materialize Delta sources through their change data feed - #2166
Conversation
…ndary DeltaSnapshot::changes_since streams the changes of every version after a given one through the snapshot's, from Kernel's change data feed: each row carries the projected columns, then _change_type and _commit_version, in commit order. With a row budget the stream ends at the first commit boundary at or past it and records the last version it read; a commit is never split. A range the feed cannot serve - the feed off at a version inside it, a schema change, a log that no longer reaches its start - is ChangeFeedUnavailable, whether Kernel says so on opening the range or partway through it. The table remembers which, so the next request for that range is refused before any rows are read. The Spark fixture generator gains change_feed (every kind of change, checked against Spark's own feed) and change_feed_late (feed on from version 2).
A Delta source now materializes and tracks like an Iceberg one. The first pass reads each table's latest version whole; later passes read the changes after the watermark from the table's change data feed. A window the feed cannot serve is read whole, with the reason logged. The engine applies a change feed by what each row does. Inserts and update after-images assert; deletes and before-images retract. - Latest-by-key ranks a key's changes by version, an assertion over a retraction within one version, then by order_by. A delete is a tombstone. - Additive mode keeps each triple's latest change, retracts exactly the triples the window's rows retracted, and inserts those they asserted. It inserts rather than upserts, so values other rows and sources hold are left alone. The per-pass row budget cuts a change window at a commit boundary. The stream reports where it stopped, so the engine records the window's end after draining it, and the watermark lands on that version. Delta sources take delete and order_by options, on /delta/map and in DeltaCreateConfig, as Iceberg sources do.
…refusals - Latest-by-key: an update's before-image now retracts the key it held, so an update that changes a row's subject, graph or target ledger removes the old copy. When the key is unchanged, the same-version after-image outranks it. - Additive materialization over a change feed refuses a mapping with blank-node objects before the first load. A delete names triples by value, and the transaction parser refuses a blank-node label, so the first delete or update of such a row failed that pass and every pass after it. - A change feed failure inside a range is remembered for the process instead of on the cached table handle, which expires between passes polled less often than its TTL. It is kept as the span of versions that failed, so a shorter range that ends before the failure is still read from the feed.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz I'm really glad this goes through the change data feed rather than an added-files scan. It's the better mechanism for Delta, and the reader is carefully built: the budget only ever cuts between versions and reports where it stopped, and a failure inside a range is remembered as a span of versions rather than as a flag on a handle that can expire. Two headline notes, both about what a retraction should mean rather than how the code applies it:
(1) A decision above the code, and yours to make: latest-by-key over a change feed reads a key's newest hard delete as deleting the key, whatever revisions of it the table still holds. That's right for a current-state table with one row per key. But the latest-by-key contract these same options carry on the Iceberg page is the append-only revision log (match a ROW_NUMBER() OVER (PARTITION BY id ORDER BY ts DESC) = 1 view; deletes are tombstone rows), and on that shape a retention DELETE of superseded revisions removes entities whose latest revision is still in the table. I reproduced it on the engine; details inline. Which shape should Delta latest-by-key serve, or should a key a hard delete touched be re-read from the table at to? What I'd hold the merge for is only that it doesn't ship silently.
(2) The additive retraction-by-value can't count a triple's supporters, so a triple two rows (or two sources) assert is retracted when one of them goes; I checked it on a subject spread over two rows, and deleting one row took the subject's class with it. The PR documents it, and the structural fix (reference counts, or Delta row tracking) is not for this PR. It does now disagree with the additive section of the Iceberg page ("never removes them … several sources can safely materialize into the same target"), though, so it may be worth deciding whether @type at least keeps its union, insert-only rule here, the way the additive upsert path already treats it.
Claude-assisted review below:
✅ Approving to unblock you — with 1 thing that needs to be addressed before this merges.
This is a big step for Delta sources. The reader is the part I'd point people at: changes_since only cuts when a batch starts a newer version than the last one sent (table.rs:686-701), so an update's before- and after-image can't straddle two passes, and the engine now records each table's window after draining its stream, so a cut lands the watermark on the version it stopped at. The engine side reads well too, and I like that the blank-node refusal happens before the first load instead of at the first delete.
Must address before merge
- Latest-by-key over a change feed: a hard delete of a superseded revision removes a live entity (
r2rml_materialize.rs:2945). Details and three ways out inline; the minimum is that the Delta docs say it plainly.
Should address
MaterializeScan's field docs no longer describe what a Delta change-feed scan returns:incrementalandto_snapshot_idboth changed meaning (r2rml.rs:416, inline).
Optional
- A schema change inside a window is logged as "the log no longer reaches the start of the range" (
error.rs:153, inline), with a question about splitting the window there instead of reading whole. - The pinned-budget rule from #2165 is derived again at the Delta dispatch (
r2rml.rs:2081, inline).
Not in this PR (I checked each mechanism):
- Initial load is not bounded. Agreed it's separable: a Delta file listing carries no per-file version, so bounding it needs a resumable cursor over one pinned version's files, which is new design. One thing I'd add to the docs alongside it, though: the change data feed is off by default on Delta tables, and a table without it is read whole on every poll in which it changed. A large table without the feed can therefore hit
FLUREE_MATERIALIZE_MEMORY_BUDGET_MBor the novelty ceiling on every such poll, and thewarnrepeats each time. Is a per-pollwarnthe posture we want there, or should/iceberg/tracksay so once when it registers a source whose tables have no feed? - No feed means no deletes. Agreed it's separable: it's the same limit Iceberg's whole read has. The schema-change case inline is the one exception I think is cheap to close.
- No bulk build. Separable scope.
CI: this PR's base is fix/pinned-materialize-reads, and ci.yml only runs for pull requests into main, so no fmt, clippy or test job has run on it; the only checks at cae0c1c67 are the Release workflow's. I ran the equivalents locally (below). Once #2165 lands and this retargets to main, CI will run for real.
Adherence to repo commitments:
- Patterns/abstractions: ✔ extends
MaterializeSource/MaterializeScanand the existing per-pass budget rather than adding a Delta-only engine;MaterializeOptionsreplacing the tuple is a nice cleanup.⚠️ the contract docs onMaterializeScan(inline). - Performance (speed first, memory second): ✔ materialization only, nothing in the query engine. The per-row
RowChange::ofand the per-triple keys in additive change-feed mode are batch-load costs, and the accumulator still counts them against the memory budget. No performance-degradation risk to queries. - Deployment targets: ✔ the tracking worker runs in long-lived hosts, and the feed-refusal memory is process-scoped, which the body says. An embedder that doesn't materialize never reaches it.
⚠️ for embedders that callscan_for_materialize_streamdirectly: with a window start, a Delta source now returns a change feed (see theMaterializeScannote), andDeltaGsConfiggains two public fields, so a struct-literal construction downstream needs..Default::default(). - Testing: ✔ reader tests against two Spark fixtures whose feed is checked against an oracle, engine tests on fakes covering ordering, ties, before-images and the cut, and end-to-end tests that release staged commits between polls.
⚠️ none of it has run in CI yet (above). - Conventions: ✔ multi-line commit bodies;
delta.md,endpoints.mdandconfiguration.mdupdated.
Verified locally at cae0c1c67, since CI hasn't run here: cargo fmt --check is clean; clippy -D warnings over fluree-db-delta, fluree-db-api, fluree-db-server and fluree-db-cli with the Delta features is clean; fluree-db-api builds with --no-default-features and with Iceberg but not Delta. Every new test passes by name: the four reader tests, the four engine tests, the three new it_delta_local_fs tests and materialize_options_are_stored_with_the_source. Mutations, each restored: an engine that ignores stopped_at turns a_cut_change_feed_advances_the_watermark_to_where_it_stopped and a_change_feed_backlog_drains_in_bounded_passes red; a feed_refusal that never refuses turns a_failure_inside_a_range_is_remembered_beyond_the_table_handle red; skipping the blank-node refusal turns an_additive_change_feed_refuses_blank_node_objects_before_loading red.
Approving now so you can merge without waiting on another pass from me. Just be sure the latest-by-key delete behavior is either changed or stated plainly in the docs before you do.
| change: change.map(RowChange::order), | ||
| column: order_by.and_then(|col| column_sort_key(batch, col, row)), | ||
| }; | ||
| let is_tombstone = change.is_some_and(|c| !c.asserts) |
There was a problem hiding this comment.
🔴 Must address before merge: in latest-by-key mode, a hard delete of a superseded revision removes the entity, even though its latest revision is still in the table.
Here any retracting change row is a tombstone, and Rank puts the change's version ahead of order_by. So when a key's newest change in the window is a delete, the key resolves to a tombstone and its whole subject is retracted, whatever other rows of that key the table still holds.
That's right for a current-state table with one row per key. But the latest-by-key contract these options carry on the Iceberg page (Change data capture, iceberg.md:651-720) is the append-only revision log: several rows per key, a target that matches a ROW_NUMBER() OVER (PARTITION BY id ORDER BY ts DESC) = 1 view, and "deletes must be expressed as tombstone rows". On that shape the routine retention job (a DELETE that drops superseded revisions) makes every key it touches disappear from the target. I reproduced it with the PR's own engine fakes and order_by: seq:
- two
inserts of key 1 (seq1 and 2), then a window holding only thedeleteof theseq1 row: the target goes from[("1", "a-new")]to empty, withsubjects_retracted: 1. A whole read of the same final table keeps[("1", "a-new")]; - one window holding a new revision of key 1 (
seq2, version 2) and then the prune of the old one (seq1, version 3): the target ends up empty for key 1 as well, because the later version outranksorder_byeven when the newer revision is in the same window.
Iceberg gets this case right today: a window with a delete in it reads the head whole (ScanChoice::FullUnsafeWindow), and the surviving revision wins.
Which fix fits depends on which table shape Delta latest-by-key is meant to serve, and that's your call: (a) exact: re-read each key a hard delete touched from the table at to and keep its winning row; (b) Iceberg's rule: with order_by set, read a window that holds a retraction whole (which would cost current-state tables their delete propagation under order_by, which the latest-by-key arm of a_delta_source_materializes_and_follows_its_change_feed relies on); or (c) state the one-live-row-per-key assumption in delta.md and on the /delta/map order_by row, so the revision-log shape isn't configured onto it. What I'd hold the merge for is that it doesn't ship silently, so (c) at minimum.
| /// then carries [`CHANGE_TYPE_COLUMN`] and [`COMMIT_VERSION_COLUMN`], and | ||
| /// either asserts its values or retracts them. Only a Delta source's change | ||
| /// data feed sets it. | ||
| pub change_feed: bool, |
There was a problem hiding this comment.
🟠 Should address: the MaterializeScan fields above this one no longer describe what a Delta change-feed scan returns.
incremental (r2rml.rs:387) still reads "Whether an added-files scan was used, rather than a full read", but DeltaSource::materialize_scan sets incremental: true for a change-feed window (delta.rs:641), whose rows include deletes and update_preimages. And to_snapshot_id (r2rml.rs:383) is still "the new watermark to persist", but when stopped_at is set, that's the watermark, and to_snapshot_id names a version the pass never reached.
Inside db only the engine reads these, and it reads change_feed and stopped_at correctly. But scan_for_materialize_stream is public, and there's at least one embedder that reads a pinned (from, to] window and, when incremental is true, treats every row as an added row. On a Delta source that consumer would now take a delete for an addition. (It doesn't reach Delta today only because it refuses non-Iceberg configs further up.)
Minimally, the two field docs could say that a change feed also sets incremental and that stopped_at, when set, is the watermark, and point readers at change_feed before they treat rows as additions. Or, since the engine only reports incremental, it could stay false for a change feed so the old meaning still holds for anyone branching on it.
| pub(crate) fn change_range_refusal(error: &delta_kernel::Error) -> Option<String> { | ||
| change_feed_refusal(error).or_else(|| { | ||
| (!kernel_is_access_or_unsupported(error)) | ||
| .then(|| "the log no longer reaches the start of the range".to_string()) |
There was a problem hiding this comment.
🟡 Optional: a schema change inside the window is reported as "the log no longer reaches the start of the range".
In ChangeDataFeed mode, Kernel 0.28 refuses a range whose two ends have different schemas with a plain Error::generic("Failed to build TableChanges: Start and end version schemas are different…") (table_changes/mod.rs, boundary_schema_error), not ChangeDataFeedIncompatibleSchema. So it misses every arm of change_feed_refusal and lands here. I added a column to a copy of the change_feed fixture (a metaData commit at version 6): changes_since(0) comes back as ChangeFeedUnavailable with this reason, so the warn points an operator at log retention when the cause was an ALTER TABLE. Matching that message, or comparing the two ends' schemas ourselves before opening, would give the right reason.
A related question: an ADD COLUMN is probably the most common way a feed-enabled table loses a window, and the whole-read fallback then drops that window's deletes. #2162 suggested splitting the window at the change, and stopped_at already lets a pass end early. On that same staged table, changes_since(5) (the range starting at the change) opens fine. So a pass could read the feed up to the version before the change and let the next pass start there, losing nothing. Is that worth folding in here, or would you rather leave it to the doc's warning?
| ) -> QueryResult<MaterializeScan> { | ||
| #[cfg(feature = "delta")] | ||
| if let Some(delta) = self.delta_source(graph_source_id).await? { | ||
| let budget_rows = if to_snapshot_id.is_some() { |
There was a problem hiding this comment.
🟡 Optional / nit: this is the same "a pin is never budgeted" rule #2165 put at r2rml.rs:2102, derived a second time for the Delta branch. Hoisting let pinned = to_snapshot_id.is_some(); and let budget_rows = if pinned { 0 } else { self.pass_row_budget() }; above the Delta dispatch, and handing budget_rows to both branches, would keep the two from drifting apart, which is the shape #2160 was. Minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
…l-materialize # Conflicts: # docs/operations/configuration.md
…table Latest-by-key over a Delta change feed took a key's latest change as its fate, and a delete or an update's before-image outranks any row an earlier version wrote. So a delete of a superseded revision retracted the whole subject, even though the table still held the key's latest revision: the retention prune of a revision log emptied every key it touched, and a new revision with the prune of the old one in one window did the same. A change feed retraction removes a row, not necessarily its key. Each key one wins is now read back from the table as of the version the pass ends on, through an `In` filter on the subject template's key columns. The key's winning remaining row replaces the subject, by `order_by` as usual, and a key with no row left is retracted, as before. A one-row-per-key table therefore keeps its delete propagation, and a revision log keeps its latest revisions. MaterializeSource gains rows_at, which the provider answers through a new public FlureeR2rmlProvider::rows_at_version over a Delta version.
MaterializeScan's incremental still read as "an added-files scan", whose rows are all additions, and to_snapshot_id as the watermark to persist. A Delta change feed also sets incremental, its rows can retract, and when stopped_at is set it, not to_snapshot_id, is the watermark. The two fields now say so, and point a caller at change_feed before it treats every row as an addition.
…urce The rule that a pinned read is never cut by the row budget was derived twice, once for the Delta dispatch and once for Iceberg, which is the shape #2160 had. It is now derived once, above the dispatch, and both sources take the same budget.
Kernel refuses a change data feed range whose two ends have different schemas with a plain message, not ChangeDataFeedIncompatibleSchema, so the refusal fell through to "the log no longer reaches the start of the range". The warn then pointed an operator at log retention when the cause was an ALTER TABLE. The message is now matched and named as a schema change.
…letes The Delta guide now says the change data feed is off by default, and that without it every pass after a change reads a table whole, which on a large table can reach the memory budget or the novelty ceiling on every such pass. The Iceberg guide's additive section promised that materialization never removes triples, so several sources can share a target; a Delta change feed in additive mode removes a deleted row's triples, including ones another source asserts, and the section now says so.
|
@aaj3f on (1): latest-by-key now serves both shapes. A key whose latest change is a retraction is read back from the table as of the version the pass ends on, and its latest remaining row wins, so a pruned revision log keeps its keys and a one-row-per-key table keeps its deletes (47c7dff). On (2): kept as is, with the Iceberg additive section now stating the Delta exception (2d88888); I left |
Brings #2142, #2144, #2154, #2155, #2156, #2158, #2159, #2165, #2166 and #2167 into next. Where main's RDF lists (#2159) meet next's RDF 1.2 links: - The list view walks an EdgeAnnotation's body; next has no AnnotationTarget. - Export marks annotated edges skipping list rows, and writes an rdf:reifies row as next's @reifies block through main's JsonLdNode, untranslated rows included. - The JSON-LD and import readers keep next's graph argument and triple-term spool records beside main's gap-free list positions and list chunking. - One collection writer: main's shared module, which both JSON-LD and Turtle use, replaces next's Turtle-only one, and now also keeps the labels of blank nodes inside triple terms, of reifiers, and of blank graph names. A reified cell keeps its triples while the well-formed tail after it folds, as JSON-LD's list conversion does; next's writer test now says so. - Hiding list members also turns off next's wildcard lane, which reads leaflets directly, and next's independent-scan count builds its right scan with the same hiding. Elsewhere: - List-predicate discovery opens a leaf ranged unless the store cannot read ranges, which next fetches whole. - GC reports main's walk stop reason without next's removed artifact cache directory. - Tests from main await next's async genesis_ledger, reload with without_storage_lock, and build stores without a cache directory.
Fixes #2162.
Fixes #2161.
Builds on #2165, which pins Delta tables and reads a version whole. This PR adds the rest: Delta sources materialize and track like Iceberg ones, reading only what changed through the table's change data feed.
Reading the change data feed
DeltaSnapshot::changes_since(after, projection, row_budget)wraps Kernel'sTableChanges.afterthrough the snapshot's version, in commit order._change_typeand_commit_version.A range the feed cannot serve is
ChangeFeedUnavailable. That covers a feed turned off at a version inside the range, a schema change, and a log that no longer reaches the range's start. Kernel reports a schema change only as a message, which is matched so thewarnnames it.Kernel checks only the two ends of a range when it opens it. A version in between that turns the feed off, or whose change file is gone, fails partway through the stream. That failure is remembered as the span of versions that failed, and a later range covering the span is refused before any rows are read. A shorter range that ends before it is still read from the feed. The memory lasts for the process rather than living on the cached table handle, which can expire between passes.
How a pass applies changes
warn. A watermark equal to the head is an empty window, so an idle table commits nothing.order_bythen ranks rows within a version. A delete is a tombstone, and so is an update's before-image at the key it held. An update that moves a row to another subject, graph or target ledger therefore removes the old copy. One that keeps the key is outranked by its after-image.MaterializeSource::rows_at, answered by the publicFlureeR2rmlProvider::rows_at_version), through anInfilter on the subject template's key columns. The key's latest remaining row, byorder_by, wins; a key with no row left is retracted.Configuration
/delta/mapandDeltaCreateConfigtakedelete_column/delete_valuesandorder_by, as Iceberg sources do.materialize_optionsreads these options for a Delta source. That was the only Iceberg-only gate on the tracking path./iceberg/materializeand/iceberg/trackalready served any source id.Not in this PR
fluree materialize, the bulk twin builder, still reads Iceberg sources only.Tests
Reader (
fluree-db-delta/tests/reader.rs), against two new Spark fixtures:change_feedholds an update, a delete, an append, a MERGE that updates, inserts and deletes in one commit, and a deleted key inserted again. The generator checks Spark's own feed against changes stated from its inputs.change_feed_lateturns its feed on at version 2.Engine (
r2rml_materializeengine tests), each with a fake change-feed source:order_by;End to end (
it_delta_local_fs), with each fixture staged and its later commits released between polls:Route: the
/delta/mapoptions round-trip into the stored config, and a delete column with no values is refused.Follow-up: #2175
Follow-up: #2176
Follow-up: #2177