Skip to content

fix: engine fixes found building the Python package - #2022

Merged
bplatz merged 31 commits into
mainfrom
fix/engine-fixes-from-python
Oct 7, 2026
Merged

bplatz merged 31 commits into
mainfrom
fix/engine-fixes-from-python

Conversation

@bplatz

@bplatz bplatz commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Engine bugs found while building the Python package (top of this stack). Each commit fixes one bug in behaviour already on main and carries a regression test that fails without the fix (two exceptions, under Tests); the commits are independent and read best one at a time.

Commit What was wrong
a write denied by modify policy is 403, not 400 ModifyDenied surfaced as a 400 Bad Request; it is now 403, so clients can tell a denied write from a malformed one.
restored ledgers read empty once; streamed rows compact IRIs restore_ledger left a stale cached genesis handle, so the first read after a restore saw nothing. Streamed rows compacted IRIs although the streaming endpoint promises bindings identical to /query.
a history range's to bound limits the events returned A history range built its graph refs at the view's head t, ignoring TO.
a multi-operation update commits only its net change INSERT x ; DELETE x committed a retraction of a fact the ledger never held (last-wins fold); reversed facts now drop out.
size the disk artifact cache off the writer's thread The cache sized the whole shared temp directory inline under its state lock, a multi-second stall on the first index write per process.
a Cypher transaction commits on a ledger with no commits yet The compare-and-set expected None where the branch ref was unborn, so the first Cypher write to a fresh ledger failed.
a constant vector argument reaches the similarity functions Lowering turned an f:embeddingVector constant into a string, so cosineSimilarity(?v, "[…]"^^f:embeddingVector) scored nothing. Also fixes two cookbook examples that could not run.
nested nodes belong to the graph their parent names A node nested in one with a per-node @graph fell back to the default graph — which is how the documented JSON-LD form of full-text config silently never took effect.
a vector value object matches in a JSON-LD where pattern An array @value typed f:embeddingVector failed to parse in where, though values, inserts and SPARQL accept it.
geo distance search without an index, and as the patterns it replaces See below.
a geo point displays as the WKT it was written as POINT(2.2945 48.8584) read back as the binary expansion of its quantized cell; each coordinate now prints as the shortest decimal that encodes to the same point.
a dropped graph source stops answering; a shared default graph is refused See below.
index flushes on Windows open files with write access Flushing written files before an index publish opened each one read-only and called sync_all, which on Windows is FlushFileBuffers and requires write access. Every flush failed with "Access is denied", so file-backed ledgers on Windows never published an index (retrying forever) and bulk import failed. Shipped in v4.2.1.
file storage lists addresses with / on Windows list_prefix built addresses from Windows paths, separated with \. No live address matched them, so a sweep took every index file as an orphan and deleted it, the current index's included, and the ledger's index then failed to load.
Cypher reads honor cancellation, and can be fuel-tracked The Cypher read path ran with a disabled tracker and default options, so a timeout, Ctrl-C or a dropped client could not stop a Cypher read. Adds query_cypher_with_tracker.

Behaviour changes worth a look

  • Policy status: a modify-policy denial is now 403 rather than 400.
  • Geo search: Triple + BIND(geof:distance) + FILTER was rewritten into GeoSearch whether or not a binary index existed, and GeoSearch errors without one, so the query failed on any ledger not yet indexed, or read before the index's base t. The rewrite now runs only when an index covers the query's t, and stamps a geo_search routing outcome. GeoSearch also answered differently from the patterns it replaces: it kept one row per subject, never bound the location variable, and, when the triple was kept, joined every point with its subject's minimum distance. It now emits one row per (subject, point) with that point's distance and binds the point; a query whose location variable another pattern uses is left as written.
  • Graph sources: a dropped source's record stays as a tombstone, and query resolution never checked it, so the process that dropped a source kept querying it. A graph source sharing the default graph with a ledger (FROM <ledger> FROM <source>) answered from only one of them, silently; that is now refused with an error naming the form that works (FROM NAMED + GRAPH). The Iceberg docs' join example used the broken form and is corrected.

Tests

The geo search tests built their index on a connection that never loaded it, and their helpers swallowed query errors, so they had been passing against the error. The per-subject dedup test is replaced by one that indexes for real and pins that the accelerated and unaccelerated paths return the same rows; the routing test runs in its own binary because it captures tracing stamps.

The two Windows fixes have no engine test that fails without them, because the engine's tests do not run on Windows; flush_keys's existing unit test and a new list_prefix one cover them wherever they do. The Python package's Windows job in #2025 (bulk import, indexing, sweep) fails without them.

Review fixes

From @aaj3f's review, one commit each, with a test that fails without it:

Commit What was wrong
multi-op netting finds a named graph's indexed values The base lookup the netting asks through filtered index rows on their graph, which they don't carry, so in a named graph an index-resident value never counted as held: on a cold index INSERT x ; DELETE x committed nothing and x survived. Rows now take the key's graph.
geo search tests reach GeoSearch and check its answers Five geo tests ran on a connection that never loaded its index and swallowed query errors. They now index file-backed ledgers, check the index is loaded, and assert exact answers; time travel and retraction leave changes in novelty over the index. An empty GeoSearch now fails all seven single-ledger tests.
no geo rewrite for a dataset spanning several ledgers The gate checked the primary snapshot's index, but a multi-ledger dataset runs with no binary store, so FROM <a> FROM <b> (or FROM NAMED <b> with the shape in GRAPH <b>) failed "GeoSearch requires binary index". The dataset path now decides single-ledger before prepare and tells it via PrepareConfig::without_binary_scans.
a dropped BM25 or vector index stops answering The providers resolved drop tombstones: a dropped BM25 index failed as an internal storage error, and a dropped vector index kept returning hits. One live-record lookup now names a dropped source as not found.
a sweep refuses a listing the live set cannot match A guard for the Windows \ class that runs on any platform: the plan requires each branch's head root in the storage listing, or refuses.
a 403 from the server shows its message The CLI dropped the server's message on a 403, so a policy-denied write lost its f:exMessage. The errors.md example now shows the message the server sends.
graph-source joins name the source with FROM NAMED r2rml.md and server-integration.md still showed the refused shape.
ensure_streamable's doc comment back on it Nit.
a graph a request empties again is not registered INSERT … GRAPH <g> ; DELETE … GRAPH <g> on a new graph landed an empty commit; it now commits nothing, like the default graph. A graph registered with no facts (CREATE GRAPH) is unchanged.
a Cypher write's reads count against its fuel limit The sequential Cypher write driver's reads ran untracked: a MERGE read through a 60³ cross product charged 10 fuel and committed under a 50-fuel limit. Its reads now take the driver's tracker. The single-statement conditional path (resolve_conditional_cypher, called from consensus) keeps its untracked one-row probe.

Also in this PR

Found while working through the review, one commit each:

Commit What was wrong
a WKT POINT constant matches the stored point A geo:wktLiteral POINT is stored as a GeoPoint but stayed a string as a query constant (core coerce_value, SPARQL typed-literal lowering, SPARQL filter constants), so it matched nothing: as a triple object, in VALUES, in FILTER(=)/sameTerm, or as a JSON-LD value object, and a JSON-LD update deleting a location by value retracted nothing. All three now coerce as a write does; the geo rewrite takes the GeoPoint center, and the routing test stamps a typed center. Predates this PR.
a TriG block's parse error names the construct it refuses #1979 item 3: inside a GRAPH block on upsert/import, [ … ] and ( … ) were refused with "expected object, found '['". The error now names anonymous blank nodes or collections and points to a labeled blank node (the limitation itself is #1930).
geo search's named-graph boundaries, un-ignored The test was ignored as needing graph-scoped index routing and ran on a setup that never loaded its index. On an indexed ledger GeoSearch keeps to the graph it reads, default and two named graphs.
one address_path for storage paths list_prefix and the nameservice's ns_record_stem share one path-to-address join.

The branch also merges current main.

Fixes #1810
Fixes #1515
Fixes #1979 (items 1–3; #2009 extends the @graph scoping to every JSON-LD reader)

bplatz added 13 commits October 5, 2026 23:04
A transaction that policy refuses was reported as 400, the same as a
malformed one, so clients could not tell "not allowed" from "not valid".
`PolicyError::ModifyDenied` (directly or wrapped in
`TransactError::PolicyViolation`) now maps to 403 with
`@type: err:policy/AccessDenied`. Other policy errors, such as invalid
policy definitions, keep their status.

In Raft mode the commit worker retries a policy denial after refreshing,
since a lagging view can affect policy evaluation, and poisons the entry
as `PolicyViolation` (403) if it is still denied.
`restore_ledger` creates its target with `create_ledger`, which caches the
empty genesis state, then moves the heads in the nameservice. The first
in-process read through the cached handle saw the empty ledger. The
cached handle is now dropped once the restore succeeds.
Test: `flpack_restore_first_cached_read_sees_restored_data`.

Streamed NDJSON rows are documented as the `bindings` entries `/query`
returns, but they compacted IRIs against the query's prefixes
(`"a:x"` rather than `"http://a.co/x"`), and a row carries no prefix map
to expand them with. Rows now use the SPARQL-results profile's absolute
IRIs, as buffered results do.
Test: `streamed_rows_match_buffered_sparql_json_iris`.
`FROM <l@t:1> TO <l@t:2>` (and JSON-LD `"to"`) returned changes after
t=2. History views are loaded at the ledger head, and
`DataSetDb::as_runtime_dataset` passed that head `t` to every graph the
scans read, so the resolved `to_t` never reached them. In history mode
each graph's `t` is now capped at the range's `to`.

Test: `history_range_respects_to_bound` (JSON-LD and SPARQL, novelty and
indexed, `to` at t:1 and t:2).
A fact one operation of a ';'-separated SPARQL UPDATE (or Cypher sequential
write) adds and a later one removes was committed as a retraction of a fact
the ledger never held, visible in history; the reverse case committed a
redundant re-assertion. The sequential fold now tracks each fact's first op
and, at finish, drops facts a later operation reversed back to how the base
had them.
The first write into a cache directory walked the whole directory to learn
its size, inline and under the cache's state lock. On a shared cache of a few
hundred thousand files that took seconds: the async worker that wrote first
stalled, every other writer queued on the lock, and tasks woken onto those
workers waited with them. Indexing two small commits took 8s.

The first size check now starts a background walk and lets writes through;
writes and evictions made meanwhile are reconciled with what the walk saw.
A ledger created but never written has an unborn commit-head ref (no id,
t 0). The interactive Cypher transaction expected no ref at all, so its
publish CAS failed with a commit conflict on such a ledger; Bolt explicit
transactions on a new ledger could never commit. It now expects the ref the
autocommit path expects.
`cosineSimilarity(?v, "[0.8, 0.1]"^^f:embeddingVector)` lowered the
literal to a vector and then, since vectors were missing from the kinds a
filter constant keeps, replaced it with its lexical string. Every score
came back unbound; only a vector bound through VALUES worked. Constants
now keep their vector value, so both forms score identically, which a
test pins for all three functions against VALUES and the JSON-LD form.

The search cookbook's JSON-LD examples passed the query vector as an
array inside the expression string, which is not a vector and also scored
nothing; they now bind it with `values`, as the vector reference does.
Its aggregation example used an `aggregate` key the query language does
not have and failed; it now uses `(as (count ?doc) ?count)`. SPARQL forms
of the vector examples are added.
A node with a per-node `"@graph": "<iri>"` landed in that graph, but node
objects nested in it (a ref with properties, or a blank node) fell back
to the default graph, as if written separately. JSON-LD puts an embedded
node in the graph of the node that embeds it, and the docs' JSON-LD form
of ledger config relies on that: the `f:LedgerConfig` reached the config
graph while its nested `f:FullTextDefaults` and `f:FullTextProperty`
nodes went to the default graph, so the config never took effect and
nothing said why.

A node's own `@graph` is now the default for the nodes nested in it, for
insert, upsert and update templates alike. Tests pin nested `@id` and
blank nodes through all three, and the documented full-text config
written as JSON-LD scoring after a reindex.
A where pattern whose object was {"@value": [...], "@type": f:embeddingVector}
failed to parse ("@value must be string/number/bool"), though the same
value object inserts, binds through values, and matches as a SPARQL
constant. The pattern parser now reads an array @value as a vector literal,
as the values clause does.
… it replaces

A triple + BIND(geof:distance) + FILTER(< r) query was rewritten into a
GeoSearch whether or not a binary index existed, and GeoSearch fails
without one, so the same query errored on a ledger not yet indexed, or
read at a t before the index's base. The rewrite now happens only when an
index covers the query's t; otherwise the patterns run as written. It
stamps a geo_search routing outcome either way.

GeoSearch also answered differently from the patterns it replaces: it
kept one row per subject (the nearest of its points), never bound the
location variable, and when the triple was kept for another use of that
variable, joined each of a subject's points with its minimum distance.
It now emits one row per (subject, point) with that point's distance and
binds the point, and the rewrite leaves alone a query whose location
variable another pattern uses.

The geo search tests built their index on a connection that never loaded
it, and their helpers swallowed query errors, so they passed against the
error. The dedup test is replaced by one that indexes for real and pins
that both lanes give the same rows; the routing test runs in its own
binary because it captures stamps.
POINT(2.2945 48.8584) read back as POINT(2.294499894878385
48.85840004203692): the stored point is quantized, and its display printed
the decoded cell's binary expansion. Each coordinate now prints as the
shortest decimal that encodes to the same point, so a point reads back as
written and still parses to itself.
…aph is refused

Dropping a graph source leaves its nameservice record as a tombstone, and
the R2RML provider resolved records without checking it, so a dropped
source still answered queries in the process that dropped it. Every
lookup that resolves a source for a query or a materialize now treats a
retracted record as absent.

A graph source sharing the default graph with a ledger (or another
source) is read by its own scan, which the default graph does not union
in: such a query answered from only one of its sources, silently. It is
now refused with an error naming the form that works — FROM NAMED and a
GRAPH block — and the Iceberg docs' join example, which used the shared
form and returned nothing, now uses it.
The Cypher read path ran every query with a disabled tracker and default
execution options, dropping the caller's: a cancellation handle (a
timeout, Ctrl-C, a client that went away) could not stop a Cypher read,
which ran to completion instead. query_cypher_with_options now passes its
options through, and query_cypher_with_tracker charges a tracker, so a fuel
limit stops a Cypher read and its tally reports what the read cost, as for
SPARQL and JSON-LD.
@bplatz
bplatz added this pull request to stack #2026 October 6, 2026 03:23
@bplatz bplatz added the bug Something isn't working as expected label Oct 6, 2026
@bplatz bplatz changed the title fix/engine fixes from python fix: engine fixes found building the Python package Oct 6, 2026
@bplatz
bplatz requested review from aaj3f and zonotope October 6, 2026 03:23
@bplatz
bplatz marked this pull request as ready for review October 6, 2026 03:23
bplatz added 2 commits October 6, 2026 06:12
Flushing written files before publishing an index opened each one
read-only and called sync_all. On Windows that is FlushFileBuffers, which
requires write access, so every flush failed with "Access is denied":
file-backed ledgers there never published an index, retrying forever,
and bulk import failed outright.
list_prefix built each address from the file's relative path, which on
Windows separates with \. No live address matched one, so a sweep took
every listed index file as an orphan and deleted it, the current index's
included; a partial-name prefix also matched nothing.

@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.

@bplatz this is great and at a design-level no pushback from me. Claude's review helped me find some "right design; issue with implementation" elements below that I won't restate here as they're clearly outlined. I will say that a lot of the work in this PR falls into a class of "two paths do the same thing and sometimes one of those paths re-derives (and drops) something the first path already did". I'll make a note of where I'm seeing that happening, but to be clear, I don't think this PR should try to abstract over them--I think for this effort the point fixes are right.

streamed rows vs /query IRI profile (44692366f); Cypher reads vs SPARQL/JSON-LD tracker+options (75f6a3f9b); GeoSearch vs the triple+BIND+FILTER it replaces (34a8f36f7); history graph refs at head t vs the range's to (351247e61); Cypher interactive txn CAS vs the autocommit path's unborn ref (757c4bce7); JSON-LD where @value vs the values parser (40c14ba73); SPARQL filter constants vs the VALUES path for vectors (e5a8d57d6)

Full review below:


✅ Approving to unblock you — with 3 things that need to be addressed before this merges.

This is a really useful batch: fifteen real bugs, one per commit, each with its mechanism in the body, and the netting fix in particular is the right design (it asks the base instead of guessing from op pairs), with one hole in the lookup it asks through. I went through it commit by commit and re-ran the new engine tests by name. The first thing below is a regression against main in indexed named graphs; the other two are places where a commit's own claim isn't true yet. All three are small.

Must address before merge:

  1. The multi-op netting drops real retractions in indexed named graphs (fluree-db-api/src/tx.rs:282; cause at fluree-db-api/src/rebase.rs:967-970). current_asserted_for_key keeps only rows whose g equals the key's, but index rows decode with g: None, so an index-resident named-graph value never counts as "in the base". On a cold index, INSERT DATA { GRAPH <g> { x } } ; DELETE DATA { GRAPH <g> { x } } commits nothing and x survives, where main deletes it. Stamping the key's graph on the rows instead of filtering on it fixes it; I ran that against the cold cases and the merge/rebase/revert tests.
  2. The geo rewrite still fails on multi-ledger datasets (fluree-db-query/src/execute/runner.rs:430; cause at fluree-db-api/src/view/dataset_query.rs:726-790). The gate checks the primary snapshot's binary store, but a dataset spanning more than one ledger runs with none, which is the store GeoSearch reads. FROM <a> FROM <b>, or FROM NAMED <b> with the pattern inside GRAPH <b>, both indexed, fails GeoSearch requires binary index (binary_store not configured), while the same query with the rewrite suppressed answers correctly. Pre-existing, but it's the failure this commit removes, in the shape the gate can't see. Decide coverage from what the operator will get.
  3. BM25 and vector sources still resolve their tombstones (graph_source/bm25.rs:618-621, graph_source/provider.rs:525-531, :563-567). A query against a dropped BM25 index fails with a 500-class Storage error: Not found instead of a not-found, and a dropped vector index keeps returning hits (I ran both). Same one-line filter, plus a drop-then-query test each.

Should address (inline): a sweep-side guard for the \ addresses so the data-loss class has a test that runs on Linux; the CLI dropping the policy's message on the new 403; five geo tests that are still hollow the way the commit body describes; and two docs (r2rml.md, server-integration.md) that still show the newly refused FROM <ledger> FROM <source> shape.

Optional (inline): a stray doc comment in stream_query.rs, an empty commit when a reversal registers a new named graph, the Cypher write driver's untracked probe reads, and the cost of the WKT shortest-decimal search.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ every fix lands at the shared mechanism (the sequential stager, the dataset builder, ApiError::status_code, the geo rewrite pass); the tombstone check is hand-repeated per site, which is how BM25 and vector got missed.
  • Performance (speed first, memory second): ✔ no query-engine hot path regresses; GeoSearch dedups by (subject, point) at the same cost, netting adds one lookup per flipped fact only on multi-op updates, and the disk-cache change removes a multi-second stall. ⚠️ geo point output formatting is ~16× slower per point (inline).
  • Deployment targets: ✔ the disk-cache scan is a plain thread (inline on wasm32, where the cache never writes), and a frozen embedded host just resumes it; the two Windows fixes have no evidence in this repo's CI, which runs only on Linux (inline).
  • Testing: ⚠️ twenty new tests, all wired, all ran in CI by name and locally; nothing runs a multi-op update against an index-resident named graph, the geo gate has no multi-ledger case, the BM25/vector tombstones have no test, five geo tests still don't reach the operator, and the Windows list_prefix test can't fail off Windows.
  • Conventions: ✔ one bug per commit, multi-line bodies with the mechanism, cargo fmt/clippy green in CI; the 403 is documented in errors.md and the raft docs; two graph-source docs still show the refused form.

Verified locally at 541b37d82: every new fluree-db-api/fluree-db-core test by name (debug, fresh TMPDIR; the server and Raft ones are green in CI); a netting matrix of 9 shapes over a novelty base and a rebuilt index, plus a cold-index probe in the default and a named graph (and the rebase.rs fix against it); a known-answer geo test over novelty, as-of, re-index and multi-ledger datasets; BM25 and vector drop-then-query; a 2M-point WKT round-trip; and mutation checks that reverted the netting, the history to cap, the geo gate and the WKT display (each turned its test red; all restored), plus one that emptied GeoSearch and left five geo tests green.

Cross-PR note: #2009. One overlap fwiw: 7d894b7e9 (nested nodes take their parent's @graph) is #1979 item 1, which my #2009 fixes across every JSON-LD reader (@list, @reverse / @included / @nest, named-graph objects, where). Same behaviour, so nothing to change here: this lands first and I'll take #2009's scoping over it when it rebases, with your two tests as the check: on a local merge of main + #2009 + this branch, taking #2009's jsonld.rs, nested_nodes_land_in_the_enclosing_nodes_graph and fulltext_configured_through_jsonld_node_graph both pass next to #2009's 18 graph-scope tests, with none of 7d894b7e9's code present. Maybe worth a Partially addresses #1979 on the commit or body so the issue shows both. The six r2rml.rs hunks against #2007 are mine to resolve too.

Approving now so you can merge without waiting on another pass from me — just be sure the named-graph netting fix, the geo gate and the BM25/vector tombstones are in before you do.

Comment thread fluree-db-api/src/tx.rs
}
let key =
fluree_db_core::ConflictKey::new(flake.s.clone(), flake.p.clone(), flake.g.clone());
let in_base = crate::rebase::current_asserted_for_key(&self.original, &key)

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.

🔴 Must address before merge: in an indexed named graph, INSERT x ; DELETE x now commits nothing and x survives, a regression against main.

current_asserted_for_key (fluree-db-api/src/rebase.rs:967-970) range-reads the slot already scoped to the key's graph, then keeps only the rows with flake.g == key.g. But the base-index decoder builds every row with g: None (fluree-db-query/src/binary_range.rs:833-834, :1448-1449); the graph rides on the query's g_id, not on the row. So in a named graph every index-resident value is filtered out, in_base reads false, and the retract that should land is dropped here as "reversed".

I reproduced it on a cold index: file storage, seed ex:s ex:p "x" in GRAPH <http://example.org/g>, rebuild_and_publish_index, then a fresh FlureeBuilder::file over the same path (novelty empty, index t = head t = 1). INSERT DATA { GRAPH <g> { x } } ; DELETE DATA { GRAPH <g> { x } } comes back at t = 1 with no flakes, and x is still there; main's last-wins fold commits the retract and x is gone. The mirror case, DELETE x ; INSERT x, commits a redundant re-assert for the same reason. The default graph and novelty-resident named-graph values are right, which is why the default-graph test passes; a memory ledger with an index rebuild doesn't reproduce it either, it needs the cold load.

Fix: stamp the graph the range was scoped to instead of comparing against it, at rebase.rs:969:

.filter(|flake| flake.op)
.map(|flake| Flake { g: key.g.clone(), ..flake })

With that, all six cold cases (default and named × present INSERT;DELETE, present DELETE;INSERT, absent INSERT;DELETE) come out right, multi_operation_reversed_facts_leave_no_commit and multi_op_dangling_retract_and_ns_delta_survive_index_merge_and_reload still pass, and so do the it_merge, it_rebase and it_revert tests in grp_ledger (75 of 75). A cold named-graph case next to the default-graph test would pin it. Commenting here because rebase.rs is not in this diff.

The rule itself is right, and worth keeping as is. A cancelling-pair rule over ops gets the redundant-assert shape wrong (insert a fact the ledger already holds, then delete it, and the pair cancels away a real deletion — the NetChangeAccumulator trap from #1818); keeping a flipped fact iff op != in_base handles it. In the default graph I ran nine shapes (present and absent × INSERT;DELETE, DELETE;INSERT, three- and four-op chains, INSERT DATA; DELETE WHERE, INSERT DATA; DELETE … INSERT … WHERE) over a novelty base and a rebuilt index, plus a language-tagged value and a novelty-resident named graph, and the three cold-index default-graph cases above; every one commits exactly the net change, and short-circuiting drop_reversed_facts turns multi_operation_reversed_facts_leave_no_commit red. It's only the base lookup underneath that's wrong, and only for index-resident named-graph values.

Fwiw this is the fourth consumer to trip on the g: None the index decoder emits: 3e3f0af28 (whole-graph scans, fixed on main by stamping), #1887's GraphMismatch, and #2008's 7305a4a71 (merge/revert/rebase conflict retractions, through this same function). Not for this PR, but having the range decoder stamp the graph it was asked for would retire the class.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 2f42039

Comment thread fluree-db-query/src/execute/runner.rs Outdated
// index's base) the patterns stay as written and evaluate as such.
// The operator reads the store its execution context takes from
// the snapshot, which a caller need not have passed in here.
let geo_index_covers = binary_store

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.

🔴 Must address before merge: the gate still rewrites into a GeoSearch that can't run whenever the query spans more than one ledger.

The gate asks whether the primary snapshot's binary store covers db.t. But the dataset path decides separately, at fluree-db-api/src/view/dataset_query.rs:747-790, that a dataset spanning more than one ledger executes with no binary store at all ("In multi-ledger mode we disable binary scans…"), and that's the store GeoSearchOperator::open reads (ctx.binary_store, geo_search.rs:329-334). prepare_config is built from primary.binary_store at :726-730, before that decision, and even if it were None the new .or_else(|| … extract_binary_store(db.snapshot)) here would still find the primary's store.

I ran it against two file-backed ledgers, both indexed (a: Paris, Lille, Brussels; b: Amsterdam), capturing the routing stamp: FROM <a> FROM <b> with the BIND/FILTER shape stamps proceed and then fails Invalid query: GeoSearch requires binary index (binary_store not configured) (a 400); FROM <b> FROM <a> the same; FROM <a> FROM NAMED <b> with the shape inside GRAPH <b> { … } the same. The same two-ledger query with FILTER(BOUND(?loc)) added, so the rewrite stands down, returns all four cities. So the patterns-as-written lane answers these, and the gate sends them to the one that refuses.

This is pre-existing (main rewrote unconditionally and open is unchanged), but it's the exact failure this commit sets out to remove ("otherwise the patterns run as written"), in the one shape the gate can't see, and since #2004's union default graph it's an ordinary query. A fix is probably to compute is_single_ledger_dataset before building prepare_config (both sites, dataset_query.rs:727 and :912) and give the gate a way to know the operator will get no store, checked before the snapshot fallback here. A two-ledger case next to geof_distance_answers_before_and_after_indexing would pin it. Commenting here because fluree-db-api/src/view/dataset_query.rs is not in this diff.

Fwiw the single-ledger lanes are good: in the same test, with the GeoSearch lane actually taken (stamp proceed), I got the right answers at head with novelty past the index's base t, as-of the base, as-of between base and head, as-of a retraction still in novelty, and after a re-index.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 4ec7034

.nameservice()
.lookup_graph_source(&id)
.await
.map(|record| record.filter(|record| !record.retracted))

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.

🔴 Must address before merge: BM25 and vector sources still resolve their tombstones, so "every lookup that resolves a source for a query" isn't true yet.

The commit body says every query/materialize lookup now treats a retracted record as absent, and the seven R2RML/Iceberg sites here do. The BM25 and vector providers don't. load_or_create_bm25_manifest (fluree-db-api/src/graph_source/bm25.rs:618-621, which bm25_index and search_bm25_selective both call) reads the tombstone's index_id: I created a BM25 index, dropped it, and asked FlureeIndexProvider::bm25_index for it again, and got Err(Internal("Storage error: Not found: fluree:memory://graph-sources/rv-drop/main/snapshots/….gssnap")), since the drop deleted the snapshot. That's a 500 for what should be a not-found. search_vector_embedded (graph_source/provider.rs:525-531) and its post-sync re-lookup (:563-567) have no check either, and drop_vector_index keeps the snapshots on purpose (vector.rs:800-803), so a dropped vector index keeps answering exactly as the R2RML one did: I indexed two docs, searched through FlureeIndexProvider::search (2 hits), dropped the index, and the same search returned the same 2 hits, while collection_exists on the same provider said false. collection_exists (provider.rs:463-471) is the one place that checks retracted, and nothing on the query path calls it.

Fix: the same .filter(|record| !record.retracted) at those three sites, and a drop-then-query test per provider like a_dropped_graph_source_no_longer_answers. Commenting here because bm25.rs and provider.rs are not in this diff.

(Not for this PR: that's ten hand-written tombstone checks across the providers now, and these are the two that were missed. A live-only lookup the query paths have to go through, with the raw one renamed so it reads as admin-only, would make the next one a compile error.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 741bea5

The check sits at the provider entry points (bm25_index, both search paths via get_deployment_config, and the vector lookups) through one lookup_live, rather than in load_or_create_bm25_manifest, which the drop path reads before it retracts. A dropped source answers Graph source not found, the error the vector provider already gave a missing one; that's a 400, since provider errors can't carry a 404 today.

Comment thread fluree-db-core/src/storage/file.rs Outdated
// a sweep reads as an orphan and deletes.
if let Ok(relative) = path.strip_prefix(&self.base_path) {
let relative_str = relative.to_string_lossy().to_string();
let relative_str = relative

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.

🟠 Should address: the \ fix is right, but nothing guards it on a platform this repo's CI runs, and the failure mode is deleting the live index.

list_prefix_addresses_separate_with_slashes passes on macOS with the fix reverted — on a Unix Path, \ is just a filename character, so components() and to_string_lossy() agree — and the only Windows evidence is #2025's Python job. It's also the second time a path→address conversion has needed this: ns_record_stem in fluree-db-nameservice/src/file.rs got the same treatment in d8d776d63.

The sweep is where a platform-independent guard fits. plan_sweep (fluree-db-indexer/src/gc/sweep.rs:138) takes scanned − live on faith; if a branch's index head root, which the walk just read, has none of its candidate_addresses in scanned, the listing doesn't speak the store's address form and every orphan it reports is suspect, so refuse to plan. That's testable on any platform with a Storage wrapper whose list_prefix rewrites / to \, and it also covers the next backend whose listing form drifts, not just Windows. Commenting here because sweep.rs is not in this diff.

It's small and non-blocking, but given the blast radius I'd rather see it folded in now than lost in the backlog. (One relative_path_to_address in core shared by list_prefix and ns_record_stem would be the tidy-up; the guard is what matters.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in a578378

The shared helper is in b73ab1c (fluree_db_core::storage::address_path, used by list_prefix and ns_record_stem).

// The write was understood but refused by its policy. Other
// policy errors (invalid definitions, evaluation failures) are
// not authorization denials.
ApiError::Policy(fluree_db_policy::PolicyError::ModifyDenied { .. })

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.

🟠 Should address: the CLI throws the policy's message away on a 403.

fluree-db-cli/src/remote_client.rs:426 maps a 403 to RemoteLedgerError::Forbidden, a unit variant, and :321 displays it as access denied (403); the message that map_error extracts just above is dropped. So fluree insert/update --remote on a write a modify policy denies used to print bad request: Employees may not modify document content. (the policy's f:exMessage, off the 400) and now prints access denied (403) with no reason. The server body still carries the message, and the server tests here assert that, but a CLI user never sees it.

Forbidden(String) displayed as access denied (403): {msg}, the way BadRequest and Conflict already carry theirs, would fix it. Commenting here because remote_client.rs is not in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in e3537ef

Join Iceberg data with Fluree ledgers:
Join Iceberg data with Fluree ledgers by naming the graph source in
`fromNamed` (SPARQL: `FROM NAMED`) and reading it inside a `graph` block. A
graph source cannot share the default graph with a ledger; such a query 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.

🟠 Should address: two more docs still show the shape that's now refused.

docs/graph-sources/r2rml.md:266-281 ("Combining with Fluree Data") has the same "from": ["products:main", "warehouse-inventory:main"] join this commit fixes here, which now fails with the FROM NAMED error. And docs/cli/server-integration.md:2520 still describes FROM <ledger>, <graph-source> as a known limitation where "bare triple patterns only scan native indexes"; it's a refusal now. Both are small text edits; commenting here because neither file is in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in db15c79

///
/// Uses `QueryError::InvalidQuery` (not `ApiError::query`, which maps to a 500)
/// so these client mistakes surface as a `4xx`.
/// The compactor for streamed rows. Rows are the `bindings` entries `/query`

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 / nit: row_compactor landed between ensure_streamable and its doc comment.

The /// Reject query shapes the streaming endpoint does not support. … block (:567-570) now reads as the first half of row_compactor's doc, and ensure_streamable lost its own. Moving row_compactor and its doc above :567 fixes both. Tiny, but if you agree I'd rather see it folded in now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in c63328d

Comment thread fluree-db-api/src/tx.rs
/// ORIGINAL base. Valid with zero staged operations (an all-no-op run):
/// the result is an empty staged view.
pub(crate) fn finish(self) -> Result<StageResult> {
pub(crate) async fn finish(mut self) -> Result<StageResult> {

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 reversal inside a new named graph still lands a commit.

INSERT DATA { GRAPH <g> { x } } ; DELETE DATA { GRAPH <g> { x } } on a ledger that has never seen <g> nets x away, but merged_graph_iris still carries <g>, so is_noop sees an unregistered graph and the request commits: I get a receipt at t = 2 with flake_count = 0. The default-graph version correctly commits nothing. Dropping, in finish, the graph IRIs whose flakes all netted away would make the two agree. If you'd rather a graph the request named stays registered, that's defensible too; mostly flagging it so it's a choice rather than an accident.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 8aafbcd

Went with dropping it, to match the default graph. A graph registered with no facts at all (CREATE GRAPH) is unaffected.

vars,
parsed,
0.0,
&QueryExecutionOptions::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.

🟡 Optional: the Cypher write driver's reads still run untracked.

query_cypher_ast and query_cypher_ast_seeded (here and :645-646) keep QueryExecutionOptions::default() and Tracker::disabled(), and they're what cypher_seq.rs uses for every MATCH probe of a Cypher write (:254, :361, :385, :605, :616, :709, :751, :1043, :1149), while the same driver threads its tracker into staging. So a Cypher write's fuel limit doesn't count its reads, and a cancellation doesn't stop them, which is the gap this commit closes for reads. This is from the code; I haven't run a Cypher write against a fuel limit. Threading the tracker and options through the two probe entry points would close it, and if you agree it's right I'd rather see it in this PR than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in d1fd28f

The tracker only: the write path has no cancellation source to thread. The single-statement conditional probe (resolve_conditional_cypher, public and called from consensus) is left untracked.

}

/// The shortest fixed-point rendering of `value` that `same` accepts.
fn shortest_decimal(value: f64, same: impl Fn(f64) -> bool) -> 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.

🟡 Optional: the shortest-decimal search costs about 16× the old Display per point.

Each coordinate tries up to 13 rounds of format! + parse + re-encode. In a debug build, 200k points formatted in 989 ms against 62 ms for the old format!("POINT({lng} {lat})"). It's output formatting, not the engine, but every result and export format that prints a point goes through it. Rounding arithmetically, checking the re-encode, and formatting only the winner would make it allocation-free.

The behavior itself checks out: I round-tripped 2M random points, the 64 raw cells at the grid extremes, and ±90/±180/0/sub-cell edges, and every one re-encodes to the same cell, with no -0 and nothing longer than 31 characters.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not changed in this PR: it's output formatting rather than the engine, so I'd rather take it as a follow-up.

bplatz added 6 commits October 7, 2026 12:49
current_asserted_for_key read the key's graph and then kept only rows
whose graph equalled the key's, but index rows decode with no graph. A
named graph's index-resident values never counted as held, so on a cold
index INSERT x ; DELETE x in a named graph committed nothing and x
survived, and DELETE x ; INSERT x committed a redundant re-assert. Each
row now takes the key's graph.
Five geo search tests ran on an in-memory connection with no indexing
mode, so the index they built was never loaded and their queries took the
patterns as written; their helpers turned query errors into empty
results, and the time-travel test asserted nothing. They now index a
file-backed ledger, check the index is loaded, and assert exact answers.
The time-travel and retraction tests leave a city and a retraction in
novelty over the index, so the overlay and as-of paths run. An empty
GeoSearch now fails all seven single-ledger tests.

The retraction binds the location by variable: a WKT constant in a
pattern does not match a stored point.
The rewrite into GeoSearch was gated on the primary snapshot's binary
index, but a dataset spanning more than one ledger executes with no
binary store, the one GeoSearch reads. FROM <a> FROM <b>, or FROM NAMED
<b> with the shape inside GRAPH <b>, both indexed, failed "GeoSearch
requires binary index" where the patterns as written answer. The dataset
path now decides single-ledger before prepare and tells it, through
PrepareConfig::without_binary_scans, that operators get no store.
The query providers resolved a graph source's record without checking
whether it was a drop's tombstone. A query against a dropped BM25 index
failed reading its deleted snapshots, as an internal error, and a dropped
vector index, whose snapshots a drop keeps, went on returning hits. The
providers now resolve only live records, through one lookup, and name a
dropped source as not found, as they already did a missing one.
A sweep deletes what storage lists minus what a live index chain
reaches, trusting the listing to name files the way the index does. A
listing in another form, as file storage's Windows listing once was,
matches no live address, so every file, the current index's included,
was planned as an orphan. The plan now requires each branch's head root
in the listing and refuses otherwise. The test lists addresses with \,
so it runs on any platform.
RemoteLedgerError::Forbidden carried nothing, so the reason a server
gives for a 403 was dropped. A write a modify policy denies, now a 403
rather than a 400, printed "access denied (403)" where it had printed
the policy's message; it now prints both.
bplatz added 9 commits October 7, 2026 12:55
r2rml.md's join example and server-integration.md's known-limitation note
still showed a graph source sharing the default graph with a ledger,
which is now refused. The example names the source in fromNamed and
reads it in a graph block, as iceberg.md does.
row_compactor was inserted between ensure_streamable and its doc
comment, which then read as the first half of row_compactor's.
INSERT DATA { GRAPH <g> { x } } ; DELETE DATA { GRAPH <g> { x } } on a
ledger that had never seen <g> netted x away but still registered <g>,
so the request landed an empty commit; the default-graph version commits
nothing. A graph whose every staged fact a later operation reversed is
now left out of the request's registrations. A graph registered with no
facts at all (CREATE GRAPH) is unaffected.
The sequential Cypher write driver threads its tracker into staging, but
the reads it makes to find rows (its MATCH prefix, MERGE probes, seeded
lookups) ran through query_cypher_ast and query_cypher_ast_seeded with a
disabled tracker. A write that read a 60^3 cross product to MERGE one node
charged 10 fuel and committed under a 50-fuel limit. Those reads now take
the driver's tracker (query_cypher_ast_tracked; query_cypher_ast keeps its
public signature, untracked).
FileStorage::list_prefix and the file nameservice's ns_record_stem each
joined a relative path's segments with / so a Windows listing would match
the addresses it names. They now share fluree_db_core::storage::address_path.
The GRAPH-block parser behind upsert and import reads neither anonymous
blank nodes nor collections, and refused them with the token alone:
"expected object, found '['". The same nodes outside a block commit
fine, so the construct, not the syntax, was unsupported, and nothing said
so or how to write it instead. The error now names anonymous blank nodes
or collections and points to a labeled blank node.
geo_search_respects_named_graph_boundaries was ignored as needing
graph-scoped binary index routing, ran on the in-memory setup that never
loaded its index, and swallowed query errors. On an indexed ledger,
GeoSearch keeps to the graph it reads: the default graph's cities from
Paris, and each named graph's from Munich, though every city is within
the radius. An empty GeoSearch fails each of the three queries.
A geo:wktLiteral POINT is stored as a GeoPoint, but as a constant it
stayed a string: core's coerce_value passed it through, and SPARQL's
typed-literal lowering had no wktLiteral arm, and its filter constants
fell back to a string for any GeoPoint. So a POINT constant matched
nothing, as a triple object, in VALUES, in FILTER(=) or sameTerm, or as a
JSON-LD value object, and a JSON-LD update deleting a location by its
value retracted nothing. All three now coerce a POINT as a write does.

The geo rewrite takes the resulting GeoPoint center as it took the WKT
string, so a typed center keeps the GeoSearch lane; the routing test now
stamps one.
@bplatz

bplatz commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f On #1979: item 3 (naming blank nodes in the TriG block errors) is now in this PR too, in 4a4f7c3, so with items 1 and 2 the body says Fixes #1979 and notes that #2009 extends the @graph scoping to every JSON-LD reader.

@bplatz
bplatz merged commit 8632e33 into main Oct 7, 2026
9 checks passed
@bplatz
bplatz deleted the fix/engine-fixes-from-python branch October 7, 2026 18:49
bplatz added a commit that referenced this pull request Oct 11, 2026
…e-config-integrity

Conflicts:
- parse/jsonld.rs: kept this branch's graph scope over #2022's narrower
  nested-node fix (7d894b7), whose tests (it_materialize_named_graph,
  it_query_fulltext) pass on it. Ported #2008's ill-typed DELETE literal
  (ill_typed_as_stored). where_reads_ledger_default calls main's
  names_default_graph, so a where reading urn:default (#2005) counts as
  reading the ledger's default graph.
- branch_validation.rs, merge/revert previews: the rejection stays a
  TransactError; a SHACL rejection keeps #2024's resolved results through
  describe().
- tx.rs: inline_shapes_policy beside #2024's violation_namespaces; dropped
  the convert_named_graphs_to_templates tests that #2008 removed with the
  function.
- stage.rs: the per-graph policy stays required (explicit-only SHACL)
  alongside main's sh:sparql constraint-failure handling.
- it_config_graph.rs, override_control_identity.rs, update docs: both
  sides kept.

shacl_tests.rs: main's twelve new SHACL tests create their ledgers through
create_shacl_ledger, as the rest of the file does; with SHACL explicit-only
they otherwise enforced nothing and failed.
q-qp-p pushed a commit to q-qp-p/fluree-db that referenced this pull request Nov 8, 2026
The cache sizes its directory with a walk that runs outside the state lock
(off-thread for the first sizing since fluree#2022, inline in evict_until), and
writes and evictions account their bytes after their file operation. A
scan landing between the two counted the operation twice or not at all:
a write whose file the walk saw was added again by its note_write, an
eviction the walk missed was subtracted again, and evict_until's total
overwrote whatever landed during its rescan. Two writes of one entry could
also both rename and both count. Each miss drifted the total by one entry
until the next evict_until rescanned.

Writes and evictions, evict_until's own removals included, now register
before their file operation, at most one per path, and account after it.
Every scan lands through one reconciliation: a path an operation changed
while the scan walked holds what that operation left, and an operation
still under way corrects the total by what it leaves when it lands. A
write registers in the lock it already took to read the size, so it takes
no extra lock; reads take none.

A disk-full write no longer leaves its partial temporary file behind,
where no accounting saw it and no eviction removed it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

2 participants