Skip to content

feat: materialize Iceberg/R2RML graph sources into native ledgers + tracking worker - #1422

Merged
bplatz merged 30 commits into
fluree:mainfrom
christophediprima:feature/iceberg-materialize
Aug 7, 2026
Merged

bplatz merged 30 commits into
fluree:mainfrom
christophediprima:feature/iceberg-materialize

Conversation

@christophediprima

Copy link
Copy Markdown
Contributor

Summary

Adds the ability to materialize an Iceberg / R2RML graph source into a native Fluree ledger and
keep it fresh with a background tracking worker. Querying a graph source directly re-reads and
re-joins the raw Iceberg rows on every request; materializing into a native ledger gives deduped,
indexed, time-travelable state that queries at native speed and refreshes incrementally.

Five commits:

  1. Append-only incremental scan + snapshot-window helpers (fluree-db-iceberg).
  2. R2RML incremental scan + snapshot helpers (fluree-db-api).
  3. Materialize into native ledgers + tracking worker + endpoints (fluree-db-api, fluree-db-server).
  4. Tombstone deletion + latest-by-key dedup for materialization.
  5. Refreshable Google metadata-server catalog auth — so long-running tracking against a Google
    Iceberg REST catalog keeps authenticating past the ~1h a static bearer lasts.

Builds on the existing Iceberg graph-source support on main.

Motivation

A graph source exposes an Iceberg table as read-on-query triples. That's ideal for ad-hoc access,
but not for a dataset you query repeatedly:

  • No dedup. Iceberg tables written by streaming/CDC pipelines are append-only — many row
    versions per entity. A graph source surfaces all of them; there's no "current state" of a subject.
  • Re-read + re-join every query. Multi-pattern queries (?s a X ; p1 ?a ; p2 ?b …) join the raw
    append-only rows on each request, which blows up combinatorially and re-does the scan every time.
  • No native indexes / time travel over the sourced data.

Materializing solves all three: collapse the append-only rows to one node per subject (upsert),
write them into a native ledger (native indexes, SPARQL, history), and refresh incrementally off
the source's snapshot log. The tracking worker automates the refresh.

Changes

  • fluree-db-iceberg — incremental scan + snapshot windows (scan/planner.rs,
    scan/send_planner.rs, metadata/table.rs, config.rs): plan a scan over only the data files
    added between two snapshots (append-only incremental), plus helpers to resolve the current
    snapshot and the delta from a watermark. Falls back to a full scan when an incremental window
    isn't safe (e.g. a non-append snapshot). + unit tests.

  • fluree-db-api — R2RML materialization (graph_source/r2rml_materialize.rs): read
    graph-source rows (full or incremental) and materialize them into a native ledger.
    Latest-by-key dedup collapses append-only rows to one node per subject (upsert); whole-subject
    tombstone retraction
    removes a subject when its key disappears from the source. A per-(source, table) watermark node (urn:fluree:materialize-state:{source}:{table}, source : escaped so
    the encoding is injective) persists the last-materialized snapshot id in the target ledger, so a
    refresh resumes incrementally; force_full ignores it. + unit tests (watermark encoding/injectivity,
    latest-by-key, retract shape).

  • fluree-db-api — tracking worker (materialize_worker.rs): a per-job worker
    (TrackedJob { source, target, interval, next_due }) driven by a base-granularity ticker; each job
    re-syncs on its own poll interval. Public API: MaterializeTrackingWorker,
    MaterializeWorkerConfig / Handle / Stats. + unit tests (due-job selection + rescheduling).

  • fluree-db-server — endpoints (routes/iceberg.rs, routes/mod.rs, state.rs): the four
    endpoints below. /track runs an immediate first sync on registration so the target is
    populated without waiting a cycle; /tracking is an admin-protected read of this node's worker
    state. Peer nodes forward writes to the write node, consistent with the existing iceberg routes.

  • fluree-db-iceberg — refreshable catalog auth (auth/google_metadata.rs, auth/token.rs,
    auth/mod.rs): a google_metadata AuthConfig variant that mints and auto-refreshes catalog
    OAuth tokens from the GCE/GKE metadata server (Workload Identity). A CachedToken helper is
    extracted from the existing OAuth2 provider and shared, so the new provider is the same small shape
    as oauth2.rs (lean reqwest client + cache, no new dependencies). Exposed via
    auth_google_metadata on the map endpoint. + unit tests (wiremock: Metadata-Flavor header,
    scopes, caching, failure surfacing).

  • fluree-db-api (graph_source/r2rml.rs): incremental-scan wiring on FlureeR2rmlProvider —
    prepare_iceberg_scan (shared REST/Direct storage + table-metadata setup over S3IcebergStorage),
    read_scan_tasks, current_snapshot_id, and scan_table_incremental.

  • docs: materialize / track / untrack / tracking in docs/api/endpoints.md; a materialization +
    tracking section (incl. append-only dedup and the watermark) in docs/graph-sources/iceberg.md; the
    auth_google_metadata option.

New endpoints

Endpoint Method Body Purpose
/iceberg/materialize POST {source, target, force_full?} One-shot: read the source and upsert it into target. Returns {from_snapshot_id, to_snapshot_id, incremental, committed, rows_read, subjects_upserted, subjects_retracted}.
/iceberg/track POST {source, target, poll_interval_secs?} Register a source → target job, run an immediate first sync, then keep target fresh on the interval (default 30s). Returns the effective interval + the first-sync result.
/iceberg/untrack POST {source, target} Stop tracking (leaves already-materialized data in place).
/iceberg/tracking GET — Worker status for this node (admin-protected read).

Auth

The tracking worker holds a job open for hours, so catalog auth has to survive token expiry. For a
workload running as a GCP service account (GKE Workload Identity / GCE), set
auth_google_metadata: true: tokens are minted and auto-refreshed from the instance metadata server,
so tracked jobs against a Google Iceberg REST catalog (e.g. BigLake) keep authenticating. A static
auth_bearer still works for one-shot map/query and for local use, but expires after ~1h.

Design note: the provider talks to the metadata endpoint directly rather than pulling a full
Application-Default-Credentials crate. That keeps fluree-db-iceberg lean and runtime-agnostic
(AuthConfig stays an explicit, declared config rather than ambient credential discovery), and it
mirrors the existing oauth2_client_credentials provider exactly — same struct shape, same
CachedToken, no new dependencies. It's precisely how a GKE workload authenticates. Storage-side
HMAC interop keys are unaffected — they don't expire.

Testing

  • Unit + integration (Docker fluree-rust-dev, workspace pinned toolchain):
    • cargo test -p fluree-db-iceberg --lib → 148 passed (incremental scan / snapshot windows,
      google_metadata provider, CachedToken).
    • cargo test -p fluree-db-api --features iceberg --lib → 669 passed (watermark
      encoding/injectivity, latest-by-key dedup, worker due-job scheduling/rescheduling).
    • cargo test -p fluree-db-api --features iceberg --test grp_graphsource → 103 passed, incl.
      it_materialize_retract — a regression test that whole-subject retraction binds ?s as a typed
      @id (a bare-string binding parses to a literal that joins nothing and silently retracts zero
      rows) and asserts the triples are actually gone end-to-end.
  • cargo fmt --all --check clean; cargo clippy --all-targets clean on the touched crates,
    with the iceberg feature both off and on (the materialize code is #[cfg(feature = "iceberg")],
    so it must be linted with the feature enabled).
  • Manual end-to-end against a real Iceberg dataset behind a Google Iceberg REST catalog: registered
    R2RML mappings, tracked several tables into a single native ledger via /iceberg/track, confirmed the
    immediate first sync + an incremental re-sync on the worker (only added files re-read), and ran SPARQL
    over the deduped materialized ledger — one node per subject, expected counts.

Known limitations / follow-ups

  • Worker state is in-memory per node. Tracked jobs are not persisted across restarts (they must be
    re-registered); persisting the ApplyRecord is noted as a follow-up in the routes. The materialized
    data and its watermark are durable (they live in the target ledger), so a re-registered job
    resumes incrementally rather than re-reading everything.
  • Incremental scan is append-only. Snapshots that delete/rewrite files fall back to a full-window
    read; combined with latest-by-key upserts this is still correct (idempotent), just less cheap.
  • google_metadata requires GCE/GKE (the metadata server isn't reachable elsewhere); locally, use
    a static auth_bearer.

Breaking changes

None. Everything is additive: four new endpoints, a new AuthConfig variant, and additive request
fields (poll_interval_secs, auth_google_metadata). All new server/API code is behind the existing
iceberg feature; nothing changes for builds without it.

@christophediprima

Copy link
Copy Markdown
Contributor Author

Hi there! What do you think about this feature? Any chance it gets merged at some point? Do you think it is a good idea?

@christophediprima

christophediprima commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Update — rebased onto latest main, plus additive @type union

Rebased the branch onto current main (v4.1.3) — conflict-free. This adapts to the Iceberg→R2RML
catalog engine that merged in the meantime: delete / order_by now sit on IcebergCreateConfig (materialization options, not connection concerns) under the new IcebergConnectionConfig split, and the refreshing providers share a single CachedToken in auth::token (keeping the redacting Debug).

Added one materialization-correctness commit: rdf:type now UNIONs across sources in additive mode. Previously each subject was applied with a single upsert (which retracts-then-inserts per predicate), so when more than one source contributed to the same subject IRI — a shared target ledger fed by several graph sources, a join table that only adds an edge to a parent entity, or a
secondary-type table — whichever source wrote last clobbered the others' @type. Now additive-mode materialize asserts @type via an idempotent insert and upserts only the non-type predicates, so classes accumulate instead of overwriting. A rr:predicate rdf:type object map is likewise routed to
the subject's @type (the only way to express per-row, data-driven typing, since rr:class is constant-only) rather than being treated as an ordinary predicate. Covered by new tests: a type-union case, a control proving the single-upsert path clobbers, and a build_live_node unit test for the
rdf:type-as-class routing.

Relationship to #1529 (feat/materialize-builder, DEC-003 D1)

#1529 lands the bulk "native twin" builder: a whole-graph R2RML enumerator feeding the native bulk-import pipeline, a post-build parity gate, and a fluree materialize CLI. It stamps each twin's final commit with a WatermarkStamp — per-table pinned Iceberg snapshot (metadata_location + snapshot_id/sequence_number) + mapping hash + builder version, readable via read_stamp. That is a one-shot build; DEC-003 calls out a separate Deliverable 3 — delta-sync for keeping a twin fresh, which isn't implemented there yet (the per-table snapshot_id/sequence_number are captured in
the stamp precisely so delta-sync can diff).

This PR is the complementary half: incremental refresh + a tracking worker + HTTP endpoints (/materialize, /track, /untrack, /tracking). Its append-only snapshot-window scan (plan_incremental over (from, to]) is exactly the delta-sync operation D3 describes — read the twin's WatermarkStamp for each table's from snapshot, scan only the files added since, and upsert the delta into the twin (with the @type union above so a re-typed subject isn't clobbered).

Happy to reframe this PR as the delta-sync layer on top of #1529's twin rather than a parallel bulk path — reusing #1529's WatermarkStamp / build_watermark as the shared contract and dropping any overlap in graph_source/{catalog_session,r2rml}.rs. Flagging the overlap now so we can decide how the two should compose.

@christophediprima

christophediprima commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Update — named-graph routing in the materializer (rr:graphMap / per-graph statements)

The materializer now honors R2RML rr:graphMap / rr:graph at the subject-map level: each source row's triples are placed into a named graph derived from the row, instead of always the default graph. No graph map ⇒ default graph (existing behavior, unchanged).

Mechanics — no transaction-core changes (named graphs are already first-class: flakes carry a graph id, staging keys on (GraphId, Sid), and generate_upsert_deletions already scopes retract-existing by graph_id):

  • fluree-db-r2rml — a GraphMap term map (rr:graph constant shortcut, or rr:graphMap [ rr:template | rr:column | rr:constant ]) parsed onto SubjectMap; materialize_graph_from_batch resolves the per-row graph IRI, reusing the exact template/column expansion the subject materializer uses.
  • fluree-db-api (r2rml_materialize.rs) — the accumulator now keys on (graph, subject), so the same IRI in two graphs is two independent keys. Live nodes are emitted with a per-node @graph selector ({"@id": <s>, "@graph": "<g>", … }), which the insert/upsert transaction parser resolves per node — scoping every triple (including @type) to that graph; default-graph nodes (and the materialization watermark — bookkeeping, kept in the default graph) stay plain top-level. Whole-subject retraction (latest-by-key mode) is scoped to each graph via the UPDATE graph key; the upsert's own retract-existing is already graph-scoped, so per-graph subjects never clobber across graphs.

Additive mode composes unchanged: @type still UNIONs and predicates still upsert — but now within each subject's graph. Tests cover rr:graphMap/rr:graph parsing, (graph, subject) isolation of the same IRI across graphs (record + merge_live), the graph-scoped retract doc, per-graph doc flattening, and an end-to-end round-trip through the transaction parser (it_materialize_named_graph) that inserts/upserts the emitted per-node @graph shape into a memory ledger and reads it back per graph — asserting each subject's triples land in its named graph (not the default) and stay isolated across graphs.

@christophediprima
christophediprima force-pushed the feature/iceberg-materialize branch from 2644dc1 to 21935c9 Compare July 22, 2026 10:31
@christophediprima

Copy link
Copy Markdown
Contributor Author

Update — templated materialize target (fan out into a ledger per partition) + a shared watermark state ledger

I added a templated materialize target so one tracking job can fan out into many target ledgers, resolved per row from the source's own columns. Motivation: I need per-user isolation (each user sees only their own data), not just per-tenant. Fluree's read-policy engine is deliberately graph-blind (it targets subjects/properties/classes, never named graphs), and the docs recommend separate ledgers for separate access regimes — so I make the isolation boundary the ledger, one per (tenant, user), which rides the existing bearer-scope (can_read) at the maintainer-endorsed granularity rather than inventing graph-as-authorization. (The rr:graphMap named-graph routing from the previous section stays as an orthogonal capability; it is just not what I use for per-user access isolation.)

How it works. The target on /iceberg/materialize and /iceberg/track may now contain {column}
placeholders (e.g. silver_{tenant_id}_{user_id}:main). I resolve the concrete target ledger per row by expanding that template against the row's columns (reusing the same expand_template_from_batch the subject/graph materializers use), so a single scan of the source routes each row into its own ledger. A placeholder-free target is the existing single-ledger behavior, unchanged — this is fully backward compatible. Concretely: the latest-by-key accumulator now keys on (target, graph, subject) instead of (graph, subject); after finalizing I group the state by target ledger and run each target's retract/@type-insert/predicate-upsert as its own independent commit chain (creating the ledger on
first sight — correct for append-only CDC, where a user's rows only arrive once the user exists). A row whose template columns are null can't be routed and is skipped.

Watermark moved to a shared state ledger. Previously the per-(source, table) watermark was written as a triple inside the target ledger's default graph, mixed with materialized entity data. With fan-out there is no single target — and the incremental scan needs the watermark before it discovers which per-row targets exist. So I moved the watermark into one shared fluree_materialize_state:main ledger, keyed by (source, target-spec, table) (the target-spec is the template for a fan-out job, so one templated job keeps one watermark per source table — a single scan feeds all its targets). This also removes bookkeeping triples from user data. I advance the watermark after every target's data commit, never before, so a crash in the gap re-reads the window (safe because the writes are idempotent:
whole-subject replace / idempotent insert+upsert). This unifies plain and templated jobs on one generic, job-linked state location instead of storing the watermark in two different places.

Tests: a new record_isolates_same_subject_across_targets (the same IRI in two target ledgers is two independent keys), the watermark helpers updated for the (source, target-spec, table) key with an injectivity test across all three segments, and the existing single-target + named-graph suites still green (19 unit + 8 materialize-integration). --features iceberg; fmt + clippy (-D warnings) clean.

@christophediprima
christophediprima force-pushed the feature/iceberg-materialize branch from b2f202f to 5e03ddd Compare July 23, 2026 15:41
@christophediprima

Copy link
Copy Markdown
Contributor Author

Update — don't upsert an empty doc for type-only sources

A type-only source (subject + rdf:type, no other predicates) produces an empty additive-mode predicate doc, and I was upserting it unconditionally. The transactor rejects an empty upsert, which aborted the sync before its watermark advanced — so that source re-scanned and re-committed the same @type triples on every poll (churn). Fix: guard the upsert with if !pred_doc.is_empty(), mirroring the existing @type-insert guard (same guard added to the latest-by-key delete-only path). +1 test; clippy/fmt clean.

@christophediprima

Copy link
Copy Markdown
Contributor Author

Update — tracking jobs survive a restart

Closes the "worker state is in-memory" limitation above, which turned out to be worse in practice than it reads. A restart silently stopped every materialization until a client noticed and re-issued POST /iceberg/track — and nothing surfaced the gap: GET /iceberg/tracking reported the worker running with zero jobs, which is indistinguishable from "nobody has tracked anything yet". For a fan-out job feeding a ledger per partition, that is an outage that looks like an idle system.

Jobs now persist as urn:fluree:materialize#Job rows in the shared fluree_materialize_state:main ledger — the store this worker already owns, already writes on every committed poll, and which already carries each job's source and target-spec on its watermark rows. MaterializeTrackingWorker::run restores the set before its first tick.

  • The job is stored as one serialized JSON blob, plus duplicate source/target triples so operators can query jobs with the same SPARQL they already use for watermarks. The blob keeps the restore decoder trivial (the only existing state-ledger reader is extract_first_i64, which cannot decode N rows × M columns) and lets a job gain fields without a schema migration. It is also self-validating on read: only a string that deserializes into a whole PersistedMaterializeJob is taken, so the sibling triples on the row can never be mistaken for one.
  • Restore lives in run(), not in the server's construction path, which inherits peer-exclusion for free — peers never spawn a worker, and /iceberg/track already 400s on them.
  • Recovery is incremental. The per-(source, target-spec, table) watermarks live in the same ledger and are read by the materialize call itself, so a restored job re-reads nothing it had already materialized. A restored job's first poll fires one interval from now, matching track.
  • untrack is durable too — it sets tracked = false rather than retracting the row, keeping an audit trail and avoiding a delete path. Restore filters on that flag.

Why not the graph-source record, which would have been the cheaper mirror of how the BM25 maintenance worker persists its own tracked flag: IcebergGsConfig has no catch-all field and both create paths serialize a fresh struct (r2rml.rs:195-198, :290-293), so any key written onto the record is dropped on the next config write; and rest_client_cache_key hashes the raw config JSON (r2rml.rs:69-71), so writing to it would discard the cached RestCatalogClient and its OAuth token on every change. A job is also a relationship (source → target-spec), not a property of the source — one source can have several targets, which the record shape handles badly.

Also fixes a latent race the new writes would have made hotter: opening the state ledger was a bare check-then-create, and the loser of a race between two pollers got ApiError::LedgerExists instead of a ledger, failing the whole materialization pass. Both call sites now share one helper that tolerates it.

Tests (fluree-db-server/tests/iceberg_track_durability.rs, +4): a job tracked before a restart is running after it with its own interval intact and nothing re-issuing track; an untracked job stays gone across a restart; re-tracking the same pair updates in place rather than accumulating rows; and a server that has never tracked anything treats the absent state ledger as "no jobs" rather than an error that kills the worker. The tests drive the durable record directly rather than through POST /iceberg/track, since that route also runs an immediate materialize and would need a reachable catalog — the restore path under test is the real one either way. clippy/fmt clean.

@christophediprima
christophediprima force-pushed the feature/iceberg-materialize branch from 69be7f6 to 6f107cb Compare July 28, 2026 15:03
christophediprima added a commit to christophediprima/db that referenced this pull request Jul 28, 2026
Adds a third read-only MCP tool, `fql_query`, alongside `sparql_query` and
`get_data_model`. It runs a SELECT-style Fluree FQL (JSON-LD) body through
`run_jsonld_subquery` — the same connection path the HTTP /v1/fluree/query route
uses, which wires the BM25 index provider — so an embedded `f:searchText`
full-text block executes in-process. BM25 is FQL-only, so this is the tool that
gives an agent full-text / graph-aware-RAG retrieval that `sparql_query` cannot.

- Forces `opts.identity` from the MCP token (non-spoofable); rejects non-SELECT
  and `from`-less bodies. Returns the same byte-budgeted Agent JSON envelope as
  `sparql_query`, governed by the same --mcp-agent-json-max-bytes /
  --mcp-query-timeout-ms settings.
- Tests (mcp_agent_json): fql_agent_json_envelope_shape,
  fql_requires_authenticated_identity, fql_rejects_non_select_and_missing_from.
- Docs: new docs/query/mcp.md ("Querying over MCP"); cross-linked from the query
  README, the SPARQL/JSON-LD pages, the AI overview, and the MCP config reference.

Stacks on the iceberg-materialize (fluree#1422) + bm25-search (fluree#1543) branches; kept on
the fork for now.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔄 Request changes — with genuine appreciation for the work, and a concrete proposal below for how we get all of it landed.

@christophediprima this is a substantial contribution, and the sustained engagement shows — the rejected-alternatives reasoning in the job-persistence commit and the churn analysis in the empty-upsert commit are the kind of commit bodies I wish more PRs had. Your core premise also survives scrutiny: I verified fluree-db-policy has no graph-scoped enforcement, so you are right that per-ledger scope is the real isolation boundary today. And the CDC semantics you've worked out — tombstone deletion, latest-by-key, the additive rdf:type union, watermarks, restart-surviving jobs — are exactly the hard-won details this capability needs.

Five things block the PR in its current shape; the inline comments carry the detail and the suggested fixes. (1) plan_incremental reimplements the Iceberg manifest walk and so misses the merge-on-read fail-closed guard that merged in #1520 roughly nine hours after your rebase — and materialization raises the stakes, because a caveated query result becomes permanent, uncaveated state in a ledger the watermark never revisits. (2) The materialize pass buffers the whole table, the whole subject accumulator, and the full JSON-LD expansion simultaneously inside the server process, so the first sync of a large CDC table — the stated use case — can take query serving down with it. (3) Target-ledger creation is a check-then-create race; your newest commit fixed exactly this for the state ledger, and the target path needs the same tolerant fallback. (4) Mutation testing shows no test calls the materialization engine: reintroducing the exact bugs that commits cf472f9ab and a985bc6b5 fix leaves all 28 tests green. (5) rr:graphMap silently drops POM-level graph maps, repeated graph maps, and rr:defaultGraph, which collapses two tenants' rows into one accumulator key — the exact clobbering named-graph routing exists to prevent.

Now the structural part, which I'd rather be transparent about than let surface awkwardly later: we have an internal draft (#1529) exploring the same native-twin capability through the bulk-import finalizer rather than transaction replay. That architecture resolves the memory blocker structurally — chunked, bounded, parallel ingest with serial finalization — rather than by adding knobs to the replay path. Neither effort should win by default, but having now reviewed both closely, I think the right landing is: the bulk-builder as the engine foundation, with your CDC semantics on top of it — #1529 has none of the tombstone/latest-by-key/watermark/job-persistence thinking this PR gets right, and that half is the harder half to get right.

So here is my concrete proposal for landing this work rather than orbiting it. Split the PR: (1) the Google metadata-server auth commit (10e27961a) is self-contained, fixes a real expiring-token bug, and I would approve it in its own PR today; (2) rr:graphMap named-graph routing stands alone as a genuine R2RML vocabulary gap — with the fail-loud fixes from the inline comment; (3) the append-only incremental scan stands alone once it routes through the shared MoR-guarded planner; (4) for the materialization engine itself, let's converge on the bulk-import foundation and port your CDC semantics onto it — I'd genuinely value doing that part together, since you've thought harder about CDC ordering and deletion semantics than anyone else on this codebase. The ledger-per-(tenant,user) fan-out deserves its own design discussion before it ships under either engine, since it converts a policy gap into unbounded ledger multiplication and graph-scoped policy may be the better long-term investment.

One housekeeping items (somewhat implied by the above). The branch currently has 5 conflicts against main, two of them exactly where #1520's guard exports live, so the MoR interaction should be resolved deliberately rather than by whatever conflict resolution happens to produce.

Adherence to repo commitments:

  • Patterns/abstractions: ✖ Reinvents bulk ingest instead of extending the memory-bounded chunked path in fluree-db-api/src/import.rs, adds a second Iceberg manifest walk instead of routing through the guarded planner, and implements a partial rr:graphMap that silently drops the R2RML constructs it does not support.
  • Performance (speed first, memory second): ✖ CRITICAL — unbounded buffering on a task spawned inside the server process. No query hot path is touched.
  • Testing: ⚠️ The new tests run (correctly wired into grp_graphsource.rs) and the durability suite is excellent, but the engine itself has zero coverage — two mutations reintroducing shipped bugs leave all 28 tests green.

/// is append-only via [`TableMetadata::window_is_append_only`](crate::metadata::TableMetadata::window_is_append_only)
/// and fall back to a full re-read otherwise — overwrite/delete/replace
/// snapshots carry updates/deletions this scan cannot see.
pub async fn plan_incremental(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. CRITICAL: this is a third Iceberg read entry point that will not inherit the merge-on-read fail-closed guard, and the merge that introduces the gap is textually clean.

plan_incremental reimplements the manifest-list walk instead of routing through plan_scan_for_snapshot_inner. Compare :219 (parse_manifest_list) and :226 (if manifest_entry.is_deletes() { continue; }) against the identical two lines at :94/:109 in the full-scan path. PR #1520 ("fail closed on merge-on-read delete files", still open on fix/iceberg-mor-delete-guard) installs mor_guard::ensure_no_summary_deletes + ensure_no_delete_manifests at exactly those two points in plan_scan_for_snapshot_inner, in both planners — and nowhere else. I verified git merge-tree --write-tree HEAD 771f6e88b returns exit 0 with no conflict, so whichever of these two merges second, git will report nothing and the incremental path will silently ship ungated.

To be fair about the exposure: the common MoR timeline is caught, because MoR delete files arrive under overwrite/delete snapshot operations, window_is_incremental_safe rejects those, and the fallback goes through plan_scan which #1520 does gate. The residual holes are (a) replace snapshots, which the Iceberg spec defines as "data and delete files were added and removed" and which table.rs:187 explicitly safelists, and (b) any writer whose summary operation string understates what the snapshot did. Both produce a materialized native twin that durably contains rows the source considers deleted — and unlike a virtual query, a twin is not re-read, so the wrong answer persists and is served at native speed as ground truth.

Suggested fix: hoist the manifest-list load + guard into one shared helper used by all three planners, or at minimum add the same two calls at the top of plan_incremental:

let allow_mor = crate::mor_guard::mor_deletes_allowed();
crate::mor_guard::ensure_no_summary_deletes(to_snapshot, &self.metadata.location, allow_mor)?;
// ...then parse_manifest_list_with_deletes + ensure_no_delete_manifests, as in plan_scan_for_snapshot_inner

Whichever PR lands second should carry this. Worth coordinating explicitly with #1520 rather than leaving it to the merge.

/// classes UNION across sources — several sources (or a join table adding an
/// edge to a parent) can contribute types to the same subject in a shared
/// target without clobbering each other.
pub async fn materialize_r2rml_graph_source(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. A 1365-line engine plus a 381-line worker ship with zero end-to-end test coverage, and the tests that claim to cover them do not.

grep -rn "materialize_r2rml_graph_source" --include=*.rs . finds no test caller anywhere in the repo — only routes/iceberg.rs:288,389 and materialize_worker.rs:277. The three new it_materialize_*.rs files are wired correctly into grp_graphsource.rs:18-23 and their 7 tests do run (confirmed by name under --all-features), but they hand-copy the JSON shapes rather than calling the code that produces them — it_materialize_retract.rs:38 even says so: "mirrors build_retract_doc".

I proved this is not theoretical. Reverting build_retract_doc:699 to the bare-string binding — the exact bug the PR body says it_materialize_retract is a regression test for — turns the unit test build_retract_doc_shape red (so there is a real guard, credit where due) but leaves all 7 PR-new integration tests green, materialize_retract_shape_actually_retracts included. The PR body's claim that it "asserts the triples are actually gone end-to-end" is true of the shape and false of the producer.

What's missing is a test that drives materialize_r2rml_graph_source itself. That needs an Iceberg source, which is the hard part — but the accumulator → doc → transaction → query round trip could be exercised against a memory ledger with a stubbed scan_for_materialize, and that is where every one of the bugs in this PR's own commit history lived (the bare-string retract, the @graph envelope, the empty-upsert abort). Three shipped-then-fixed bugs in the same seam is the argument for the test.

Comment thread fluree-db-api/src/graph_source/r2rml.rs Outdated
}
})
.buffer_unordered(concurrency)
.try_collect::<Vec<Vec<ColumnBatch>>>()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. CRITICAL (performance/memory): the materialize path buffers the entire table, twice, with no streaming or byte budget.

read_scan_tasks does try_collect::<Vec<Vec<ColumnBatch>>>(), so every Parquet file in the plan is decoded and held before a single row is processed. materialize_r2rml_graph_source:234-288 then accumulates one SubjectNode per distinct subject across all tables into MaterializeAccum, and :398 serializes the whole set into a single JSON-LD array per target. build_retract_doc:696 has the same shape — every subject IRI in the window goes into one values array in one update call.

An initial materialization (from = None → full scan, which is also what force_full and every expired/branched-history fallback take) therefore holds the decoded table plus its full JSON-LD expansion simultaneously. This does not degrade gracefully on a large table; it OOMs. Given the PR's stated motivation is large CDC tables, that ceiling deserves at least a documented row limit, and ideally chunked commits keyed off a byte budget.

Note the query engine itself is unaffected — I verified plan_scan_for_snapshot_inner and r2rml.rs::scan_table are byte-unchanged and the new helpers have no query-path callers, so there is no virtual-query regression.

// per-row template (e.g. one graph per tenant/user) routes each row into its
// own graph so the same subject IRI holds independent per-graph statements.
// A null graph value materializes to `None` -> default graph (never dropped).
let graph_iri = match &tm.subject_map.graph_map {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. rr:graphMap is honored only by the materialize path, so the virtual and materialized views of the same source disagree about where the triples live.

grep -rn "graph_map" across fluree-db-query/ and fluree-db-api/ returns exactly one consumer: this line. The query path never reads SubjectMap::graph_map. So for a mapping with a subject-level rr:graphMap, querying the graph source virtually returns every triple in the default graph, while the materialized twin puts them in per-row named graphs — and a query written against one returns nothing against the other. That breaks the PR's own premise that materializing gives you the same data at native speed, and it is silent.

Either teach the query path to honor graph maps too (parity), or gate materialization on the mapping having no graph map until it does.

Separately, R2RML permits rr:graphMap on predicate-object maps as well as subject maps; extractor.rs:extract_graph_map only reads the subject-map position, so a POM-level graph map is silently ignored rather than rejected — that one should at minimum fail loud.

Comment thread fluree-db-server/src/state.rs Outdated
let storage_vend_scope = resolve_storage_vend_scope(&config);

// Spawn the R2RML/Iceberg materialization tracking worker on write
// nodes. Peers forward writes elsewhere, so they don't run it. (In Raft

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional, but please confirm the deployment story. (Covers :285-287.)

The code comment concedes it: "In Raft mode the worker currently runs on every node and writes directly via Fluree::upsert; gating it to the leader is a follow-up." Every non-Peer node spawns its own worker with its own in-memory job set.

If a multi-node non-Peer deployment is reachable today, two workers polling the same (source, target) will interleave their retract and upsert commits — and since the retract at r2rml_materialize.rs:376 and the upsert at :400 are two separate transactions, node A's retract landing after node B's upsert leaves subjects missing until the next poll.

The same race exists between the worker and a concurrent POST /iceberg/materialize for the same pair even on a single node, since nothing serializes them. A per-(source, target) mutex around the pass would close the single-node half cheaply.

/// (fan-out: one ledger per partition, e.g. per (tenant,user)). Returns `None`
/// when a template placeholder column is null/missing — the row cannot be routed
/// to a ledger and is skipped (it could not be isolated to a user anyway).
fn resolve_target_ledger(target: &str, batch: &ColumnBatch, row: usize) -> Option<String> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Design discussion — worth resolving before the fan-out ships; non-blocking for the rest.

First, your stated premise is correct, and I verified it rather than assuming: fluree-db-policy/src/ has no graph-scoped enforcement (12 "graph" references, all about the policy model graph; graphs: None at index.rs:327,545). Named graphs genuinely are not an authorization axis here, so per-ledger bearer scope genuinely is the isolation boundary. The reasoning in eb62eaa4e is sound.

The open question is whether ledger-per-(tenant,user) is the right answer to that constraint: it converts a policy gap into unbounded infrastructure multiplication — every partition gets a nameservice record, a commit chain, and its own index set, created implicitly from row data with no bound, no quota, and no operator visibility beyond the ledger list. It also puts the PR in the odd position of shipping two isolation mechanisms (named graphs and separate ledgers) where only one can be the boundary. I'd like us to weigh graph-scoped policy as the longer-term investment before the fan-out lands, rather than settling it implicitly inside this PR.

self.bump(|s| s.syncs_noop += 1);
debug!(source = %job.source, target = %job.target, "materialize tracking: no delta");
}
Err(e) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional.

A permanently failing sync is a warn! plus a syncs_failed counter, so a target ledger can diverge from its source indefinitely while GET /iceberg/tracking still reports the worker healthy. Given the MoR refusal recommended in the scan-path comment will make exactly this happen post-merge for MoR tables, consider surfacing per-job last_error and last_success timestamps on the tracking endpoint.

entity**, not individual columns — a `null` in an ordinary column of a *live* row
just clears that one predicate.

### Assumptions and limitations

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional.

The "Assumptions and limitations" section is genuinely good on CDC shape (one row per subject revision, one triples map per table, orderable order_by, dedicated target, tombstones required). It omits four things the code does: merge-on-read is unhandled on the incremental path, the full sync is unbounded in memory, the worker runs on every non-peer node so multi-node deployments double-materialize, and a templated target creates ledgers without bound. #1520 added an MoR section to this same file on main — the materialization section should cross-reference it after the rebase.

@@ -0,0 +1,224 @@
//! Materialization tracking jobs must survive a server restart.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Praise.

This is the strongest-tested part of the PR: four tests that drive the real persist_materialize_job / forget_materialize_job / tracked_materialize_jobs API and the worker's actual restore path, including the negative cases (untracked jobs stay out, re-tracking replaces rather than duplicates, restore is a no-op with no state ledger). This is exactly the pattern the materialization engine tests should follow.

#[cfg(feature = "iceberg")]
let v1_admin_protected_writes =
v1_admin_protected_writes.route("/iceberg/map", post(iceberg::iceberg_map));
let v1_admin_protected_writes = v1_admin_protected_writes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Praise.

The four new routes are correctly mounted on the existing v1_admin_protected_writes / v1_admin_protected_reads layers rather than inventing a new auth path, so they inherit admin-token enforcement and leader-forward ordering for free. Correct altitude.

@christophediprima

Copy link
Copy Markdown
Contributor Author

Taking the split — it's the right call, and thank you for laying it out that concretely rather than just blocking. Answering per part.

Part 1 — up as #1567

10e27961a cherry-picked onto current main with one conflict (upstream's with_auth_bearer_token_ref landed at the same insertion point as with_auth_google_metadata — resolved as a union, neither modified), plus one adaptation: hydrate at auth/mod.rs:189 needed a GoogleMetadata arm, written out explicitly rather than as a wildcard so the match keeps failing compilation when a variant appears.

Your wildcard-free canary in ledger_info.rs then caught what I'd missed — a new AuthConfig variant has to earn an explicit redaction decision and I hadn't made one. For the record it needs no allowlist entry: both fields are plain String rather than ConfigValue, so there's no secret-capable field to seed, and the credential is minted per call and only ever lives in the in-memory CachedToken, which isn't serialized. I added the variant to the fixture anyway so it runs the assertions with the rest. Good guard — it failed me in precisely the way it was written to.

Part 2 — rr:graphMap routing — up as #1581

Agreed it stands alone, so I've sent the vocabulary layer: #1581, fluree-db-r2rml only, 7 files. It carries every fail-loud fix from your inline comment — POM-level graph maps, more than one graph per term map, and rr:graph rr:defaultGraph all now fail at mapping-load time with a ConfigError naming the construct, instead of being dropped into the default graph and collapsing two partitions into one accumulator key.

One I added beyond your list, because it reaches the identical failure by another route: a rr:graphMap with no rr:template, rr:column or rr:constant was treated as absent rather than malformed.

I deliberately left out the 313 lines of r2rml_materialize.rs from 7979c338f — that's engine consumption and belongs with part 4. Splitting at the crate boundary is what makes this the standalone vocabulary gap you described.

Two things #1581 does not resolve, both called out in its body rather than left for you to find:

Your virtual/materialized divergence finding. The query path still never reads SubjectMap::graph_map. Worth flagging a trap in your second option though — "gate materialization on the mapping having no graph map" would disable exactly the feature this enables, so parity looks like the real requirement rather than a choice between two. That's query-engine work and I haven't sized it; happy to, if you agree that's the direction.

graphMap routing and BM25 are mutually exclusive today. The indexing query runs at ledger.as_graph_db_ref(0) (bm25.rs:241, :259) and DocKey is {ledger_alias, subject_iri} with no graph field (bm25/index.rs:29-34), so anything routed into a named graph silently disappears from full-text search. Pre-existing rather than introduced by part 2 — but part 2 is what makes it reachable. Would you rather I document the limitation, or is a graph-aware DocKey something you'd take? The latter is a snapshot format change plus a forced rebuild of every existing index, so I'd want your call before starting rather than presenting you with one.

Also up: #1580, a policy bug found while auditing how far the graph identifier travels through the read path. PolicyContext::class_cache is keyed on Sid with no graph, so the same subject IRI in two named graphs with different types resolves to whichever populated the cache first and f:onClass then decides on the wrong classes — order-dependent behaviour in an authorization path. It's reachable by any from-named user, not just through R2RML; docs/security/policy-in-queries.md:203-205 actually recommends f:onClass for exactly the graph-differentiated case it corrupts. Sent separately since it's pre-existing and independent of this PR. Two smaller siblings in the same family — two commit/block paths that hardcode graph 0, and the read-path condition executor pinned to g_id 0 — I'll send the same way rather than clutter this thread.

Part 3 — append-only incremental scan

Agreed, and it's blocked exactly where you said. You were more right than you knew about the housekeeping note. I attempted the rebase to size it: four of the five conflicts are import-list unions, but the fifth isn't a conflict at all — it's a compile error, send_planner.rs:235: cannot find function parse_manifest_list. plan_incremental calls a function #1520 restructured away when it introduced the MoR-guarded planner. So finishing the rebase is the fix, there's no mechanical resolution, and I'd have papered straight over it if I hadn't compiled the result. I've reset the branch to what you reviewed rather than push a rebase that hides that.

Part 4 — the engine

Yes, and thank you — I'd much rather converge than have two implementations orbit each other, and I'll take you up on doing it together. Two things I'd want to carry across explicitly, because they're the easiest to lose in a port and the most expensive to rediscover:

  • The retract-then-upsert pair is ordered, and its crash window is documented as self-healing rather than merely tolerated. If the finalizer reorders or batches those, the guarantee changes shape.
  • The watermark deliberately never rides in the same commit as the data. It advances after every target's data commit, never before, so a crash in the gap re-reads the window — safe only because the writes are idempotent.

Point me at #1529 whenever it's shareable and I'll start by mapping our CDC semantics onto its seams rather than proposing a shape.

On the fan-out, and on graph-scoped policy

Agreed it deserves its own discussion, and I'll bring numbers. We've run the ledger-per-(tenant,user) shape in anger, and it bends in three specific places:

  1. Boot is O(tenants). preload_all_ledgers structurally loads every non-retracted ledger at startup — the warm budget caps page warming, not the structural load.
  2. reindex_max_bytes has no aggregate ceiling. It's the hard threshold that blocks commits, and it's set per LedgerState, so the safe per-ledger value has to shrink as tenants grow and nothing surfaces that. At 64 MiB and 1000 ledgers the worst case is 62 GiB of novelty.
  3. BM25 maintenance saturates first — at our data density, somewhere around 25-50 concurrently-active users — because the "incremental" sync re-runs the whole indexing query. It's also the only one of the three that gets worse as data grows at a fixed tenant count.

On graph-scoped policy specifically — I went and sized it, because it's what I originally wanted and I'd have argued for it if I thought it carried its weight. I don't think it does, at least not as a fix for those three, and I'd rather say so than sell it.

The mechanism is fine: graph is a physical partition rather than a key column (run_record.rs:231), so restricting a scan to one graph is cheaper than a prefix seek, and g_id already reaches every read enforcement site — it's dropped at exactly one boundary, policy/enforcer.rs:102-109. The materializer's @graph IRI would resolve and match an f:onGraph target exactly.

What it doesn't do is fix (1), (2) or (3) — collapsing 1000 ledgers into 1000 graphs in one ledger trades each of them for a different problem rather than removing it:

  1. Boot — the N ledger loads go away, but store construction eagerly fetches every named graph's four branch manifests in a serial await loop (binary_index_store.rs:316-330), so it becomes O(4xtenants) sequential CAS round-trips on every cold open. Net win only once that loop is lazy or concurrent. There's also a hard u16 ceiling at ~65,533 graphs with no cap check.
  2. Novelty budget — the 62 GiB aggregate worst case does collapse, which is a real gain. But 1000 independent budgets become one shared 64 MiB budget, so a single busy tenant applies commit backpressure to every other tenant. Lower ceiling, much wider blast radius.
  3. BM25 — this one gets actively worse, for the DocKey reason under part 2: routed data isn't indexed at all today, and a naive shared DocKey would merge two tenants' text into one document. And the saturation itself is per-index maintenance work, which consolidating ledgers doesn't reduce.

So f:onGraph is worth doing on its own merits, but not as multi-tenancy plumbing, and I don't want to argue for it on a benefit it doesn't deliver.

If you do want it, three decisions look like yours rather than mine:

  • for_graphs as an orthogonal narrowing field mirroring for_classes, not a TargetMode::OnGraph variant. Under the narrowing form the covers_predicate fast path (types.rs:504-521) stays sound by construction. Under a variant with its own bucket it over-approximates the wrong way, and the two non-exhaustive matches!(target_mode, OnProperty|OnSubject|OnClass) sites take the fail-open branch.
  • Fail-closed semantics for unresolved graph targets. Target-mode precedence falls through to TargetMode::Default when all target sets are empty (policy_builder.rs:1058-1068), and Default applies to every flake. A graph has no GraphId until something is written to it — so f:allow + f:onGraph <not-yet-created> wouldn't be inert, it'd be blanket allow on the ledger. That contradicts the for_classes convention, which is why it needs your call rather than my guess.
  • A written position on the write side. WriteFlakeInfo has no graph field (fluree-db-policy/src/types.rs:172-196) and a transaction naming a new graph IRI implicitly registers it, so graph would be a confidentiality boundary with no integrity half. Fine for my case — only the materializer writes — but it should be stated rather than discovered.

Worth noting the docs currently point the other way: docs/security/policy-in-queries.md:201-205 says to use separate ledgers for wholly separate access regimes. I read your comment as revisiting that, but I'd rather name the contradiction than let it surface later.

Blockers

2–5 I'll pick up in their respective parts. Blocker 4 is fair and slightly embarrassing — mutation testing showing all 28 tests green with the engine's bugs reintroduced is exactly the check I should have run myself.

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔄 Request changes — third round, but the delta is genuinely better work than the last two, and one of the two commits I'd land nearly as-is.

Resolution table (prior findings → 4e09f8ee3)

# Finding Status
B1 MoR fail-closed guard bypassed in plan_incremental Unfixed — and the rebase premise is refuted (R3-3)
B2 Unbounded memory in the materialize pass One of three terms fixed; the two larger ones untouched (R3-1)
B3 No test drives the materialization engine Unfixed, and the new code repeats it (R3-2)
B4 rr:graphMap divergence + virtual/materialized parity Vocabulary half in #1581; engine half unchanged here
B5 Target-ledger check-then-create race Unfixed — r2rml_materialize.rs:421 → :442
NEW-1 Chunk budget premise measured inverted Unfixed, byte-for-byte — :409-411, :415
NEW-2 External-indexer config never drains Unfixed — state.rs:498-513, :291; reindex_min_bytes still misstated at :413
NEW-3 Chunking unreached by tests Unfixed — mutation still green
D, O1–O5, O8, O9 Design discussion + optional items elsewhere Unchanged (delta is two files)
O6, O7 Google-auth items Moved to #1567

@christophediprima f539a4378 is the best commit on this branch. unwrap_or(false) collapsing three situations into one boolean, in a place where the two branches differ by orders of magnitude in cost, is a real defect and the four-variant ScanChoice is exactly the right shape for the fix — routine at info, operator-actionable at warn, with the reason carried on the variant. Building the fixtures through the real from_json_str instead of a struct literal is the right call. And I checked the mutation you claim in the body rather than taking it: collapsing Err(e) into FullUnsafeWindow fails exactly three of them, as you said.

The blocker is on the second commit, and I'm afraid it is the same shape as round 2's: a memory fix whose premise is stated but not measured. 4e09f8ee3 bounds the raw scan, which is real and which I'd keep. But I sized all three resident terms at your own row count — 735,446 — from the actual type layouts, and the raw scan is the smallest of them by roughly an order of magnitude. For a wide CDC source: raw scan 1.97 GiB, MaterializeAccum 21.99 GiB, by_target's JSON-LD 9.20 GiB. For a typical 20-predicate source: 0.66 / 7.60 / 3.36 GiB. The accumulator runs 11–18× the columnar form of the same rows, because columnar storage pays one Vec header per column while SubjectNode pays a String predicate IRI, a Vec<JsonValue> and a BTreeMap node per predicate per row (r2rml_materialize.rs:1051-1057 against fluree-db-tabular/src/batch.rs:116-122).

Which means the 21.4 GiB you measured against a 24 GiB limit is a near-exact match for the accumulator and is not reachable by the raw scan at all — so the deployment that was OOMKilled every 4–6 minutes has no reason yet to stop, and the self-sustaining part you correctly identified (the OOM prevents the commit that would advance the watermark, so the next poll re-reads the same window) survives. Your own BE PRECISE ABOUT WHAT THIS BOUNDS paragraph names the residual honestly — I'm not saying you hid it. I'm saying the residual is the whole number, and the streaming flush per chunk that paragraph defers is the actual fix rather than the follow-up.

And the coverage claim in that commit body doesn't hold. It says grp_graphsource's 153 tests cover it, "so the whole materialize pipeline runs through the streaming path" — those three it_materialize_* files are wired in correctly and they do run, but each drives fluree.insert/upsert/update against a hand-built document that mimics what the materializer emits, and none calls materialize_r2rml_graph_source. I replaced stream_scan_tasks's body with an unconditional return empty_batch_stream(); — every Iceberg scan in the crate yielding nothing, no rows, no chunks, no commits — and got 954/954 green. Round 2's chunking mutation is still green too. That's blocker 4 for the fifth commit running, and it is why both of the last two premises had no way to be caught.

One correction I owe you from round 2, because it changes what "blocked on the rebase" means. parse_manifest_list has not been restructured away — it's on main today at manifest/manifest_list.rs:153, exported from manifest/mod.rs:21, as a one-line wrapper over parse_manifest_list_with_deletes(data, false). The cannot find function you hit comes from a resolution that took main's import line at send_planner.rs:10 while keeping this branch's body. Resetting rather than pushing a rebase you hadn't compiled was still the right instinct and I'd rather you kept it — but the job is the mechanical five-conflict one it first looked like, and landing it is what gets CI looking at this branch again. That still matters: check-runs on 4e09f8ee3 returns only Graphite / mergeability_check, same as at the round-2 head, so everything since 6f107cb48 is unverified by anything but you and me running things locally.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ for the delta, and this is an improvement — 4e09f8ee3 reaches for ColumnBatchStream, the streaming primitive the query path already had, rather than inventing a third batching mechanism, which is exactly the "extend the shared abstraction" move the last two rounds asked for. The branch-level finding is unchanged (the chunker is still a private mechanism where fluree-db-api/src/import.rs's chunked ingest exists), but the delta itself went the right way.
  • Performance (speed first, memory second): ✖ CRITICAL — memory. Speed is neutral-to-slightly-better (buffer_unordered + per-file tokio::spawn are preserved, so this is backpressure rather than serialization, and no query hot path is touched). Memory bounds the 0.12–1.97 GiB term and leaves the 2.17–21.99 GiB and 1.13–9.20 GiB terms, and NEW-1's mis-denominated chunk budget is unchanged.
  • Testing: ⚠️ The six new ScanChoice tests are genuine guards — verified by mutation, exactly as the commit body claims. But gutting the streaming core to yield nothing leaves 954/954 green, so the commit that motivated the whole delta has no coverage, and B3 is untouched.
  • Conventions: ✔ cargo fmt --all -- --check clean; cargo clippy -p fluree-db-api --features iceberg --all-targets clean; conventional-commit subjects with thorough multi-line bodies. Docs aren't updated for either commit, which is the only gap. (For the record, the Co-Authored-By trailers are not a finding — main carries 34 of them in the last 600 commits, so my earlier rubric was wrong about that being a repo prohibition.)

Verified locally at 4e09f8ee3: fmt and clippy clean at package scope; cargo nextest run -p fluree-db-api --features iceberg --lib --test grp_graphsource --test it_graph_source_r2rml → 954 passed, all six new tests confirmed by name; mutation M-1 (chunking disabled) → 954/954 green; mutation M-2 (streaming core yields nothing) → 954/954 green; mutation M-3 (collapse Err into FullUnsafeWindow) → 3 failures, matching the commit body; memory probe deep-sizing MaterializeAccum, the finalized JSON-LD, and the equivalent columnar form at three table widths, extrapolated to 735,446 rows. Worktree clean after every mutation.

Holding at request-changes, and the shortest path through it hasn't changed much: get the rebase landed so CI can see the branch, and put one test on materialize_r2rml_graph_source — I think that single test is worth more than the next three commits, because it's the thing that would have caught both of the last two. The streaming change I'd keep exactly as it is; it just needs the flush that bounds accum behind it, and I'd rather help size that with you than have you guess at it. Point me at where you want to start.

// cap, so it multiplies by concurrently-hot ledgers, and no fixed value is
// safe because a larger window breaches any of them.
//
// The budget is measured in serialized JSON-LD bytes (cheap to estimate

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fluree-db-api/src/graph_source/r2rml_materialize.rs:390-397 — Blocking. CRITICAL (correctness of the fix itself). The budget's stated premise is measurably inverted: flakes are not several times smaller than the JSON-LD that produces them, they are the same size or larger.

The comment at :390-396 argues that "JSON-LD text runs several times larger than the flakes it yields ... so budgeting JSON bytes at a QUARTER of the flake ceiling errs in the safe direction," and :397 implements that as reindex_max_bytes / 4. I measured the ratio rather than reasoning about it — inserting 500-node docs into a memory ledger and reading novelty_size() before and after. Flake bytes divided by serialized JSON bytes: 1.30 for a wide numeric CDC row with long IRIs, 2.50 for the same row with short IRIs, 1.32 for wide booleans, 0.96 for a narrow long-text row. The ~108 flake-bytes-per-row figure from silver.observation is a property of that one very narrow table, not of JSON-LD versus flakes in general.

The mechanism behind it is Flake::size_bytes (fluree-db-core/src/flake.rs:370-408): every flake pays 16 + (8 + s.name.len()) + (8 + p.name.len()) + (8 + dt.name.len()) + o_size + 9, so a row's subject IRI is charged once per predicate on the flake side but once per node in the JSON. Short local names make it worse, not better, because the ~40-byte fixed base stops amortizing.

Consequence: a chunk sized at ceiling / 4 in JSON bytes lands at 0.24–0.62 of the flake ceiling, and the gate at fluree-db-transact/src/commit.rs:634-640 is current_bytes + delta_bytes >= max_bytes — it charges resident novelty too, which the budget never accounts for. So between 1.6 and 4.2 back-to-back chunks fill the ceiling, and the next one is rejected with the same NoveltyWouldExceed this commit exists to eliminate, on a window whose watermark then never advances. The failure is deterministic, so it recurs on every poll — the ~34h loop, just at a larger table size.

Suggested fix: budget against flakes rather than a JSON proxy. The cheap version is to size the chunk from an estimated flake cost per node — roughly subject_iri_len + Σ(pred_len + dt_len + obj_len) + 41 × predicate_count, which is derivable from the same SubjectNode you already hold — and to subtract ledger.novelty_size() from the ceiling before dividing. The honest version, if a proxy is kept, is to lower the divisor a long way and say in the comment that it is calibrated rather than safe.

// here) while the ceiling is in flake bytes. JSON-LD text runs several times
// larger than the flakes it yields — that window was ~108 flake-bytes per
// row against JSON nodes of a few hundred bytes — so budgeting JSON bytes at
// a QUARTER of the flake ceiling errs in the safe direction. Over-chunking is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fluree-db-api/src/graph_source/r2rml_materialize.rs:394-396 — Blocking. The one thing standing between NEW-1 and a repeat of the original outage — "the indexer drains novelty between chunks" — is switched off in a supported server configuration that also runs this worker.

fluree-db-server/src/state.rs:498-513: when config.indexing_enabled is false the builder takes .without_indexing().with_novelty_thresholds(...), which the comment there calls "Peer / external-indexer mode" — backpressure is still enforced, but nothing drains novelty locally. That produces IndexingMode::Disabled, whose own doc at fluree-db-api/src/tx.rs:1738-1743 says "Transactions complete without triggering indexing."

The materialize worker's spawn condition is independent of that knob: state.rs:283-297 spawns it whenever config.server_role != ServerRole::Peer. So a write node running an external indexer — indexing_enabled = false, role not Peer — runs the tracking worker against a ledger whose novelty only ever grows. There, chunking buys 2–5 transactions and then the pass fails permanently, watermark unadvanced, every poll, which is exactly the shape of the incident the commit describes.

Even with the indexer on, nothing awaits it: the four commit loops issue chunks back to back, so the drain is a race the budget is silently betting on rather than a guarantee. Subtracting live novelty_size() from the budget would make the bet explicit and self-correcting.

Minor, in the same comment: :395 says "reindex_min_bytes is 1 MiB". The shipped default is 100 bytes (fluree-db-api/src/server_defaults.rs:31, "effectively reindex after every commit"). The direction of the argument survives, but the number should match the code or name the deployment it came from.

// Chunked: one window used to be one transaction, which a wide
// source cannot fit under the novelty ceiling at any window size
// (see `transaction_json_budget`).
for chunk in chunk_nodes_by_size(live_doc, txn_budget) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fluree-db-api/src/graph_source/r2rml_materialize.rs:460 — Blocking (test coverage). The new chunking has no test that reaches it, so this commit lands in exactly the seam round-1 blocker #4 was about.

The five new tests are good unit tests of chunk_nodes_by_size / chunk_iris_by_size, and I confirmed they are not decorative: removing the if !current.is_empty() suppression from both chunkers turns chunk_nodes_empty_yields_no_chunks red while everything else stays green. That guard is real, and the reasoning in its comment is right.

But nothing exercises the call sites. I reverted all four of them to their pre-delta unchunked form (if !live_doc.is_empty() { upsert(...) } and friends), left the helpers and their tests untouched, and re-ran: 37/37 green, across the lib unit tests and the whole grp_graphsource materialize set. grep -rn "materialize_r2rml_graph_source" still finds no test caller anywhere — only fluree-db-server/src/routes/iceberg.rs:288,403 and fluree-db-api/src/materialize_worker.rs:328.

This is the fourth behavior commit on the branch whose subject matter no test can distinguish from its own bug, and the pattern is why NEW-1 could ship: a test that drove materialize_r2rml_graph_source against a small fixture and asserted more than one commit landed would have caught both the missing coverage and the ratio.

)
})?;
let manifest_list_data = self.storage.read(manifest_list_path).await?;
let manifest_entries = parse_manifest_list(&manifest_list_data)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fluree-db-iceberg/src/scan/send_planner.rs:219,226 — B1, the merge-on-read guard. Still parse_manifest_list + is_deletes() { continue; }, mor_guard.rs absent, mergeable: false. Nothing to re-argue — the author's finding that the rebase produces a compile error rather than a conflict (cannot find function parse_manifest_list, because #1520 restructured it away) is the right read, and resetting the branch rather than pushing a rebase that hid it was the right call.

}
}

let mut accum = MaterializeAccum::default();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fluree-db-api/src/graph_source/r2rml_materialize.rs:232,333,359-373 — B2 proper. MaterializeAccum still retains one SubjectNode per distinct (target, graph, subject) for the whole pass, and by_target still holds every target's finalized JSON-LD at once before the first commit. Transaction chunking sits downstream of both.

@@ -8,8 +8,8 @@ use fluree_graph_ir::{Graph, Term, Triple};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

B4's engine half, unchanged; the query path still never reads SubjectMap::graph_map, so virtual and materialized views of the same source still disagree about where triples land.

/// - [`FullUndeterminable`](Self::FullUndeterminable) is **a configuration
/// problem to fix**. Retention is shorter than the poll interval, or the job
/// was stopped for longer than retention. A full read still produces correct
/// data, so this deliberately does not fail — but it must be visible, because

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More of a question than a suggestion. The doc says FullUndeterminable "left alone it repeats every poll forever and never self-heals", and I think that's true for one of the two causes you name but not the other. A successful full read advances the watermark to the current snapshot (r2rml_materialize.rs:522-531), so for "the job was stopped for longer than retention" a single completed pass repairs it and the next poll is incremental. It's only "retention is shorter than the poll interval" that recurs indefinitely. That distinction seems worth having in the log line too, since it's the difference between an operator waiting one cycle and an operator changing a retention setting.

})
.buffer_unordered(concurrency)
// One file's `Result<Vec<ColumnBatch>>` becomes individual
// `Result<ColumnBatch>` items; a read error becomes one error item.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, and I don't think it matters. The flat_map arms each build a Vec<Result<ColumnBatch>> so the two branches unify, which is a real allocation but a per-file one, not per-row — so it's nowhere near the hot path this PR should worry about. futures::future::Either would avoid it if you're ever in there anyway. Mentioning it only so it's on the record as considered rather than missed.

format!("{graph_source_id}\u{1f}{:016x}", config_fingerprint(config))
}

/// Why a materialize poll reads added files only, or re-reads the whole table.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • fluree-db-api/src/graph_source/r2rml.rs:73-140 (f539a4378) — this one I'd take more or less as written, and I'd say that even if it were the whole PR. Collapsing three distinguishable situations into one boolean and throwing away the error that separates them is a real defect with a real cost, and the four-variant enum is exactly the right shape for it. The log levels are correctly proportioned. meta_with_chain building fixtures through the real TableMetadata::from_json_str rather than a struct literal is the right call and the comment says why. And the mutation you claim in the body is true — I collapsed Err(e) into FullUnsafeWindow and got exactly the three failures you said I would.

/// compaction on the cheap incremental path while staying correct across
/// updates/deletes.
/// Yields batches rather than collecting them, so a consumer that processes and
/// drops each batch never holds the whole table in memory.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • fluree-db-api/src/graph_source/r2rml.rs:894-899 (4e09f8ee3) — removing scan_for_materialize rather than leaving it beside the streaming variant, and saying "make the safe shape the expressible one" as the reason, is the right instinct. A collecting method that nobody should call does eventually get called.

christophediprima and others added 13 commits August 6, 2026 14:30
Adds the read half of incremental materialization:
- SendScanPlanner::plan_incremental(from, to): the data files ADDED in a
  (from, to] sequence-number window (live entries whose effective data
  sequence number > from.sequence_number), reusing the existing manifest walk.
- SendScanPlanner::plan_scan_with_selection: full scan at a chosen snapshot.
- effective_sequence_number(): Iceberg null/0 seq inheritance from the manifest.
- TableMetadata::snapshot_window / window_is_append_only: parent-chain ancestry
  walk + append-only detection, so the materialize layer can fall back to a full
  re-read when the window has overwrite/delete/replace (updates/deletes the
  added-files scan can't see) or from is not an ancestor of to.

Unit tests cover seq-number inheritance, the ancestry walk (incl. branch/expired
errors), and append-only detection. Row-level delete-file (v2 MoR) support is
future work.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds, on FlureeR2rmlProvider:
- prepare_iceberg_scan(): shared setup (REST/Direct × GCS/S3 × creds × metadata cache).
- read_scan_tasks(): bounded-parallel Parquet read of a task set.
- current_snapshot_id(): the source table's current snapshot (materialize 'to' point).
- scan_table_incremental(from, to): scans only data files ADDED in the snapshot
  window, via SendScanPlanner::plan_incremental.

These back the materialization layer. NOTE: scan_table still inlines the same
setup/read (TODO dedup once the incremental path is verified end-to-end).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…tracking worker

Materialize an R2RML/Iceberg graph source into a native Fluree ledger so
native features (BM25, vector/RAG, reasoning) can run over external tables.

- Engine: Fluree::materialize_r2rml_graph_source(source, target, force_full)
  reuses the query-path R2RML term materializers (subject-IRI parity),
  aggregates one JSON-LD node per subject, and upserts into the target ledger.
- Incremental: scan only files added in the (from, to] snapshot window when it
  is append/compaction-only (TableMetadata::window_is_incremental_safe);
  overwrite/delete or expired/branched history fall back to a full re-read.
  Compaction (replace) stays incremental because Iceberg preserves each row's
  data_sequence_number, so the sequence-number window excludes rewritten rows.
- Watermark persisted in the target ledger (string-encoded snapshot id),
  written atomically in the same upsert; a no-delta poll commits nothing.
- Tracking worker (MaterializeTrackingWorker): a Send polling task spawned on
  non-peer nodes that keeps tracked source->target jobs fresh on an interval.
- Routes: POST /v1/fluree/iceberg/{materialize,track,untrack},
  GET /v1/fluree/iceberg/tracking.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…zation

Extend materialization with change-data-capture semantics so a materialized
native ledger tracks source updates and deletes, not just inserts.

- DeleteConvention { column, deleted_values: Vec<Option<String>> } on
  IcebergGsConfig: a row is a delete when its column value is in deleted_values;
  a null entry matches a NULL column (Debezium null-payload). Threaded through
  the create builders + /iceberg/map route; validated at graph-source creation.
- order_by column enables latest-by-key: per subject the highest-ordered row
  wins (value-orderable int/date/timestamp only, enforced) with a whole-subject
  replace that clears fields dropped in a newer revision; a tombstone retracts
  the whole subject via a typed-@id wildcard update. Two ordered commits keep the
  watermark advancing only in the upsert (crash/failure self-heals next poll).
- Per-(source,table) watermark with an injective subject; each table is read once
  with its own (from,to] window. Dual-mode: with neither delete nor order_by set
  the pass is the legacy additive merge (unchanged). Fails loud on a
  non-orderable order_by column or multiple triples maps per table.
- term.rs exposes column_string / batch_has_column / column_sort_key /
  column_is_orderable. subjects_retracted on MaterializeResult / route / worker.
- Docs: a "Materialization" guide in docs/graph-sources/iceberg.md plus the
  materialize/track/untrack/tracking endpoints in docs/api/endpoints.md.
- Tests: latest-by-key ordering + retraction-doc-shape unit tests, and an
  end-to-end integration test proving retraction actually deletes (with a control
  proving the earlier bare-string form was a silent no-op).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A static bearer for a Google Iceberg REST catalog (BigLake) is a short-lived
OAuth access token: it expires after ~1h and `BearerTokenAuth` cannot renew it,
so a long-running materialization tracking worker starts returning 401s.

Add `AuthConfig::GoogleMetadata` + `GoogleMetadataAuth`, which mints and
auto-refreshes tokens from the GCE/GKE instance metadata server (Workload
Identity), mirroring the existing `OAuth2ClientCredentials` cache+refresh — the
jittered-expiry `CachedToken` is now shared via `auth::token`. Wire it through
`{Iceberg,R2rml}CreateConfig::with_auth_google_metadata` and the `/iceberg/map`
`auth_google_metadata` field.

The GCS reader's storage HMAC keys are unaffected (static, non-expiring). The
metadata server is only reachable on GCE/GKE; local runs keep using a static
`auth_bearer`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
When several graph sources materialize into one target ledger (a shared
knowledge graph, a join table that only adds an edge to a parent entity, or an
entity_type-style table adding a secondary class), their classes must UNION, not
clobber. Additive-mode materialize now asserts `rdf:type` via an idempotent
`insert` and upserts only the non-type predicates, so classes accumulate across
sources instead of the last writer replacing them per predicate.

A `rr:predicate rdf:type` object map is routed to the subject's `@type` (the
union path) rather than treated as an ordinary predicate. This is the only way
to express per-row, data-driven typing, since `rr:class` is constant-only; as an
ordinary predicate it would be upserted and clobber other sources' classes.

Tests: type-union + single-upsert-clobber-control integration tests, and a
build_live_node unit test for the rdf:type-POM-as-class routing. Docs updated
(docs/graph-sources/iceberg.md).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… v4.1.3

Rebasing this branch onto current upstream surfaced API drift a textual merge
could not detect:

- `LoadTableResponse` gained a `metadata` field — set `None` on the Direct
  metadata-location cache-hit path in `prepare_iceberg_scan` (r2rml.rs).
- The `IcebergConnectionConfig` refactor moved the auth builders to delegate to
  the connection; re-add `with_auth_google_metadata` on `IcebergCreateConfig`
  (config.rs), consistent with `with_auth_bearer` / `with_auth_oauth2`.
- Upstream's redaction tests construct `IcebergGsConfig` and match `AuthConfig`
  exhaustively; cover the new `delete` / `order_by` fields and the
  `GoogleMetadata` variant (ledger_info.rs).
- fmt normalization of the resolved re-export list (lib.rs).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…hMap)

The materializer only ever wrote the default graph — rr:graphMap/rr:graph were
vocab constants but unparsed and unused. Honor a subject-map-level graph map so
each source row's triples land in a per-row named graph (constant, column, or
template over the row's columns); no graph map keeps the existing default-graph
behavior.

This lets the SAME subject IRI carry independent per-graph statements: when one
real-world entity is contributed by several partitions of a source (e.g. the
same actor/article under different tenant/user ids), a shared subject in one
graph makes per-predicate upsert last-writer-wins across partitions. Routing
each partition's row into its own named graph (e.g. .../tenant/{t}/user/{u}) is
the RDF-native provenance/override boundary and the basis for graph-scoped read
isolation over a shared materialized twin.

No transaction-core changes — named graphs are already first-class (flakes carry
a graph id, staging keys on (GraphId, Sid), and generate_upsert_deletions scopes
retract-existing by graph_id):

- fluree-db-r2rml: a GraphMap term map (rr:graph constant shortcut, or
  rr:graphMap [ rr:template | rr:column | rr:constant ]) parsed onto SubjectMap;
  materialize_graph_from_batch resolves the per-row graph IRI, reusing the
  subject materializer's template/column expansion.
- fluree-db-api (r2rml_materialize.rs): the accumulator keys on (graph, subject),
  so the same IRI in two graphs is two independent keys. Live nodes are emitted
  with a per-node "@graph" STRING selector ({"@id":s,"@graph":"<g>",...}) — the
  named-graph form parse_insert/parse_upsert accept (they resolve the graph per
  node and scope every triple to it); default-graph nodes and the materialization
  watermark stay plain top-level. The JSON-LD ENVELOPE {"@id":g,"@graph":[...]}
  (an @graph ARRAY) is NOT accepted by insert/upsert — its @graph key is skipped
  and the wrapper collapses to @id-only — only the UPDATE parser reads a top-level
  graph key. Whole-subject retraction is scoped per graph via that UPDATE graph
  key; the upsert's own retract-existing is already graph-scoped. Additive
  @type-union and per-predicate upsert now apply within each subject's graph.

Tests: rr:graphMap/rr:graph parsing; (graph, subject) isolation of the same IRI
across graphs (record + merge_live); graph-scoped retract doc; per-graph doc
flattening; and an end-to-end round-trip through the real transaction parser
(it_materialize_named_graph) that inserts/upserts the emitted per-node "@graph"
shape into a memory ledger, asserts it lands in the named graph (not the default
graph) and stays isolated per graph, plus a control proving the envelope form is
rejected.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…er partition

The materialize/track `target` may now contain `{column}` placeholders (e.g.
`silver_{tenant_id}_{user_id}:main`), resolved per row from the source's own
columns, so ONE tracking job fans out into a separate native ledger per
partition (tenant,user). This is the isolation boundary for per-user access:
Fluree's read policy is graph-blind and the docs recommend separate ledgers for
separate access regimes, so isolation rides the existing per-ledger bearer-scope
rather than making a named graph an authorization axis. A placeholder-free
target keeps the existing single-target behavior — fully backward compatible.

- Per-row target resolution reuses `expand_template_from_batch`; a row whose
  template columns are null is skipped (it cannot be routed to a ledger).
- The latest-by-key accumulator keys on `(target, graph, subject)` (was
  `(graph, subject)`); the finalized state is grouped by target ledger and each
  target's retract / @type-insert / predicate-upsert runs as its own commit
  chain, creating the ledger on first sight (correct for append-only CDC).
  Named-graph routing (rr:graphMap) still applies orthogonally within a target.
- The per-(source, table) watermark moves OUT of the target ledger into a shared
  `fluree_materialize_state:main` ledger, keyed (source, target-spec, table) —
  one watermark per source table for a fan-out job (a single scan feeds all its
  targets), and read BEFORE the scan (targets are discovered from rows, so the
  watermark cannot live in a not-yet-known target). Advanced AFTER every target
  data commit so a crash re-reads the window (safe: writes are idempotent). This
  removes bookkeeping triples from user data and unifies plain + templated jobs
  on one generic, job-linked state location.

Tests: +record_isolates_same_subject_across_targets (same IRI in two target
ledgers = two independent keys); watermark helpers keyed (source, target-spec,
table) with a 3-segment injectivity test; single-target + named-graph suites
still green (19 unit + 8 materialize-integration). `--features iceberg`; fmt +
clippy (-D warnings) clean.

Docs: docs/graph-sources/iceberg.md + docs/api/endpoints.md updated — document
the templated target / fan-out, and correct the (now stale) "watermark in the
target ledger" language to the shared fluree_materialize_state:main state ledger.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A type-only source (e.g. an r2rml `entity_type` map: subject + rdf:type,
no other predicates) splits into a @type node and NO predicate node, so
the additive-mode predicate document is empty (`[]`). The materialize
loop upserted it unconditionally, and the transactor rejects an empty
upsert ("Upsert must contain at least one predicate or @type"). That
error aborts the sync BEFORE its per-(source,table) watermark is written
(the watermark write is the last step), so the source never gets a
watermark: every poll full-rescans, re-inserts the same @type triples as
a fresh commit, and re-fails — the target ledger's `t` climbs on every
poll forever even though nothing in the source changed (pure churn).

Guard the additive-mode predicate upsert with `if !pred_doc.is_empty()`,
mirroring the existing `if !type_doc.is_empty()` guard on the @type
insert: a type-only source now commits its classes once and advances its
watermark, so subsequent polls short-circuit (0 rows) with no commit.

Also guard the latest-by-key upsert the same way: a delete-only window
(tombstones, no live rows) leaves the live doc empty; the retracts have
already applied, so skip the empty upsert rather than error.

Tests: +type_only_source_yields_no_predicate_upsert (a type-only
SubjectNode splits to a @type node + no predicate node, and the additive
predicate doc it produces is empty → caller must skip the upsert). Full
materialize suite green (21 unit tests); fmt + clippy (-D warnings) clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The materialize tracking worker kept its job set only in memory, and the
server never restored it: a restart silently stopped every
materialization until a client noticed and re-issued
`POST /iceberg/track`. Nothing surfaced the gap — `GET /iceberg/tracking`
reported the worker running with zero jobs, which reads exactly like
"nobody has tracked anything yet". For a fan-out job feeding a ledger per
(tenant,user), that is an outage that looks like an empty system.

Jobs now persist as `urn:fluree:materialize#Job` rows in the shared
`fluree_materialize_state:main` ledger — the store this worker already
owns, already writes on every committed poll, and that already carries
the job's source and target-spec on its watermark rows. The job is kept
as one serialized JSON blob (extensible without a schema migration, and
self-validating on read: only a string that deserializes into a whole
`PersistedMaterializeJob` is taken) plus duplicate `source`/`target`
triples so operators can query jobs with the same SPARQL they already
use for watermarks.

`MaterializeTrackingWorker::run` restores the set before its first tick.
Putting restore there rather than in the server's construction path
inherits peer-exclusion for free — peers never spawn a worker, and
`/iceberg/track` already 400s on them. Recovery is incremental: the
per-(source, target-spec, table) watermarks live in the same ledger and
are read by the materialize call itself, so a restored job re-reads
nothing it had already materialized.

`untrack` is durable too — it sets `tracked = false` rather than
retracting the row, which keeps an audit trail and avoids a delete path.
Restore filters on that flag.

Not the graph-source record, which would have been the cheaper mirror of
the BM25 worker's `tracked` flag: `IcebergGsConfig` has no catch-all
field and both create paths serialize a fresh struct, so any key written
there is dropped on the next config write; and `rest_client_cache_key`
hashes the raw config JSON, so writing to the record would discard the
cached catalog client and its OAuth token on every change.

Also fixes a latent race the new writes would have made hotter: opening
the state ledger was a bare check-then-create, and the loser of a race
between two pollers got `LedgerExists` instead of a ledger, failing the
whole materialization pass. Both call sites now share one helper that
tolerates it.

Known limitation, unchanged in kind but now permanent: both background
workers spawn on every non-peer node. A restart used to clear duplicate
jobs in a multi-node deployment; persisted jobs will be restored by
every node. Leader-gating background workers remains the open follow-up
noted at state.rs:293-297.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ceiling

A materialize window became ONE transaction per target ledger, so a source
wide enough to exceed the ledger's novelty ceiling could never sync at all —
not slowly, never. `silver.observation` produced 702k rows = 75,964,480 B of
flakes against a configured 67,108,864 B ceiling and failed on every poll for
~34h. The error carried `current=0`, proving novelty was empty and the single
transaction was simply too large, so no amount of waiting or indexing could
ever have cleared it.

Raising `reindex_max_bytes` is the wrong lever: it is per-ledger with no
aggregate cap, so it multiplies by concurrently-hot ledgers, and no fixed
value is safe because a larger window breaches any of them.

Instead derive a per-transaction budget from that same ceiling and cut the
window into as many transactions as it needs, at all three commit sites (the
`latest_by_key` retract and upsert, and the additive insert and upsert),
threading the LedgerState through each.

The budget is measured in serialized JSON-LD bytes — cheap to estimate here —
while the ceiling is in flake bytes. JSON-LD text runs several times larger
than the flakes it yields (~108 flake-bytes per row against JSON nodes of a
few hundred bytes), so budgeting JSON at a quarter of the flake ceiling errs
in the safe direction. Over-chunking costs almost nothing: reindex_min_bytes
is 1 MiB, so the indexer drains novelty between chunks instead of letting it
accumulate toward the ceiling.

Splitting is only sound because `nodes_by_graph_to_doc` emits self-contained
nodes — a named-graph node carries its own `@graph` string selector, so graph
scoping travels with the node and never depends on its neighbours. A test
pins that, since moving to an envelope form would silently drop graph scoping
and cross-write tenants' graphs.

Tests also pin the properties that would corrupt data if broken: empty input
yields NO chunks (an empty upsert is rejected by the transactor, which aborts
the sync before its watermark advances and makes the next poll re-fail
forever), every node survives in order (materialize is a whole-subject
replace, so a dropped node leaves a subject retracted and not re-asserted),
a node larger than the whole budget is sent alone rather than dropped, and
retraction chunks cover every subject exactly once.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… a full table read

`scan_for_materialize` chose incremental vs full with one expression:

    let incremental = from_snapshot_id.is_some()
        && metadata.window_is_incremental_safe(from, to).unwrap_or(false);

`unwrap_or(false)` collapses three different situations into one boolean and
throws away the error that tells them apart. That matters because the branches
are not comparable in cost: the incremental path reads the files added since the
watermark, while the fallback reads the ENTIRE table into `Vec<ColumnBatch>` in
memory. A swallowed error therefore turns a few-MB read into an unbounded one,
and nothing logged which branch had been taken.

It cost a production outage. A source table's snapshot retention expired the
stored watermark, so `snapshot_window` returned `SnapshotNotFound`,
`.unwrap_or(false)` rendered that as "not safe", and every poll re-read the whole
table. On a 728,876-row source the process reached 21.4 GiB of anonymous memory
and was OOMKilled every 8-17 minutes. Observed: 16 full-scan plans, 0
incremental. Because both branches were silent, the symptom presented as "Fluree
uses all the memory" and took days to attribute.

Replace the boolean with `ScanChoice`, which keeps the distinction the boolean
destroyed:

  Incremental          append/replace-only window; added-files scan is complete
  FullInitial          no stored watermark — first run, expected once per source
  FullUnsafeWindow     overwrite/delete in the window; a full read is CORRECT
  FullUndeterminable   safety unknown (expired/unknown/non-ancestor snapshot),
                       carrying the reason

The behaviour is deliberately unchanged: all three Full* variants still do a full
read, because a full read is the only thing that yields correct data once the
watermark is unusable. What changes is that they are now distinguishable, and
logged accordingly — the routine cases at `info`, `FullUndeterminable` at `warn`
naming the underlying error and the two configurations that cause it (retention
shorter than the poll interval, or a job stopped for longer than retention).
That is the difference between diagnosing this in one log line and in three days.

Six tests, built through the real `from_json_str` deserializer rather than a
struct literal. The expired-watermark case is the regression test; reintroducing
`unwrap_or(false)` semantics (collapsing `Err` into `FullUnsafeWindow`) fails
three of them, verified by mutation.

Not fixed here, and worth stating: a full read is still unbounded in memory. This
makes the escalation visible, not cheap. Bounding the read is a separate change.

fluree-db-api: 877 passed. fmt and clippy --all-features --all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
christophediprima and others added 10 commits August 6, 2026 14:37
…veltyWouldExceed

The backpressure retry added in 060db6e handled `NoveltyWouldExceed` and let
`NoveltyAtMax` fall through as fatal. In production that made the whole fix INERT:
a forced full re-materialize failed instantly on all 17 sources with "Novelty at
maximum size, reindexing required", and the split path logged **zero** times —
74 `NoveltyAtMax` against 0 `NoveltyWouldExceed`.

The two are the same condition observed at different moments, and the enum gives
no hint they belong together:

  NoveltyWouldExceed{current,delta,max}  the transaction was SIZED and rejected.
                                        Splitting reduces `delta`, so it can help.
  NoveltyAtMax                          novelty is already at the ceiling, raised
                                        BEFORE sizing — which is why it carries no
                                        numbers. No chunk is small enough; only the
                                        indexer draining helps.

So they need opposite responses, and collapsing them would be its own bug:
splitting on `NoveltyAtMax` would loop forever shrinking a chunk that can never fit.

Changes:

- `classify_novelty` + `NoveltyPressure` extracted as a named, testable function
  that the retry loop calls. `WouldExceed` splits; `AtMax` goes straight to the
  wait; anything else fails fast, because retrying a validation error forever is
  worse than erroring.
- The watermark write at the end of a materialize now goes through the same helper.
  It was a bare `upsert`, which is the most expensive possible place to give up on a
  transient condition: failing it discards the whole window's work and the next poll
  redoes all of it.

On the test, because the first two attempts at it were worthless. A canary that
defines its own copy of the classification passes happily while production
regresses — testing a replica is not testing the logic. This asserts against
`classify_novelty` itself, verified by mutation: deleting the `NoveltyAtMax` arm
from the production classifier fails the test. It also asserts the two variants do
NOT compare equal, so a future "simplification" that merges them is caught.

fluree-db-api: 883 lib, grp_graphsource 153. fmt and clippy --all-features
--all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…adence

The retry budget added alongside the `NoveltyAtMax` fix was 12 waits x 5 s = 60 s
per stalled chunk. That number was a guess, and measuring it showed the guess was
wrong by enough to make the retry useless.

Novelty for a ledger cannot drain faster than that ledger's own next index build.
Measured on a live deployment — interval between consecutive index builds of the
SAME ledger, 31 samples over 30 minutes across 22 ledgers:

    min 7 s    median 144 s    p90 174 s    max 202 s

So a 60 s budget was ~2.4x too small at the median: most stalled chunks would have
exhausted it and errored, which is precisely the failure the retry exists to
prevent. The fix would have looked correct in tests and failed in production for
the second time.

Raised to 72 x 5 s = 360 s, covering the observed max with ~1.8x headroom, and made
it overridable via `FLUREE_MATERIALIZE_MAX_DRAIN_WAITS` for deployments with a
slower indexer.

Note the budget is PER STALL, not per materialize: `drain_waits` resets on every
successful chunk, so a long window that keeps making progress is never capped. The
bound only bites when nothing is draining at all, which is the case that should
surface as an error.

fluree-db-api: 883 passed. fmt and clippy --all-features --all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…instead of waiting

Two changes, both validated against the real silver dataset locally.

C3 — SNAPSHOT-ID MOVEMENT IS NOT WORK.

The no-delta short-circuit required `all_watermarks_unchanged`, which made it almost
never fire: the watermark is the source's Iceberg snapshot id, and the upstream Kafka
sink bumps that 37-72 times an hour per table whether or not any row concerns us. So a
poll that read NOTHING still wrote a watermark commit. Seventeen sources at a ~50 s
interval produced ~1,200 commits/hour of two-triple payloads into the shared state
ledger, which reached 27,179 commits against 3 index roots, saturated its novelty, and
— because the watermark write is the LAST step of every materialize — halted every
sync in the deployment.

Now a watermark persists when rows were applied, or when the window has aged past
`watermark_refresh_bound_ms` (30 min default, `FLUREE_MATERIALIZE_WATERMARK_REFRESH_MINS`).

That bound is what makes skipping SAFE, and it is the part to preserve: a watermark
that never advances eventually falls outside the source's snapshot retention (4 h
here), `snapshot_window` can no longer resolve it, and every poll degrades to a FULL
table read. One source reached exactly that state and full-read 739,446 rows per poll.
The bound is tested as a RATIO against retention rather than a bare number, so raising
it forces the relationship to be confronted.

Window age comes from Iceberg's own snapshot timestamps via a new `MaterializeScan`
struct — a struct rather than a tuple because a positional return makes it easy to drop
the field silently, which reintroduces exactly the staleness this prevents.

C5 — DEFER, DO NOT WAIT.

The in-process sleep-and-retry added for `NoveltyAtMax` caused a production deadlock:
only the INDEXER can drain novelty, and the materialize worker holds what the indexer
needs to publish. Sleeping therefore guaranteed the awaited condition could not clear —
the indexer produced ZERO builds for six minutes and recovered only when the wait was
disabled. A larger budget makes that worse, not better.

So `NoveltyAtMax` now returns `ApiError::NoveltyDeferred` immediately, releasing
everything; the worker's own 30-57 s poll interval is the backoff. `NoveltyWouldExceed`
still splits and retries in place, because that path never sleeps and splitting reduces
the rejected size. The distinction lives in `classify_novelty`, mutation-verified.

A deferral is NOT a failure: it is a distinct error variant mapped to 503, counted in a
new `syncs_deferred` stat and surfaced in `/iceberg/tracking`. Lumping deferrals into
failures is how 1,050 of them once presented as an outage and hid the real cause.

Also removes `all_watermarks_unchanged`, dead after C3, and the drain-wait budget with
its `FLUREE_MATERIALIZE_MAX_DRAIN_WAITS` override.

LOCAL VALIDATION (real BigLake silver, 17 sources, fan-out per tenant/user):
- state-ledger commits ~3.4/min at a 3 s poll, against ~1/source/poll before
- `incremental (added-files)` plans tracked completed syncs EXACTLY (0->1->3->3->5->5),
  so watermarks still advance when work happened — a broken C3 would show zero
- zero `CANNOT DETERMINE incremental safety`, i.e. no staleness regression
- with the ceiling lowered: 9 deferrals and 56 splits while indexer builds rose
  230->517 and syncs 12->30. The indexer never stalled, which is the specific failure
  the sleeping version caused.

fluree-db-api 885, fluree-db-server 150. fmt and clippy --all-features --all-targets
clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… job

Each resolved target is an independent commit domain — its own novelty ceiling, its
own index, its own ways to be broken. Aborting the whole job on the first bad one is
how a SINGLE truncated dict pack in one ledger produced 208 identical failures across
all 17 sources in 20 minutes, while 21 healthy targets received nothing.

Worth being precise about what this changes: the loop ALREADY commits per target as it
goes, so partial application was always the reality. What was missing is recording
which targets succeeded. This does not introduce partial writes — it stops discarding
the knowledge of them.

The per-target body moves into `materialize_one_target`, so every `?` scopes to one
target, and the caller collects an outcome per target: ok / deferred / failed.

WATERMARK SEMANTICS, which is the subtle part. The watermark is still SHARED across
targets (per-target watermarks are a separate change), so it must NOT advance while any
target is behind — that would skip this window for them permanently. Successful targets
keep their data; the window is re-read next poll and re-applied idempotently. So the
gain here is "healthy targets get their data now" rather than "progress is durable";
the latter needs per-target watermarks.

Failure outranks deferral when choosing what the job reports: a deferral self-heals on
the next poll, a failure usually needs attention, and reporting the milder of the two
would bury it.

THE RISK THIS CARRIES, stated plainly: making failures non-fatal can turn a loud
outage into a quiet divergence — 21 successes and one target broken for days. The
mitigation is that a failing target is logged individually with its own `warn!` naming
it, not merely counted, and the job's error reports "N of M targets failed" with the
first failure attached. Aggregate-only reporting would have made this change net
harmful, and a repeated-failure escalation is still worth adding.

fluree-db-api: 885 lib, grp_graphsource 153 (exercises the refactored per-target path).
fmt and clippy --all-features --all-targets clean.

Not yet validated against a real per-target failure — the local harness is the only
place that can force one, and that is the next step.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`ledger_exists` then `create_ledger` is check-then-create, and it is not atomic.
Under fan-out this races constantly: 17 sources resolve the SAME ~22 targets, so when
a target is new several sources see it missing in the same instant and all try to
create it. One wins; the losers failed the entire target.

This is not a new discovery. `materialize_state_ledger` in the same file already
documents and handles it:

    Tolerates losing the create race: two concurrent pollers (or a poller and a
    `track` call) can both see it missing, and the loser gets `LedgerExists` rather
    than a ledger. Before this existed the same check-then-create sat inline in the
    watermark write and could fail a whole materialization pass on that race.

The fix was applied to the state ledger and never to the target path — which is where
fan-out makes it far MORE likely, because there are 22 targets rather than one and
every source resolves all of them. Observed locally as
`Commit conflict: expected t=2, head_t=1`, t=1 being the signature of a just-created
ledger.

The loser now opens the winner's ledger and continues, and reports it as EXISTING
rather than created-by-us. That choice is deliberate: it does exist now, and for
latest-by-key it routes through the whole-subject retract before re-asserting. On a
ledger the winner has only just created that retract is very likely a no-op, so the
cost is at most one redundant transaction — whereas skipping a retract that WAS needed
would leave stale fields behind. Erring toward the harmless side.

Scope, stated honestly: this explains the low-`t`, small-gap conflicts (`expected t=2,
head_t=1`, gaps of 1-2). It does NOT explain every instance — one had
`expected t=21, head_t=5`, a gap of 16, which a creation race does not obviously
produce. Concurrent writers to a shared target remain structural under fan-out and are
not fully diagnosed.

Also fixes two reporting defects in the deferral added earlier:

- `NoveltyDeferred` mapped to 503 on `ApiError::status_code()`, but the HTTP layer uses
  `ServerError`'s own mapping, so the 503 was dead code and a deferral surfaced as
  `500 err:system/InternalError` — telling operators that ordinary capacity pressure was
  an internal server error. Now 503 with a distinct `err:db/NoveltyDeferred` type.
- The message said "(will retry)". True for the tracking worker, FALSE for a one-shot
  `/iceberg/materialize`, which retries nothing. It now says which is which.

Tests: a canary asserting create-race tolerance exists on BOTH paths (a real two-writer
race needs a concurrent harness this module lacks, and the failure mode is silent until
fan-out hits a new target, so the canary earns its place).

fluree-db-api 886, grp_graphsource 153, fluree-db-server 150. fmt and clippy
--all-features --all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…nflict

`CommitConflict`'s fields read the OPPOSITE way to their names, and misreading them
sent this investigation down the wrong path for two days.

From `verify_sequencing` in fluree-db-transact:

    expected_t = record.commit_t   -> the NAMESERVICE's durable head
    head_t     = base.t()          -> OUR in-memory base

So `expected t=21, head_t=5` does NOT mean "we expected the head to be further along".
It means our base was SIXTEEN COMMITS BEHIND the durable head — a textbook lost update.
The conflicts were documented as "direction unexplained, possibly something exotic"
until the raise site was finally read.

With that understood, the cause is ordinary and structural: 17 sources resolve the same
~22 targets, so while one source works through its chunks the others commit to the same
ledger. The gap is just how many they managed. Observed gaps: 1, 2, 4, 16 — all
consistent, none exotic.

The remedy is the standard one, which was unreachable while the cause was believed
strange: on `CommitConflict`, reload the ledger and retry the chunk. Bounded to 10
reloads per call, because a target under permanent write pressure should surface rather
than spin — and C4 isolates it to that target either way.

This complements rather than replaces the create-race fix: `LedgerExists` tolerance
covers ledger CREATION, this covers ledger WRITES.

A test pins the field order with the exact production shape (`expected=21, head_t=5`,
gap 16) and states in its own comment why it exists, so the misreading is not
re-derived. `MATERIALIZE_FANOUT_REDESIGN.md` is corrected too — the previous entry
asserted the opposite direction and is now marked as wrong with the reasoning.

Method note worth keeping: whenever a diagnosis rests on interpreting an error's
FIELDS, read the raise site. Field names are documentation, and documentation can
mislead; three minutes in `verify_sequencing` would have settled this immediately.

fluree-db-api: 887 passed. fmt and clippy --all-features --all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`/iceberg/track` awaited an "immediate first sync" and `?`-propagated its error. Both
halves were wrong, and the error half is the more damaging.

THE JOB IS ALREADY DURABLE BEFORE THE SYNC RUNS. Registration puts it in the worker and
persists it to the state ledger; only then does the first sync happen. So the sync is a
latency optimisation, not part of the operation — yet:

  * `?` on its error made the call report failure for a job that WAS registered and
    persisted. A first sync losing a commit race produced
    `track ERROR: Commit conflict: expected t=2, head_t=1`, which an operator
    reasonably reads as "tracking did not happen". It had.
  * awaiting it made `track` cost a full materialize. Bootstrap check-then-skips, so on
    a restart this is a no-op — but on a FRESH VOLUME nothing is tracked, all 17 sources
    register, and each blocks on a full read. Seventeen backfills serialised inside pod
    startup, which is exactly the shape of a planned PVC reset.

Now the first sync is spawned and its outcome logged, and the response separates the two
concerns: `tracked` (durable, always true here) from `first_sync`
(`started` | `completed` | `failed`), with `first_sync_error` carrying the reason when it
fails. It never fails the call.

`wait_for_first_sync: bool` (default false) restores the old blocking behaviour for
callers that want the numbers in the response — tests, or a one-off manual run on a small
source. Even then a failure is reported rather than fatal.

`initial` becomes optional and is omitted unless the caller waited. Both existing
consumers already tolerate that: `bootstrap.sh` pipes it through `jq ... 2>/dev/null`,
and `e2e_full.sh` explicitly tests `!= "null"`.

Note this was never async — the synchronous sync dates from the feature's first commit
(3e86a1d), so nothing regressed; it is a design fix rather than a repair.

fluree-db-server: 150 passed. fmt and clippy --all-features --all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…g first syncs

Two findings from a local run against the real dataset, one of them a regression I had
just introduced.

1. FOUR ERROR VARIANTS, ONE CONDITION.

Retrying only `CommitConflict` left its siblings fatal. After that fix the residual
target failures were **all** `PublishLostRace` — one per target, at low `t`, during the
initial backfill burst when every source writes every target. Same race, caught at a
different point in the commit path:

    CommitConflict     base.t() != nameservice commit_t, caught before publishing
    PublishLostRace    someone published while we were building, caught AT publish
    CommitIdMismatch   our base's head CID is not the nameservice's head CID
    NamespaceConflict  namespace allocation raced a concurrent staging registry

Where staleness is detected is an implementation detail of the commit path, not
something a caller should branch on, so `is_stale_base()` now classifies all four and
they share one remedy: reload the base, retry the chunk, bounded.

Measured before this change: 25 stale-base reloads absorbed (each previously a hard
target failure) and ZERO `Commit conflict` target failures, against 13-of-18
concentrated on one ledger beforehand. Gap distribution 14x behind-by-1, then 2, 3, 4,
7 — small gaps dominate, as concurrent-writer contention predicts.

2. MAKING THE FIRST SYNC ASYNC REMOVED AN ACCIDENTAL BRAKE.

Spawning the first sync looked like the way to keep its latency benefit without
blocking. It is a trap: the tracking worker polls through a SERIAL outer loop, but
spawned tasks bypass that entirely. Registering 17 sources therefore launched 17
unbounded concurrent materializes, each holding the per-window accumulator — the one
memory term nothing currently bounds (~10 GiB for a single ~800k-row window). Measured
locally at 873 % CPU, i.e. ~9 cores, for what is meant to be background work.

The synchronous version had been providing that serialisation by accident. Removing the
await must not also remove the brake — so the first sync is no longer spawned at all;
the worker picks the job up on its next tick under its own serialisation. First-sync
concurrency now equals the worker's, which is the only place it is bounded.

Cost: up to one poll interval before data appears (30 s default, and a caller can pass
`poll_interval_secs` to shorten it). `first_sync: "scheduled"` reports this, and
`wait_for_first_sync: true` still runs it inline for a caller that wants the numbers.

This regression was caught by an operator noticing CPU, not by any test — worth noting,
because "background work" that bypasses the only concurrency bound in the system is not
something the current tests can see.

fluree-db-api 887, fluree-db-server 150. fmt and clippy --all-features --all-targets
clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The unit of fan-out materialize work is the TARGET ledger, not the poll. One job
resolves to N independent commit domains, each of which can commit, defer on novelty
backpressure, or fail on its own. Every existing counter was measured in polls, so it
was measuring the wrong thing.

What that cost: a production window with 21 of 22 targets committing was reported as one
`NoveltyDeferred`, so the worker recorded ZERO commits and one deferral. Read off
`/iceberg/tracking`, a healthy deployment writing 21 ledgers every poll was
indistinguishable from one writing nothing — and I diagnosed it as a stall within
minutes of deploying, because the stats said so.

The count was not merely dropped, it was UNREPRESENTABLE: the aggregation returned
`NoveltyDeferred { remaining }` or `Internal(String)`, and neither has anywhere to put
"21 targets succeeded".

So:

- `TargetTally { ok, deferred, failed }` with `total()` / `is_complete()`, carried on
  BOTH outcomes — `MaterializeResult` on the success path and the new
  `ApiError::MaterializePartial` on the mixed one — so a caller accounts for targets
  uniformly instead of inferring from which branch it landed in.

- `MaterializePartial` stays an `Err`, because the shared watermark IS held back and the
  window is NOT complete; a caller must re-poll. Its message leads with the ratio
  ("applied 21 of 22 targets"), since "deferred" alone is the word that read as a stall.
  `ApiError::target_tally()` recovers the counts without matching the variant.

- Deliberately NOT special-cased to `NoveltyDeferred` when `ok == 0`. That looked
  tidier and discards `tally.deferred` — the same loss this variant exists to prevent,
  just at the other end of the range.

- HTTP status follows WHY the window is incomplete, not the fact of it: deferral-only is
  503 (capacity, self-healing), any failed target is 500 + `err:db/MaterializePartial`.
  Answering 503 for a permanently broken ledger would tell callers to retry forever
  while reporting it as merely busy — the same mistake as the 500 a plain deferral used
  to return, in the other direction.

- `targets_committed` / `targets_deferred` / `targets_failed` accumulate across polls and
  are what to read for progress. A rising `targets_committed` beside a flat
  `syncs_committed` is precisely the fan-out steady state that previously had no
  representation. `syncs_partial` records incomplete windows separately: for a 22-target
  job that is normal, not an anomaly.

- The worker `warn!`s only when a target genuinely FAILED; an all-deferred remainder logs
  at `info`. Warning on routine backpressure trains operators to ignore warnings.

Credit assignment is extracted to `MaterializeWorkerStats::record_targets`, reachable
from a test without a live `Fluree` — the previous inline rule was never exercised.
Mutation-verified both ways: collapsing the status decision fails
`partial_window_status_follows_the_reason_not_the_partialness`; zeroing the ok-credit
fails both worker tests.

Also fixes a doc comment I had orphaned onto NOVELTY_DEFERRED, leaving INTERNAL
undocumented.

fluree-db-api 892 (+5), fluree-db-server 152 (+2). fmt and clippy --all-features
--all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…tadata arm

Finishes the 24-commit rebase onto `upstream/main` (452 commits of drift). Separate
from the replayed commits because every hunk here is a rebase-resolution artifact,
not a change of intent: nothing in this commit alters behaviour.

THE `parse_manifest_list` CORRECTION.

`send_planner.rs` needed one import added:

    -use crate::manifest::{parse_manifest, parse_manifest_list_with_deletes};
    +use crate::manifest::{parse_manifest, parse_manifest_list, parse_manifest_list_with_deletes};

That single line is the whole of what we spent three review rounds describing as
"fluree#1520 restructured `parse_manifest_list` away, so the rebase is blocked and there is
no mechanical resolution." @aaj3f refuted it in round 3 and was right:
`parse_manifest_list` is on `main` at `manifest/manifest_list.rs:153`, exported from
`manifest/mod.rs:21`, a one-line wrapper over `parse_manifest_list_with_deletes(data,
false)`. Our conflict resolution had taken main's import line while keeping our body,
and we then reported the resulting `cannot find function` as a fact about upstream's
code rather than about our own resolution. One `git show upstream/main:<path>` would
have settled it.

The rest:

- `auth/mod.rs` — `hydrate` gained a `GoogleMetadata` arm. Written OUT rather than
  matched by a wildcard, deliberately: that exhaustiveness is what forced an explicit
  redaction decision for this variant in fluree#1567, and a wildcard here would silently
  accept the next variant too.
- `graph_source/config.rs`, `graph_source/r2rml.rs`, `ledger_info.rs` — three
  functions/initializers left unclosed by a conflict that cut THROUGH a body. Both
  sides ended mid-expression and shared the closing `}`, so taking both halves left
  one closer for two items. Worth naming as a rebase hazard: a union is only safe
  when each side is a whole item.
- `graph_source/r2rml.rs` — upstream's `gs_config_json` auth fixture gained
  `delete: None, order_by: None`. Those fields are ours (`439908642`), so this is our
  breakage of their test, and it surfaced ONLY under `--all-targets`: `cargo check`
  does not build test targets. Same blind spot that took fluree#1567's first CI run down.
- `lib.rs` — export list unioned (`MaterializeResult`, `PersistedMaterializeJob` from
  us; `verify_storage_access`, `StorageAccessReport` from upstream).

NOTE — fluree#1529 HAS MERGED. `fluree-db-api/src/materialize.rs` is now on main (3,174
lines: `materialize_graph`, `WatermarkStamp`, `ImportSink`/`ParsedChunk` ingestion,
parity gate), so the bulk-import engine this PR was asked to converge onto is no
longer a draft. Our replay engine now sits beside it, and there are two watermark
concepts in one codebase. That is a design conversation, not a rebase problem, but it
changes what this branch should become.

PER-COMMIT COMPILABILITY IS NOT RESTORED. The 24 replayed commits are individually
bisect-hostile until these hunks are folded into the commits they belong to. Left as
one commit on purpose: this branch is headed for the four-way re-split, so
`rebase -i` to make a soon-to-be-decomposed history bisectable is poor value. Say the
word and it gets folded.

Verified at this SHA, 0 behind `upstream/main`:
  fluree-db-iceberg  --lib  266 passed
  fluree-db-api      --lib  1014 passed
  fluree-db-server   --lib  167 passed
  grp_graphsource           157 passed
  it_graph_source_r2rml     65 passed
  iceberg_track_durability  4 passed
  cargo fmt --all -- --check          clean
  cargo clippy --all-features --all-targets  clean (3 crates)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@christophediprima
christophediprima force-pushed the feature/iceberg-materialize branch from 4e09f8e to 4e48d39 Compare August 6, 2026 13:30
christophediprima and others added 2 commits August 6, 2026 15:36
…l (B1)

`plan_incremental` — the materialize path — bypassed the fail-closed merge-on-read
guard that `plan_scan` has carried since fluree#1520. Two ways, compounding:

1. No `mor_guard` call of any kind.
2. It parsed with `parse_manifest_list`, which filters `content=1` entries OUT. So the
   `if manifest_entry.is_deletes() { continue; }` inside the loop was **dead code** —
   it read as a delete-file safety check while being unreachable, which is worse than
   no check at all, because it looks like one.

Now mirrors `plan_scan` exactly: the zero-I/O summary check first
(`ensure_no_summary_deletes`), then parse WITH delete manifests so the backstop can
actually see them and `ensure_no_delete_manifests` can count them. The in-loop
`is_deletes()` skip now does the job its name claims.

WHY THIS IS WORSE ON THE MATERIALIZE PATH THAN ON A QUERY.

A query that reads a MoR table without applying its delete files returns deleted rows
once, to one caller, who can re-run it. Materialization writes those rows into a ledger
as committed state and then advances the watermark PAST the window — so nothing ever
re-reads it. A transient wrong answer becomes permanent wrong data, and the only repair
is a `force_full` that someone has to know to run. @aaj3f made exactly this point in
round 1 and it is the sharpest finding in either review.

THE `from = None` CASE IS THE HOLE.

`from_snapshot_id = None` means "since genesis" — a full read of `to`'s live state,
which is precisely the read `plan_scan` refuses on a delete-bearing snapshot. It is
also the initial-materialization path, so the very first build of a twin was the least
guarded thing in the pipeline.

`window_is_append_only` does not cover this: it is a CALLER contract (stated in this
method's own docs) and is not enforced here, so it cannot serve as the guard.

Three tests, all using `NoReadStorage` (errors on every read) so they also pin that the
refusal happens BEFORE any manifest-list I/O — matters on a path polled every 30-57 s:

  send_planner_refuses_delete_bearing_snapshot_incrementally  (windowed read)
  initial_materialization_from_genesis_also_refuses           (from = None)
  a_clean_snapshot_is_not_refused_incrementally               (no false positives —
      a copy-on-write table is the common case and must still plan)

Mutation-verified: removing both guard calls fails the first two by name and leaves the
third passing, which is correct — it asserts the guard does NOT fire.

The operator escape hatch is unchanged and shared: `FLUREE_ICEBERG_ALLOW_MOR_DELETES=1`
(`mor_deletes_allowed()`), same env var, same warn-once, same semantics as the query
path. Nothing new to learn, and no separate switch to forget.

fluree-db-iceberg 269 (+3), fluree-db-api 1014, fluree-db-server 167. fmt clean; clippy
--all-features --all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…t (B3, layer 1)

`materialize_r2rml_graph_source` had three callers in this repo and none was a test. That
is why replacing the streaming core with "yield nothing" left 954/954 green.

IT WAS NOT CARELESSNESS — IT WAS UNTESTABLE. Two reasons, both verified:

1. There is NO offline Iceberg fixture anywhere in the tree. Every graph-source
   integration test needs live infrastructure — a Polaris REST catalog
   (`it_graph_source_r2rml.rs`), LocalStack (`it_iceberg_direct.rs`) or MinIO — and
   nothing writes Iceberg metadata / Avro manifests / Parquet for a test.
2. The provider was hardcoded: the pass opened with
   `let provider = FlureeR2rmlProvider::new(self);`. No injection point at all.

So the fix is a seam, and the seam is small: the engine touches the provider at exactly
THREE call sites. `MaterializeSource` has exactly those three methods — a wider trait
would be easier to write and harder to fake honestly. `&dyn` rather than a generic
because the pass is ~400 lines and I/O-bound, so monomorphizing per provider buys nothing
measurable and would leak a type parameter into the per-target helpers.

The public method keeps its exact signature and delegates, so nothing the server does
moves. The production impl is straight delegation and adds no behaviour of its own.

SIX TESTS, and one of them corrected me. `an_empty_window_commits_nothing` first set
`window_age_ms: None` and asserted no commit — which has C3 backwards. `None` means
"first run, or the stored snapshot no longer resolves", and both must persist regardless,
or a quiet table's watermark ages out of Iceberg's snapshot retention. The test now pins
BOTH branches: fresh-and-empty commits nothing, stale-or-unresolvable persists anyway.

The rest: end-to-end rows into a target ledger; fan-out (one scan, two tenants, two
ledgers, `TargetTally { ok: 2 }`); an unroutable NULL-template row skipped rather than
misfiled into another tenant's ledger; and the chunking test below. Each asserts the fake
was actually pulled (`scans()`), which is the anti-theatre guard — a fixture that wires up
but is never read would otherwise "pass", which is exactly how the gutted scan left 954
tests green.

ACCEPTANCE BAR — MEASURED BOTH WAYS, INCLUDING THE HALF THIS DOES NOT REACH.

  M-1 (chunking) now FAILS, by name.
      Their mutation was not breaking `chunk_nodes_by_size` — its unit tests catch that.
      It neutralised chunking AT THE CALL SITE with the function intact. I reproduced that
      (`txn_budget = usize::MAX`) and got 1019 passed INCLUDING the first four engine
      tests, so the seam alone did not meet the bar. The comparative chunking test is what
      does: the same window under an unbounded budget and a 200-byte budget must reach
      different `t` on the target ledger.

  M-2 (gut `stream_scan_tasks`) STILL PASSES — 1020 green. Verified, not assumed.
      A fake source bypasses the real provider's scan by construction, so this covers
      nothing in `stream_scan_tasks` / `ScanChoice` / the incremental snapshot window.
      Saying so here rather than letting a reviewer find it: the last round's finding was a
      coverage claim that did not hold, and this one would be the same mistake.

Closing M-2 needs a storage seam plus a table fixture — `prepare_iceberg_scan` returns a
concrete `Arc<S3IcebergStorage>` (also at `:940`, `:991`) and `MemoryStorage` implements
only the non-Send `IcebergStorage`, while the scan path needs `SendIcebergStorage`. That
is layer 2 and it changes signatures in a file under review, so it is a maintainer
decision, not ours to take unilaterally.

`txn_budget_override` is a parameter only tests supply, which is a smell, and the
alternative was worse: the derived budget has a 1 MiB floor, so proving a window splits
across transactions otherwise needs ~24,000 rows — that version ran for minutes. An env
var would be process-global and flaky under parallel tests. Rationale is on the function.

fluree-db-api 1020 (+6), fluree-db-iceberg 269, fluree-db-server 167, grp_graphsource 157.
fmt clean; clippy --all-features --all-targets clean.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@christophediprima

Copy link
Copy Markdown
Contributor Author

Rebased, green, and B3 is in — plus one question for you

@aaj3f The rebase is done and CI can finally see this branch. feature/iceberg-materialize is 0 behind main, and everything that ran is green: test 10,664 passed, plus clippy, fmt, bench-paths, bench-compare and plan.

You were right about parse_manifest_list and I was wrong. It is on main at manifest/manifest_list.rs:153, exported from manifest/mod.rs:21, exactly as you said. The fix was one line — adding it to an import list in send_planner.rs. My "cannot be resolved mechanically" claim came from a conflict resolution that took main's import line while keeping our body, and I then reported that as a fact about your code rather than about my own resolution. One git show upstream/main:<path> would have settled it three rounds ago.

One red check needs your re-run, and it isn't code. testsuite-sparql failed inside GitHub's own "Prepare all required actions" step — action-download-info returned 500 then 503, so nothing was checked out or compiled. It also cannot be affected by this branch: it builds fluree-db-api with features = ["native"], which doesn't include iceberg, and both files I changed sit behind #[cfg(feature = "iceberg")]. I verified that job's other two steps (fmt --check, clippy --all-targets -- -D warnings) pass locally in that sub-workspace. I can't re-run it from a fork.

B3 — done, and the half of your mutation it does not reach

You were right that one test on materialize_r2rml_graph_source was worth more than the next three commits. Writing it turned up why it had never existed, which I think is more useful than the test itself.

It was not reachable. Two things, both of them ours:

  1. Every graph-source integration test in the repo needs live infrastructure — Polaris (it_graph_source_r2rml.rs), LocalStack (it_iceberg_direct.rs) or MinIO — and nothing in the tree writes Iceberg metadata / Avro manifests / Parquet for a test. So there is no way to reach the engine through the real provider offline.
  2. The pass opened with let provider = FlureeR2rmlProvider::new(self). No seam.

So the engine wasn't left uncovered by carelessness; there was nothing to cover it through. That reframes your finding rather than excusing it — the gap was structural, and a mutation was the only way anyone would have noticed.

Fixed with a three-method seam, because three is the entire provider surface the pass touches: compiled_mapping, materialize_options, and one scan window. &dyn rather than a generic — the pass is ~400 lines and I/O-bound, so monomorphizing per provider buys nothing and would leak a type parameter into the per-target helpers. The public method keeps its signature and delegates; the production impl is pure delegation.

Six tests now drive the engine: rows end-to-end into a target ledger, fan-out (one scan → two tenants → two ledgers, TargetTally { ok: 2 }), an unroutable NULL-template row skipped rather than misfiled into another tenant's ledger, and both branches of the watermark-freshness rule. One of them corrected me while I wrote it: I first asserted that an empty window never commits, which has the rule backwards — window_age_ms: None means "first run, or the stored snapshot no longer resolves", and both must persist or a quiet table's watermark ages out of snapshot retention. It pins both branches now.

Your two mutations, measured, including the one still green

M-1 (chunking) now fails by name. Worth noting your mutation was sharper than I first read it: breaking chunk_nodes_by_size is caught by its own unit tests, so you must have neutralised it at the call site with the function intact. I reproduced that (txn_budget = usize::MAX) and got 1019 passed including the first four new engine tests — so the seam alone did not meet your bar. What does is a comparative test: the same window under an unbounded budget and a 200-byte budget must reach different t on the target ledger.

M-2 (gut stream_scan_tasks) still passes — 1020 green. I verified that rather than assuming it. A fake source bypasses the real provider's scan by construction, so these tests cover nothing in stream_scan_tasks, ScanChoice, or the incremental snapshot window. Last round you caught a coverage claim of mine that didn't hold; I'd rather state this one myself than have you find it.

The question

Closing M-2 means being able to run the real scan path with no catalog. I sized it and stopped, because it touches your surface, not mine:

  • prepare_iceberg_scan returns a concrete Arc<S3IcebergStorage> (and the scan helpers take &Arc<S3IcebergStorage> at :940, :991), so the storage type would need to become Arc<dyn SendIcebergStorage>.
  • MemoryStorage implements only the non-Send IcebergStorage; the scan path needs SendIcebergStorage, so it needs that impl too.
  • Then a minimal Iceberg v2 table fixture — metadata.json, an Avro manifest list, an Avro manifest, one Parquet file — built into memory.

The pitch isn't "we need it for our test." It's that the repo has no way to test any Iceberg scan offline, and this would give plan_scan, plan_incremental, the MoR guard, pruning and the stats path the same coverage — including code that is entirely yours. If you'd take it, I'll build it as its own PR against main, independent of #1422.

Three ways I can see, and I don't want to guess which you'd prefer:

Approach Cost
A Arc<dyn SendIcebergStorage> + Send impl for MemoryStorage + in-memory table fixture signature change on the provider's scan surface; unlocks offline testing for the whole crate
B LocalStack, reusing it_iceberg_direct.rs's existing helpers zero refactor, but a Docker-dependent test, and those look gated
C Leave M-2 uncovered, documented free, and the scan stays only manually verified

I'd argue for A on the grounds that it pays for itself across the crate rather than just for this PR, but B is defensible if you'd rather not move those signatures while #1422 is open, and I'd rather do C deliberately than pretend the coverage exists.

One more thing, since it changes what this PR should become

#1529 has merged, so the engine convergence is concrete now rather than hypothetical, and a couple of things follow that I'd like your read on:

  • materialize_graph(provider, graph_source_id, observer) has no target concept, so fan-out sits at the sink layer rather than competing with your engine. The engine question and the isolation-boundary question look orthogonal to me.
  • But TripleObserver::observe(subject, predicate, object) is triple-level with no row context, and our target template expands from row columns. So a routing observer can only see the subject IRI. Options: require the routing key be derivable from the subject IRI (a documented mapping contract — true of our mappings, not enforced), give the observer row context (a change to a merged public trait), or run the engine once per target with a row filter (no upstream change, O(targets) scans).
  • There are now two watermark concepts in one codebase. Your WatermarkStamp is a build receipt — written once, immutable provenance. Ours is a resumable cursor — advanced every window, and it must never advance past durable data. Your suggestion of reading the stamp for each table's from snapshot composes them in exactly one direction: receipt → cursor seed. I don't think it works the other way.

Also, three of the ten commits I wrote after your last review are novelty-backpressure scaffolding — chunk splitting, deferral, drain sizing — which the bulk-import path deletes outright. I'd rather not write more of that until the engine question is settled, so I've stopped.

bplatz added 3 commits August 7, 2026 09:21
…ed scans

Three related hardening changes to the Iceberg/R2RML materialization path,
plus the scan-layer API they depend on.

Accumulator memory budget (pre-OOM circuit breaker)

The per-pass subject accumulator retained one node per distinct subject for
the whole window with no ceiling — a 735k-row full re-read reached 21.4 GiB
resident and was OOM-killed every few minutes with the watermark never
advancing. MaterializeAccum now tracks its estimated size incrementally
(per-entry bytes in KeyState; a tombstone replacing a live node shrinks the
estimate; nodes sized with estimated_json_bytes so the memory budget and the
transaction chunk budget share one model). The gate is checked per batch and
fires pre-commit — no retract has run, no target ledger is touched, the
watermark stays put — as typed ApiError::MaterializeMemoryBudget naming the
size and the operator levers. FLUREE_MATERIALIZE_MEMORY_BUDGET_MB defaults to
1024; 0 disables.

Row emission converges on the shared enumerator

TmEmitContext / emit_row / emit_row_terms are extracted from emit_batch
(behavior-identical; emit_row_terms takes a caller-supplied subject for
classify-then-emit callers). build_live_node is now a TripleObserver
(NodeCollector, keeping the rdf:type-to-@type routing) driving that
enumerator, so the incremental materializer and the bulk twin builder cannot
drift on POM interpretation. Two deltas fall out: templated (non-constant)
predicates now materialize where the hand-rolled loop silently dropped them,
and ParentIndexSet::new validates the mapping fail-closed. FK edges still
drop — parents are not indexed on this path — but are now counted and warned
about rather than silently absent.

Snapshot-pinned materialize scans

scan_for_materialize_stream takes an explicit to_snapshot_id (None = current).
A pin that no longer resolves is typed QueryError::SnapshotNotFound rather
than a silent fall-forward, so a consumer holding a pin can tell an expired
watermark from a transient scan failure. Both planners and both provider entry
points project against TableMetadata::schema_for_snapshot — the schema in
effect at the snapshot, not the current one — so a historical read under
schema evolution resolves the right field ids.

Also: the tracking worker only spawns where a local indexer runs, since
chunked commits rely on the indexer draining novelty between chunks; the
/iceberg/track error says so. Docs cover the new env vars and extend the
materialize limitations (FK edges, graphMap query-path parity, compaction
turning incremental into full reads, multi-node interleaving, templated
targets).
@bplatz

bplatz commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Thank you both for the work here. @christophediprima for a substantial feature contribution and a responsive review cycle, and @aaj3f for the reviews. This comment records the decisions made to get this PR out of the queue, what we changed on the branch, and what moves to follow-up issues.

We have upstream use cases that depend on the snapshot-window scan layer this PR implements quite nicely — the incremental (from, to] diff over Iceberg snapshots, the window-safety classification, and the streaming reader. That is a piece nothing else in the codebase provides. Rather than let the remaining engine-level findings hold the whole PR, we've resolved them to a mergeable minimum and filed the rest as tracked follow-ups.

Here is what was pushed: one commit on top of the author's head + a merge of latest main

  • Shared-enumerator convergence with feat(materialize): fluree materialize — native-twin builder from virtual R2RML/Iceberg datasets #1529
  • Memory budget on the accumulator the per-window subject accumulator — the term measured at 21.4 GiB — is now
    metered and gated per batch against FLUREE_MATERIALIZE_MEMORY_BUDGET_MB (default 1024, 0 disables).
  • NEW-1 (the /4 budget). The divisor stays
  • NEW-2 (worker placement). The tracking worker now spawns only on write nodes with local indexing
  • Snapshot-pinned reads (upstream-driven API addition). scan_for_materialize_stream gains to_snapshot_id: Option<i64>
  • Docs updates

Follow up issues will reference this PR momentarily.

@bplatz
bplatz merged commit 9685d30 into fluree:main Aug 7, 2026
15 checks passed
aaj3f added a commit that referenced this pull request Aug 10, 2026
main moved 114 commits ahead (incl. #1422 iceberg-materialize and #1591
import-fd-budget, both overlapping this PR's materialize domain). Two files
conflicted, both in fluree-db-r2rml/src/materialize/:

- graph.rs (emit_batch): #1422 refactored the inline per-row emit loop into
  emit_row / emit_row_terms behind a TmEmitContext; this PR had optimized the
  same inline loop (MAJOR-4: batched per-POM local_ref_edges fold for constant
  predicates). Took main's emit_row refactor verbatim — it is the go-forward
  structure the rest of #1422 depends on, and it is behavior-identical (the
  per-edge vs batched ref_edges counting yields the same totals). This DROPS
  MAJOR-4's constant-predicate allocation optimization on the bulk-materialize
  path; it is tangential to this PR's fused-aggregate QUERY-path core and can be
  re-applied inside emit_row_terms (a scratch-buffer param) as a follow-up if the
  materialize bulk-emit path perf warrants it.

- mod.rs (pub use graph::{…}): union re-export — canonical_join + subject_sort_key
  (this PR, reused by the fused query path) plus emit_row + emit_row_terms +
  TmEmitContext (#1422).

Verified on the merged tree: cargo check --all-targets (workspace) = clean;
cargo fmt --all --check = clean; cargo clippy --all --all-features --all-targets
-- -D warnings = clean; nextest seam crates (fluree-db-r2rml, fluree-db-query,
--all-features) = green.
@christophediprima
christophediprima deleted the feature/iceberg-materialize branch August 13, 2026 08:15
christophediprima added a commit to christophediprima/db that referenced this pull request Aug 17, 2026
Adds a third read-only MCP tool, `fql_query`, alongside `sparql_query` and
`get_data_model`. It runs a SELECT-style Fluree FQL (JSON-LD) body through
`run_jsonld_subquery` — the same connection path the HTTP /v1/fluree/query route
uses, which wires the BM25 index provider — so an embedded `f:searchText`
full-text block executes in-process. BM25 is FQL-only, so this is the tool that
gives an agent full-text / graph-aware-RAG retrieval that `sparql_query` cannot.

- Forces `opts.identity` from the MCP token (non-spoofable); rejects non-SELECT
  and `from`-less bodies. Returns the same byte-budgeted Agent JSON envelope as
  `sparql_query`, governed by the same --mcp-agent-json-max-bytes /
  --mcp-query-timeout-ms settings.
- Tests (mcp_agent_json): fql_agent_json_envelope_shape,
  fql_requires_authenticated_identity, fql_rejects_non_select_and_missing_from.
- Docs: new docs/query/mcp.md ("Querying over MCP"); cross-linked from the query
  README, the SPARQL/JSON-LD pages, the AI overview, and the MCP config reference.

Originally written on the iceberg-materialize (fluree#1422) + bm25-search (fluree#1543) stack
and kept on the fork; both are now in this branch's base, but the rebuild of
tadaweb/main onto upstream/main never replayed this commit, so it is restored here
verbatim from archive/iceberg-materialize-bm25-pre-rebuild.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants