Skip to content

Rules see claims: executor-backed datalog, Turtle-star on every write path, in-round budgets, W3C RDF suites - #1823

Merged
aaj3f merged 23 commits into
mainfrom
feat/rules-see-claims
Sep 14, 2026
Merged

aaj3f merged 23 commits into
mainfrom
feat/rules-see-claims

Conversation

@aaj3f

@aaj3f aaj3f commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Why

For a scenario where a user models attributed claims as RDF 1.2 edge annotations and wants reasoning rules that read those claims — "trustedKnows if any claim on the edge has confidence > 0.85". Auditing that scenario from the CLI and docs turned up a cluster of gaps: rule bodies could not see annotations and the unsupported pattern was dropped silently (over-deriving), datalog results were never cached and ran on a quadratic matcher, the reasoning budget was checked per round only (and never for memory), Turtle-star was accepted by insert/import but refused by upsert, graph sync and memory import, the vendored W3C RDF 1.2 Turtle suite had no runner, and four doc pages described a Turtle-star restriction that had not existed for two releases.

Design record: docs/design/rules-engine.md. Audit notes: docs/audit/… is not touched; the durable audit artifacts live outside the repo.

What changed

Rules see claims (new datalog engine). Rule bodies are now parsed by the standard JSON-LD / SPARQL query parsers and executed by the planned query executor inside the fixpoint, so everything a query can express works in a rule: inline @annotation / {| |} / ~ ?r, claim-first @reifies / rdf:reifies <<( )>>, full FILTER expressions, BIND, VALUES, UNION, property paths. The old pattern matcher (fluree-db-reasoner/src/datalog.rs, fluree-db-query/src/datalog_rules.rs) is deleted; the new engine lives in fluree-db-query/src/datalog_rules/{parse,validate,execute}.rs.

Loud rejection. A rule that cannot run — OPTIONAL / MINUS / NOT EXISTS / FILTER(!EXISTS{}) / aggregates / SERVICE in the body, LIMIT or OFFSET on the body or a subquery, a head variable the body does not bind, a bare word or undefined prefix in a filter, an unregistered IRI, a stray JSON-LD keyword key — fails the query with an error naming the rule and the construct. This applies to stored f:rule definitions too: a broken stored rule now fails the query instead of being skipped with a log line. The expression walk is exhaustive rather than wildcard-terminated, so a new Expression variant is a compile error until someone decides what it means in a rule body.

IRI operands in JSON-LD filters. (= ?p ex:knows) compares by identity (previously the string "ex:knows"); <…> and http(s)://… atoms are IRIs; an undefined prefix stays a string at query level and is an error inside a rule.

Cache and budgets. Datalog materializations are cached under a key that includes a content hash of the rule set (stored and query-time) and the budget. Budgets are enforced per derived fact in datalog and inside each OWL 2 RL round, so a single large round cannot overshoot maxFacts; the datalog iteration cap reports capped_reason: "iterations". The derived-facts overlay keeps one Arc<[Flake]> plus three index permutations instead of four sorted copies.

The memory budget becomes real. max_memory_bytes was inert on main — nothing read it. Making it live needed three things beyond the accounting: it counts only derived facts, matching the fact budget and the overlay it bounds (it was charged for the whole seed delta, so a 3-fact closure over an 8,000-edge seed capped at "memory"); its default is derived from the effective fact ceiling rather than a flat 100 MB, which at 176 bytes a flake bound at roughly half the 1,000,000-fact default and made maxFacts unable to buy a larger closure; and it is settable on the same three surfaces as the other two — "reasoningBudget": {"maxMemoryMb": …} / # PRAGMA reasoning-max-memory-mb:, f:reasoningMaxMemoryMb, FLUREE_REASONING_MAX_MEMORY_MB.

Turtle-star on every write path. GraphCollectorSink records reifier attachments (Graph::reifications) and the Turtle→JSON-LD adapter emits them as @annotation blocks, so upsert, sync_named_graph / fluree sync, and the memory importer accept {| |}, ~ reifier and << s p o >> with the same bundles as a direct insert. Graph sync anchors lowered bundles to the target graph (f:reifiesGraph) — without that the stage-time invariant refused every synced annotation — and its accumulator counts each asserted fact once (FlakeAccumulator::mixed_set_assertions): the parallel-annotation shape states the base edge once per claim, which under counting semantics out-voted the sync wave's single retraction and committed a no-op delta on every re-sync. An annotated rdf:type edge is refused on the converted paths with a message naming the way out (JSON-LD @type values cannot carry @annotation).

Write-path invariants. The f:reifies* firewall now covers the Turtle transaction path (hand-written bundles were accepted before); the single-target reifier invariant runs on stage_flakes as well as stage, so one named reifier on two edges is refused on insert and upsert alike. That check is linear in the reifiers of a transaction, and it stamps the graph onto the bundle it scans — see the self-review section.

Chunk splitter. In compute_chunk_boundaries, << no longer enters the IRI scan state, so a > inside a string literal within a reified triple can no longer place a boundary mid-statement. That scanner is a public API with no caller in this tree outside its own tests; bulk import goes through StreamingTurtleReader, whose line-based scan never had the hazard and which now has its own star-statement test.

Turtle parser conformance. RDF 1.2 VERSION "1.2" / @version "1.2" . directive; base-direction language tags validated (--ltr / --rtl only, tag must start with a letter); PREFIX / BASE case-insensitive, @BASE rejected; repeated ;;; relative @base resolves against the base in scope; bare << s p o >> . statements.

W3C results. RDF 1.1 Turtle 302/313 (11 registered: numeric lexical-form canonicalization, IRI escape validation, dotted local names); RDF 1.2 Turtle syntax 59/67 (8 registered: <<( )>> triple terms); RDF 1.2 Turtle evaluation 0/29 (all registered: every expected .nt uses rdf:reifies <<( )>>, which the graph IR cannot represent). SPARQL 1.2 eval-triple-terms: construct-2 now passes; the remaining 29 entries re-attributed.

W3C suites in CI. testsuite-sparql/tests/w3c_rdf.rs runs the vendored RDF 1.1 Turtle (313 tests) and RDF 1.2 Turtle syntax (67) and evaluation (29) manifests through the collector-sink path, with registers policed both ways. The SPARQL 1.2 eval-triple-terms register is re-attributed (its Turtle-star data now loads). Overlap note: the unmerged RDF-toolkit PR #1569 carries a full testsuite-rdf crate; this runner is ~150 lines on the existing harness so main has coverage now, and one of the two should be retired when #1569 lands (staged as a follow-up).

Docs. docs/query/datalog-rules.md rewritten around the new engine; Turtle-star ingest documented as supported (transactions/turtle.md, concepts/edge-annotations.md, guides/cookbook-edge-annotations.md, reference/compatibility.md, reference/vocabulary.md); "retract one claim, keep the edge" recipe; CLI config-graph recipe; IRI filter operands; budget and cache rows.

Behavior changes to note

  • Rules with unsupported constructs now error instead of warn-and-skip (this is the fix for Datalog rule bodies silently ignore ["not-exists", …] — rules derive as if the negation weren't there #1786; stratified negation remains unsupported).
  • Migration edge: a ledger holding a stored f:rule in the nested-object shape the old docs showed now fails every datalog query on that ledger, not just that rule. The error names the two accepted shapes; the remedy is to retract the value or re-store it as {"@type": "@json", "@value": {…}} or an f:sparql CONSTRUCT.
  • A multi-head rule with one unbound head is rejected whole, where it previously derived the good head and warned about the other. Range restriction is per rule.
  • An uppercase ["FILTER", …] key in a JSON-LD rule body is now accepted and filters, where it previously had to be rejected: rule bodies go through the query parser, which accepts the case variant.
  • @BASE / @PREFIX (uppercase @-directives) and language tags such as @1 or @en--LTR are now parse errors.
  • An unquoted absolute URL in a JSON-LD filter is an IRI operand for every query, not only inside rules. A query comparing a string-valued property against a bare URL matched before and does not now; quote the operand. The array filter form is unchanged — it has no syntax for the distinction.
  • An annotated rdf:type edge through upsert / sync / memory import is refused (insert and SPARQL UPDATE accept it).
  • Datalog results are cached: a changed stored rule invalidates through the content hash; a changed ledger invalidates as before.
  • A relative IRI with no base in scope is an error rather than silently kept verbatim. @base <data/> . at the top of a file parsed before and does not now. Keeping it wrote a relative IRI into the store, and a relative IRI cannot identify a node, so the data was invalid in a way nothing downstream reported. The message now says to add an absolute @base or write the IRI in full.
  • A long @version / VERSION specifier is rejected, including one carrying an escape (@version """1\u002E2"""), which passed before because escape-bearing long and short strings lex to the same token kind.
  • Two f:rule values on one subject are refused by name. The second used to silently replace the first, in an order the author does not control.
  • did:, urn:, mailto: and the other non-hierarchical schemes are IRI operands in an identity comparison, like http:// already was. They used to classify as compact IRIs with an undefined prefix and fall back to strings, so (= ?id did:key:z6Mk…) matched nothing.
  • A prefix that a context aliases to a JSON-LD keyword ({"type": "@type"}) stays a string rather than expanding to a non-IRI like @typeadmin.
  • Computed SELECT columns and HAVING resolve compact IRIs, as FILTER already did. (as (= ?p ex:knows) ?isKnows) was always false and now matches what the same comparison matches in a filter.
  • Re-pointing a claim at a different fact through sync or upsert now succeeds. It was refused with a message advising the caller to do what it had already done.
  • Upsert is idempotent for blank-node-rooted structures: its skolem ids are scoped to the payload, so re-applying a file no longer duplicates every anonymous claim, OWL restriction and RDF list in it. Changing an anonymous claim's body still adds a second claim on upsert rather than replacing the first, because a different payload is a different scope. fluree sync scopes to the target graph instead, so there the changed body replaces the claim. Naming the reifier gives replacement on both, and docs/transactions/turtle.md now carries the table.
  • push applies a commit that violates the single-target reifier invariant, logging it rather than refusing. Authoring still refuses. Older builds did not enforce the invariant on insert_turtle or bulk import, and refusing on push would strand such a ledger permanently to prevent data already written.
  • A hand-written f:reifies* triple inside a TriG GRAPH { … } block is refused, as it already was on every other surface.
  • An R2RML mapping file containing ~ r or {| … |} is refused rather than loaded with its attachments discarded.

Self-review follow-ups

After the first green CI run I reviewed the change again against its own claims, which turned up eight defects — six in the guard code this PR adds, none in the design. They are fixed in the four commits after 327eddb3e:

  • The single-target reifier check was quadratic, and this PR is what put it on the bulk Turtle insert and commit-apply paths. It re-scanned the whole flake vector twice per reifier; with ~5 flakes per annotation the flake count grows with the reifier count. Grouping by subject in one pass makes it linear: through insert_turtle on an optimized build, 9,000 annotated edges went 1.80 s → 0.14 s, and the growth rate ×8.9 → ×3.2 per ×3 of input. The commit this PR's own demo produces carries 130k reifiers. (That measurement had no binary store behind it, so it did not reach the second, larger cost — see the round-two section below.)
  • A named-graph bundle could not be rewritten once indexed. The check keys a reifier's current bundle against the transaction's by (graph, s, p, o, dt), but index-decoded flakes carry g: None while a named-graph transaction's carry g: Some(sid), so the two never matched and the net bundle decoded as MixedFlakeGraphs. Re-asserting an unchanged annotation, or adding a property to an existing claim, failed with an invariant violation on a legitimate write. The scanned side is stamped now, as scan_graph_flakes already does.
  • Four holes in the loud-rejection contract, each letting a rule run and derive: FILTER(!EXISTS{}) (which lowers to Not over a non-negated Exists — Datalog rule bodies silently ignore ["not-exists", …] — rules derive as if the negation weren't there #1786's own defect class in a different spelling, inside the PR that fixes Datalog rule bodies silently ignore ["not-exists", …] — rules derive as if the negation weren't there #1786), a subquery's own GROUP BY, a subquery's LIMIT, and a head variable bound only inside a FILTER (range restriction was reading referenced_vars where produced_vars is the predicate it wants). All four now reject by name, LIMIT/OFFSET on the body itself with them, and the negation walk tracks Not parity so !!EXISTS stays allowed.
  • The memory budget went live in an incoherent shape — charged for seed facts, defaulting below the fact cap, with no operator knob. See "The memory budget becomes real" above.
  • The cache test could not tell a hit from a recompute, and the rule-content hash it implied was unpinned: removing the hash by hand left the whole suite green. ReasoningCache now counts hits and misses, and the test pins both the hit and the re-materialization a changed rule forces.
  • The splitter fix protected a scanner production does not run, and the PR body said otherwise. Corrected above. The correction was itself incomplete — see the round-two section: nothing outside fluree-graph-turtle calls the splitter at all.
  • Smaller: the in-round budget check read the clock once per derived fact, which is a performance.now() call per fact on wasm32 — sampled every 1,024 now, with the round boundary still exact. Four documentation surfaces described something other than the code (the query-level filter change, the array-form divergence, how base-direction tags are stored, what rules_fired counts), and a fifth page still said Turtle ingest cannot parse annotation tails.

Round two: bplatz's review

A second review left 45 inline comments. All of them are folded in, in the nine
commits after 8f93dbebe; nothing was deferred that could be closed here. Four
were reproduced defects, and each is now pinned by a test that fails when only
its own fix is reverted.

Sync and upsert refused ordinary edits to annotated data. Deleting one
annotated line from a claims file and re-syncing, changing an anonymous-annotated
edge's object, and re-pointing a named claim through upsert all failed with
"would reify a malformed or multi-target edge" and advice to retract the prior
attachment in the same transaction — which the caller had done. Both paths hand
the accumulator the current state as retractions and the payload as assertions,
and matched pairs cancel, so a slot whose value does not change appears in
neither list. The cascade then saw the base edge retracted, decided the reifier
was orphaned, and retracted its whole bundle including those unchanged slots.
A reifier the transaction itself asserts a f:reifies* fact for is not
orphaned; the cascade leaves it alone, and the invariant still validates the
result.

Re-upserting was never a no-op. An edge with two claims asserted the base
edge twice (the adapter states it once per reifier) while the upsert wave
retracted the stored copy once, so an identical payload committed a delta every
time. Upsert's assertion side now has set semantics, as graph sync already did.
Separately, every blank-node structure in an upsert payload was skolemized under
a fresh per-transaction id, so upserting one file twice left two copies of every
anonymous claim in it. Upsert now scopes its skolem ids to the payload.

The single-target check was not linear on indexed ledgers. A reifier this
transaction just minted resolves in neither dictionary, and binary_range then
falls into a walk of the graph's entire novelty — one per annotation in the
file. On a file-backed ledger, indexed and then given unindexed novelty,
inserting 2,000 annotated edges:

novelty flakes before after
20,000 124 ms 52 ms
60,000 270 ms 52 ms

The remaining 52 ms is the insert. Isolating the scan, its cost grew 3.04× for
3× the novelty — linear, as expected — and is gone. The earlier 9,000-edge
figure above was measured without a binary store attached, so it never reached
this path.

Three paths accepted an annotation and then dropped part of it: TriG GRAPH
blocks had no reserved-predicate firewall; the R2RML loader read mapping files
through a collector that had quietly begun accepting reifiers it does not read;
and the memory importer lost annotations twice over, once when rebuilding
@fulltext value objects from an empty map and once when a payload split put a
blank-node claim body in a different transaction from the node naming it.

The rest were smaller but not cosmetic: a reifier legitimately reifies an edge
in two graphs (that is what COPY produces), and the invariant refused in one
transaction what two transactions could do; the Datalog fact ceiling returned
N+1 facts for a budget of N; max_facts truncated on 32-bit targets, turning
a raised ceiling into 1; a rejected language tag named a character that was not
where the message said; the iri function was documented as resolving against
a base that the JSON-LD surface does not have.

Two review items were resolved by answering rather than changing code, and both
answers are in the behavior list above: push applies a commit an older build
authored instead of stranding the ledger, and a stored rule naming a namespace
the ledger has not seen now warns rather than failing every reasoning query —
namespace existence is ledger state, not a property of a rule's text.

Checking one claim turned up something worth recording: nothing outside
fluree-graph-turtle calls extract_prefix_block, compute_chunk_boundaries
or StreamingTurtleReader. The importer chunks by its own route. The splitter
fix in this PR is correct and is pinned by the splitter's own test, but its
reach is that crate, not the bulk-import path — which an earlier commit message
here implied. Whether the splitter is dead code or a component something should
be using is filed as a follow-up.

Known limit

Rule bodies (like OWL 2 RL materialization) run at prepare time, before the query's fuel tracker and cancellation handle exist, so they are bounded by the reasoning budget's between-rule checks rather than cancellable mid-body. Threading the tracker into prepare-time materialization is staged as a follow-up.

Head-minting in rule heads (deferred)

A rule head that mints an annotated edge (provenance on derived facts) is rejected by name for now. docs/design/rules-engine.md lays out the options; the recommendation is a deterministic anonymous reifier per derived triple (skolem of rule id + instantiated triple) as a follow-up.

Tests and gates

  • New: it_datalog_rules_annotations.rs (23 tests: every annotation form in rule bodies, stored rules, UNION/BIND bodies, rejections by name including the four contract holes, the !!EXISTS counter-case, cache hit + content-hash miss, in-round fact cap, IRI filter identity across all six spellings, Datalog JSON-LD rule parser silently mis-classifies bare keys, bare @type values, and JSON-LD keywords #1558 classification), it_turtle_star_write_paths.rs (7: upsert, re-upsert replaces the body, insert/upsert parity, type-edge refusal, single-reifier-two-edges refusal on both paths, graph sync + idempotent re-sync across an index boundary), it_import_turtle_star.rs (bulk import with VERSION header), three memory-budget tests including the first anywhere that trips capped_reason == "memory", the indexed named-graph rewrite test, OWL in-round cap test, adapter / sink / parser / splitter / lexer unit tests, memory-import and CLI sync unit tests.
  • Round two adds: three sync/upsert edit tests, two upsert idempotence tests, the anonymous-claim boundary, two cascade tests (one per cascade pass), the indexed-reifier scan guard, one reifier on one edge in two graphs in one transaction, replayed-commit acceptance versus authoring refusal, a stored rule naming an unseen namespace versus the same rule query-time, duplicate rule ids, IRI operand resolution across three positions, a multi-chunk import, and the long-@version and language-tag rejections.
  • Every regression test above was proven non-vacuous by reverting its fix and watching it fail. Four were not, on the first attempt, and were rewritten until they were: the named-graph one reached the invariant through sync, whose retraction wave cancels the bundle before the check sees it; the seed-fact one used a seed too small to cross the ceiling; the first cascade test's delete selected nothing because a bare 0.9 in SPARQL is an xsd:decimal while JSON-LD had stored an xsd:double, so the transaction committed having matched nothing; and the pass-2 cascade test hit the same literal-type trap. Where two fixes could have covered one test, each was reverted separately to confirm the mapping is one-to-one.
  • cargo test: fluree-db-api groups grp_misc, grp_reasoning, grp_query_reason, grp_transact, grp_import, grp_ledger, grp_query; unit tests of every touched crate; cargo clippy --all-targets --no-deps on touched crates; cargo fmt --all -- --check in both workspaces; testsuite-sparql W3C RDF and SPARQL 1.2 suites.
  • End-to-end with the CLI binary built from this branch (audit scripts replayed): fluree upsert -f claims-star.ttl and a re-upsert that replaces a claim body; fluree sync --graph … -f claims-star.ttl twice (second run a no-op); rules over claims on both surfaces; OPTIONAL / undefined-prefix rules rejected with the rule and construct named; hand-written f:reifies* refused on insert and upsert; one reifier on two edges refused; stored rules applied by ledger config.
  • Perf (audit e10, 100k annotated edges, same box): datalog rule knows ⇒ acquaintedWith 19.4 s → 0.31 s (RSS 170 MB); owl:TransitiveProperty closure probe under the default budget 78.8 s wall → 1.07 s, capped in-round; OWL 2 RL symmetric closure unchanged at 0.3 s.

CI status

All checks were green on 327eddb3e and on 8f93dbebe. The round-two commits
are pushed and re-running. Locally: every touched crate's tests, cargo clippy --all-targets --no-deps on each, and cargo fmt --all -- --check in both
workspaces including testsuite-sparql.

Two flakes to know about, neither caused by this PR.
it_iceberg_policy::authorization_crawl_preserves_policy_across_formatting_terminals
failed on this PR's earlier run (34661046112) and on main's own run at the
base commit (34588592126, the #1804 merge) with the five crawl rows in a
different order between the formatted and tracked terminals, then passed on the
next run; a test-side fix is staged separately.
it_bounded_overlay_translation::selective_brackets_stay_bounded failed once
under a full parallel cargo test -p fluree-db-api here and passed in
isolation, both with and without this branch's changes.

Issues

Fixes #1786
Fixes #1558
Fixes #1559
Partially addresses #1557 — the Debug-string dedup key is gone (typed fact key in a HashSet); the per-round overlay rebuild remains, now over one shared flake array; incremental append is the remaining item.
Follow-up: head minting (design record §"Reifier minting in rule heads"); the
Turtle parser leftovers in the RDF 1.1 register (numeric lexical forms, IRI
escape validation, dotted local names); write-time validation of f:rule
values; caching the parsed rule set so a reasoning cache hit does not still pay
for a parse; a byte-aware bound on the combined reasoning cache entry; keying
the annotation arena's multi-target detector by graph; and deciding whether the
Turtle splitter is dead code. Bodies are drafted and awaiting numbers.

… path, in-round budgets, W3C RDF suites

Rule bodies are now ordinary query WHERE clauses parsed by the standard
JSON-LD/SPARQL parsers and executed by the planned query executor inside
the fixpoint, so edge annotations (@annotation / {| |} / ~ ?r), claim-first
patterns (@reifies / rdf:reifies <<( )>>), full FILTER, BIND, VALUES, UNION
and property paths all work in rules. Constructs a fixpoint cannot evaluate
soundly, unbound head variables, undefined prefixes, bare words, stray
keyword keys and malformed stored rules fail the query with an error naming
the rule and the construct instead of being skipped with a log line. The old
pattern matcher is deleted. Datalog materializations are cached under a key
that hashes the rule set; budgets are enforced per derived fact (datalog)
and inside each OWL 2 RL round, the memory budget is accounted, and the
iteration cap is reported. JSON-LD filters compare unquoted IRI operands by
identity.

GraphCollectorSink records reifier attachments and the Turtle→JSON-LD
adapter emits them as @annotation blocks, so upsert, graph sync and memory
import accept Turtle-star with the same bundles as insert; sync anchors
bundles to the target graph and nets payload assertions as a set. The
f:reifies* firewall covers the Turtle transaction path and the single-target
reifier invariant runs on stage_flakes too. The Turtle parser gains the RDF
1.2 VERSION directive, base-direction tag validation, case-insensitive
PREFIX/BASE, repeated ';;', relative @base resolution and bare reified-triple
statements. testsuite-sparql runs the vendored RDF 1.1 and RDF 1.2 Turtle
suites with policed registers. Ten doc pages updated; design record in
docs/design/rules-engine.md.

Fixes #1786
Fixes #1558
Fixes #1559
Partially addresses #1557
@aaj3f aaj3f added enhancement New feature or request area:datalog Reasoner, rules, reasoningDefaults area:transact Staging, commit, import/bulk-import, novelty, retraction semantics labels Sep 12, 2026
std::time::Instant::now() traps on wasm32; the reasoner's fixpoint already
goes through fluree_db_core::clock::Instant, and the old matcher did too.
A reified triple's contents are ordinary terms, so a '>' inside one of its
string literals ended the bogus IRI scan and the next '. ' was taken for a
statement boundary, splitting a bulk-import chunk mid-literal. Resolve '<'
on the following byte instead. Also records the prepare-time tracker limit
in the rules-engine design record.
fluree-db-docs embeds every page under docs/ and fails its
every_embedded_page_is_published_or_an_extra check for a page that
SUMMARY.md does not link.
…ned side

Self-review of the reifier invariant this PR moved onto `stage_flakes` turned
up two defects, both invisible to the existing tests because they are
default-graph and novelty-resident.

The check re-scanned the whole flake vector twice per reifier: once to resolve
the bundle's graph and once to fold the reifier's own facts. With R reifiers in
a transaction of N flakes that is O(R x N), and since each annotation
contributes about five flakes, N grows with R — quadratic on exactly the shape
the check exists for. That was tolerable while it only ran on the JSON-LD
staging path; `stage_flakes` puts it on the bulk Turtle insert path and on
commit apply (push, import, restore), where one transaction carries every
reifier in a file. Grouping the reserved-predicate flakes by subject in one
pass makes it linear. Measured through `insert_turtle` on an optimized build:

     edges   before    after
     1,000    0.04s    0.02s
     3,000    0.20s    0.04s
     9,000    1.80s    0.14s

That is x8.9 per x3 of input before and x3.2 after, 12.9x faster at 9k edges.
The "gate on asserts" property is preserved: a reifier becomes work only when
the transaction asserts one of its facts, so retract-only and non-annotation
transactions still do no scanning.

Second, the check keys a reifier's current bundle against the transaction's by
(graph, s, p, o, dt), and the two sides populate the flake's graph field
differently. Index-decoded flakes come back with `g: None` — the graph is the
index they came from, not a field — while a named-graph transaction's flakes
carry `g: Some(sid)`. Once a named-graph bundle had been indexed the two sides
could never match, so the net bundle mixed `None` and `Some` and decoded as
`MixedFlakeGraphs`: re-asserting an unchanged annotation, or adding a property
to an existing claim, failed with an invariant violation on a legitimate
write. `scan_graph_flakes` already stamps the graph for this reason; the check
now does the same. Graph sync is unaffected (its retraction wave cancels the
unchanged facts before the check sees them), which is why this surfaced only
through a plain JSON-LD write.
Self-review of the loud-rejection contract found four constructs that reached
the fixpoint anyway. Each is the same failure the contract exists to prevent:
the rule runs, derives something, and nothing tells the caller the body did not
mean what it said.

`FILTER(!EXISTS { … })` was accepted. The walk matched `Exists { negated:
true }`, which is how `NOT EXISTS { … }` lowers, but `!EXISTS` lowers to `Not`
wrapping a plain `Exists`, so the walk descended through the `Not`, found a
non-negated `Exists`, and allowed it — #1786's own defect class surviving in a
different spelling inside the change that closes #1786. In a fixpoint this is
unsound rather than unsupported: when the head predicate appears in the negated
pattern the answer depends on which round evaluated it, and is then cached. The
walk now carries the parity of the `Not` wrappers, so both spellings and any
odd nesting are rejected while `!!EXISTS` stays allowed, being monotone. The
expression match is also exhaustive now instead of falling through on a
wildcard, so a construct cannot hide inside a container the walker forgot —
which is how this one slipped past — and a new `Expression` variant is a
compile error until someone decides what it means in a rule body.

A subquery's own `GROUP BY` and `LIMIT` were never inspected: the walk recursed
into the subquery's patterns and looked no further. An aggregating sub-SELECT
computed counts inside the fixpoint, and a sub-SELECT with `LIMIT` kept
whichever row existed when it ran, so the rule's output changed with round
order. Both are rejected, along with `OFFSET`, and along with the same
modifiers on the rule body itself, which `build_rule` had been clearing
silently. `DISTINCT` and `ORDER BY` stay allowed: neither changes which
solutions exist as derivation grows.

Range restriction counted filter operands as bound. It read `referenced_vars`,
which includes operands a pattern only reads, so a head variable mentioned
solely inside a `FILTER` passed the check and then derived nothing at runtime
with no diagnostic. It now reads `produced_vars`, the sibling primitive whose
documented meaning is "variables this pattern adds to the binding set" — empty
for filters, the target only for a bind, the SELECT list only for a subquery.
That is also the body's output projection, which stays correct because every
head variable is a produced variable once the check passes.

The rules documentation promised the subquery-aggregate restriction it did not
enforce; it now describes what the code does, including the negation spellings
and the LIMIT/OFFSET rule.
This PR made `max_memory_bytes` live for the first time — nothing on main read
it — and self-review found it went live in a shape that could truncate closures
that used to complete, with no way for an operator to raise the ceiling.

It was charged for seed facts. `derived_len` excludes re-added base facts from
the FACT budget and `into_derived_flakes` drops them from the overlay the
memory budget bounds, but the byte total counted them anyway. The whole seed
delta — every fact of every rule-relevant predicate, plus all rdf:type facts
when class rules are active — merges into the derived set at the end of round
one, so from round two on the memory cap was being spent on exactly the base
data the fact cap ignores. A 3-fact closure over an 8,000-edge seed capped at
`"memory"`. Both limits now count the same population.

Its default bound before the fact default. A flake is 176 bytes on a 64-bit
target before its names, so the flat 100 MB ceiling was about 530k ordinary
facts against a documented 1,000,000-fact default: memory decided first, and
raising `maxFacts` could not buy a larger closure. The default is now derived
from the effective fact ceiling at a generous per-fact allowance, so the fact
cap binds on ordinary data and the memory cap only fires when facts are
abnormally large — long IRIs, big string or JSON literals — which is the
failure it is there to catch.

And it had no knob. `f:reasoningMaxFacts` and `f:reasoningMaxSeconds` are
settable per query, per ledger and server-wide; memory was settable nowhere, so
a capped closure had no operator escape. It now has the same three surfaces:
`"reasoningBudget": {"maxMemoryMb": …}` / `# PRAGMA reasoning-max-memory-mb:`,
`f:reasoningMaxMemoryMb`, and `FLUREE_REASONING_MAX_MEMORY_MB`, resolved last
so an explicit value wins and the derived ceiling applies only when nothing
sets one.

Three tests cover it, including the first anywhere that trips
`capped_reason == "memory"` — the only previous assertion about that field
checked its default value. The coherence property is asserted directly in the
reasoner's own budget test, since reproducing it end to end would need a
closure of half a million facts.

Separately, the in-round check read the clock once per derived fact. That is a
vDSO call natively but a `performance.now()` call across the JS boundary on
wasm32, where `clock::Instant` is `web_time`. The fact and memory comparisons
stay exact on every call and the clock is now sampled every 1,024; the round
boundary still checks it exactly, so a short round is never left unchecked.
Follow-up items from the same self-review, all test and documentation.

The chunk-splitter guard added earlier protects `compute_chunk_boundaries`,
which has no caller in this tree outside its own tests: bulk import goes
through `StreamingTurtleReader`, whose boundary scan is line-based and never
had the IRI-state hazard. The guard is still right for a public API, but the
path production actually runs had no star coverage at all, so it has a test
now — four RDF 1.2 statements across four chunks with every reifier intact.
(The other half of that hunk is production-live: the streaming reader's prefix
extraction is what lets a bulk-imported file carry a `VERSION "1.2"` header.)

The cache test could not tell a hit from a recompute. It compared two runs'
tallies, which a recompute reproduces exactly on a four-triple ledger, and
asserted the global cache was non-empty, which any other test in the binary
satisfies. Entry counts cannot fix it either — the cache is process-wide and
tests run in parallel — so `ReasoningCache` now counts hits and misses, which
are attributable because each test's ledger name makes its key unique. The
test also pins the rule-set content hash: a widened filter must re-materialize
rather than serve the previous closure. Removing the hash from the key by hand
now fails that assertion; before, the whole suite still passed.

Three documentation surfaces were describing something other than the code.
Unquoted IRI operands in JSON-LD filters are a query-level behavior change,
not only a rules feature: an unquoted absolute URL used to lower to a string,
so a query comparing a string-valued property against a bare URL matched
before and does not now. That is written down, with the quoting fix. The array
filter form has no way to spell the distinction — every element is a JSON
string — so `["=", "?p", "ex:knows"]` still compares against the string, and
the escape hatch is `["iri", "<absolute IRI>"]`; `iri` does not expand
prefixes, which a test now pins across all six spellings. Base-direction
language tags are stored as an `rdf:langString` whose language is the whole
`en--ltr` string rather than as `rdf:dirLangString`, so `LANG()` returns
`en--ltr` and `langMatches` will not match it — accurate now in both the
Turtle and compatibility pages. And `rules_fired` counts derived facts per
rule, not rule applications.

Finally, a fifth page still told users the Turtle ingest paths cannot parse
annotation tails, and neither the Turtle page nor the cookbook said that an
anonymous `{| … |}` reifier is minted fresh per transaction — so re-upserting
a file adds a second claim instead of replacing the first, and every sync of
one commits a delta. Name the reifier when the file will be re-sent.
@aaj3f

aaj3f commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Went back over this one myself after the first green CI run, reading the change against its own claims rather than just re-reading the diff. That turned up eight things worth fixing — six in the guard code the PR adds, two in what the body says about it. All are addressed in the four commits above; the design is unchanged.

The single-target reifier check was quadratic (102c869c1). It re-scanned the whole flake vector twice per reifier, once to resolve the bundle's graph and once to fold that reifier's facts. At about five flakes per annotation the flake count grows with the reifier count, so the check was O(reifiers²) on exactly the shape it exists for — and this PR is what moved it onto stage_flakes, which is the bulk Turtle insert path and the path that applies a received or restored commit. Measured through insert_turtle on an optimized build:

annotated edges before after
1,000 0.04s 0.02s
3,000 0.20s 0.04s
9,000 1.80s 0.14s

×8.9 per ×3 of input before, ×3.2 after. Worth knowing because create --from claims100k.ttl writes 130,058 reifier bundles in one commit, and replicating or restoring that commit runs this check over all of them.

A named-graph annotation could not be rewritten once indexed (same commit). The check keys a reifier's current bundle against the transaction's by (graph, s, p, o, dt), and the two sides populate the flake's graph field differently: index-decoded flakes come back with g: None because the graph is the index they came from, while a named-graph transaction's flakes carry g: Some(sid). So once the bundle was indexed the two never matched, the net bundle mixed both and decoded as MixedFlakeGraphs, and re-asserting an unchanged annotation — or just adding a property to an existing claim — failed with an invariant violation on a legitimate write. scan_graph_flakes already stamps the graph for this reason; the check does now too. Worth calling out that my first regression test for this was vacuous: I reached the invariant through graph sync, whose retraction wave cancels the unchanged reifies facts before the check ever sees them. It only reproduces through a plain JSON-LD write, which is where the test lives now.

Four holes in the loud-rejection contract (e856cf818), each one letting a rule run and derive:

  • FILTER(!EXISTS { … }) was accepted. The walk matched Exists { negated: true }, which is how NOT EXISTS lowers, but !EXISTS lowers to Not wrapping a non-negated Exists, so the walk descended through the Not and allowed it. That is Datalog rule bodies silently ignore ["not-exists", …] — rules derive as if the negation weren't there #1786's own defect class surviving in a different spelling inside the change that closes Datalog rule bodies silently ignore ["not-exists", …] — rules derive as if the negation weren't there #1786 — and in a fixpoint it is unsound rather than merely unsupported, since a head predicate appearing in the negated pattern makes the answer depend on which round evaluated it, and it is then cached.
  • A subquery's own GROUP BY and LIMIT were never inspected — the walk recursed into the subquery's patterns and looked no further. An aggregating sub-SELECT computed counts inside the fixpoint; a sub-SELECT with LIMIT kept whichever row existed when it ran.
  • Range restriction counted filter operands as bound, because it read referenced_vars where produced_vars is the predicate its name claims. A head variable mentioned only inside a FILTER passed the check and then derived nothing, silently.

The negation walk tracks Not parity now, so both spellings and any odd nesting reject while !!EXISTS stays allowed (there is a test for the allow-case too — a blanket ban would have passed the rejection tests while quietly removing a legal construct). The expression match is also exhaustive instead of wildcard-terminated, so a construct can't hide in a container the walker forgot, which is how this one got in. LIMIT/OFFSET on the rule body itself reject as well, where build_rule had been silently clearing them. The docs promised the subquery-aggregate restriction they did not enforce; they now describe what the code does.

The memory budget went live in an incoherent shape (247d830d5). max_memory_bytes was inert on main, so making it live was effectively introducing it, and it had three problems at once. It was charged for seed facts, which derived_len excludes from the fact budget and into_derived_flakes drops from the overlay it bounds — a 3-fact closure over an 8,000-edge seed capped at "memory". Its flat 100 MB default bound before the 1,000,000-fact default (a flake is 176 bytes before its names), so memory decided first and raising maxFacts couldn't buy a larger closure. And it was settable nowhere, while the other two limits are settable per query, per ledger and server-wide. All three are fixed: derived-only accounting, a default derived from the effective fact ceiling, and maxMemoryMb / # PRAGMA reasoning-max-memory-mb: / f:reasoningMaxMemoryMb / FLUREE_REASONING_MAX_MEMORY_MB. There is now a test that trips capped_reason == "memory", which I believe is the first one in the tree.

Two claims that outran the code (4895314f5). The cache test couldn't distinguish a hit from a recompute — it compared two runs' tallies, which a recompute reproduces exactly, and asserted the global cache was non-empty, which any other test in the binary satisfies. Entry counts can't fix it either, since the cache is process-wide and tests run in parallel, so ReasoningCache counts hits and misses now. That also let me pin the rule-content hash the body advertises: removing it from the key by hand previously left the whole suite green, and now fails. Separately, the chunk-splitter guard I added protects compute_chunk_boundaries, which has no caller in this tree outside its own tests; bulk import uses StreamingTurtleReader, whose line-based scan never had that hazard. The guard is still right for a public API, but the body claimed a bulk-import fix it wasn't making. Corrected, with a star test on the path bulk import actually runs.

Also folded in: the in-round budget check read the clock once per derived fact, which is a performance.now() call across the JS boundary on wasm32 — sampled every 1,024 now, with the round boundary still exact. And four documentation surfaces were describing something other than the code: the unquoted-IRI filter change is a query-level behavior change and not only a rules feature (a query comparing a string-valued property against a bare URL matched before and doesn't now), the array filter form has no syntax for that distinction so ["=", "?p", "ex:knows"] still compares against the string (the escape hatch is ["iri", "<absolute IRI>"] — iri does not expand prefixes, which a test now pins across all six spellings), base-direction tags are stored as an rdf:langString carrying the whole en--ltr rather than as rdf:dirLangString, and rules_fired counts facts per rule rather than rule applications. A fifth page still said the Turtle paths can't parse annotation tails.

The PR body's behavior-change list was missing three entries the diff establishes, now added — including the migration edge that matters most: a ledger holding a stored f:rule in the nested-object shape the old docs showed now fails every datalog query on that ledger until the value is retracted or re-stored.

Every regression test above was proven non-vacuous by reverting its fix and watching it fail. Two weren't on the first attempt and were rewritten until they were.

The permutation layout's safety net compares every index order and a bounded
scan against independently sorted copies, which is what makes the layout safe
to touch. Its six flakes all shared a `t` and a datatype, though, so every
comparison was decided by subject, predicate or object and the comparators'
`t` and datatype arms were never reached — precisely the fields a permutation
can reorder without any earlier field noticing.

Three flakes that tie on (s, p, o) and differ only past that point close it.
Demonstrated by mutation: a permutation sort that drops the tie-break passes
the old six-flake body and fails this one.
@aaj3f
aaj3f requested review from bplatz and zonotope and removed request for bplatz September 14, 2026 16:19

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

Went through the datalog engine, the reasoner budget/cache changes, the JSON-LD filter/BIND operand change, and the Turtle parser/splitter/W3C runner. I did not get to the Turtle-star write-path changes (stage.rs, accumulator.rs, flake_sink.rs, the adapter, graph sync, memory import) in this pass.

Each inline comment says whether it was reproduced (a throwaway probe test on this branch) or found from code reading.

Would want fixed before merge

  1. Negation still reaches the fixpoint via EXISTS{…} = false, BIND(EXISTS…) and IF(EXISTS…) (reproduced)
  2. OWL2-RL can report a false capped: "facts" in round 1 on ledgers that already store their entailments (reading)
  3. Typed literals in rule heads aren't coerced, so derived dates come out as strings (reproduced)
  4. Unquoted (count *) in HAVING broke (reading)
  5. BIND/UNWIND IRI classification changes what JSON-LD updates write (reading)
  6. Unquoted URLs in string-function arguments silently turn into IRIs (reading)
  7. A query's maxMemoryMb is dropped when ledger-config reasoning modes apply (reading)
  8. A failed OWL pass gets cached as a complete owl2rl+datalog result (reading)
  9. Splitter IriEscaped directive bug drops data in streaming import (probe; predates the PR, but in an arm this PR edits)
  10. A relative @base with no base in scope is now a hard error, and it isn't in the behavior-change list

Design points to discuss: how far a broken stored rule's failure spreads (validity depends on namespace registration and engine version, so consider write-time validation), caching time-capped results, multi-valued f:rule being last-wins, and the non-exhaustive pattern walk.

General (not anchored to the diff)

  • Pre-existing, but it now interacts with this PR: the OWL2-RL cache key (fluree-db-reasoner/src/lib.rs:~216) has no graph id, while the new datalog key does. On a datalog miss for graph B, the OWL step can reuse graph A's closure at the same t, which then gets folded into B's combined entry. Plausible from reading; worth an issue.
  • The streaming-reader claim ("never had the hazard") is true for <</> specifically, but that reader has its own mid-statement split modes that predate this PR (probe-confirmed). A trailing comment ending in . on a non-final line (ex:s ex:p ex:o ; # see note.\n ex:q ex:r .) splits the statement. '''/""" inside a short string flips in_long_string, which suppresses later boundaries. Suggest narrowing the wording in the PR body and filing an issue.
  • Per CLAUDE.md, follow-ups should carry issue numbers. Head minting, the RDF 1.1 register leftovers, tracker/cancellation threading into prepare-time materialization, retiring one of the two W3C runners when #1569 lands, and the iceberg crawl-order test fix are all "to be filed" / "staged".

negated: bool,
) -> Result<()> {
match expr {
Expression::Exists {

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.

Correctness — negation still reaches the fixpoint (reproduced).

The Not-parity walk catches !EXISTS, but Exists can be negated by any operator that isn't Not. All three of these rules were accepted and derived facts on this branch:

FILTER(EXISTS { ?b ex:knows ?c } = false)
BIND(EXISTS { ?b ex:knows ?c } AS ?e) FILTER(!?e)
FILTER(IF(EXISTS { ?b ex:knows ?c }, false, true))

The self-referential form CONSTRUCT { ?b ex:leaf ?a } WHERE { ?a ex:knows ?b . FILTER(EXISTS { ?x ex:leaf ?a } = false) } also runs. It keeps facts that a later round's negation would have excluded, so the answer depends on round order, and then it gets cached.

Suggestion: invert the check. Allow Exists only where its truth value is used positively: as the direct FILTER operand, under And/Or, or under an even number of Nots. Reject it under any other Call (comparisons, IF, COALESCE, function args) and anywhere inside BIND/UNWIND. Tracking parity alone can't be made sound.

docs/query/datalog-rules.md:342 ("Negation is rejected in every spelling it has") needs updating either way.

new_delta: &DeltaSet,
out_of_time: impl FnOnce() -> bool,
) -> Option<&'static str> {
if derived.derived_len() + new_delta.len() > budget.max_facts {

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.

Correctness — possible OWL2-RL regression: false capped: "facts" in round 1 (from code reading).

In round 1 the seed facts are registered only in base_keys, not seen, so DerivedSet::contains returns false for them. Any rule that re-derives a fact that is already stored pushes it into new_delta, and this check then counts it via new_delta.len() (the memory arm has the same problem via new_delta.approx_bytes()). The old between-rounds check only looked at derived.derived_len() after the merge, which excludes base facts.

Scenario: a ledger that already stores its type hierarchy (DBpedia-style, where Student instances are also typed Person), or symmetric edges stored in both directions, with more than 1M re-derived facts under the default budget. On main it completes with ~0 derived facts. Here it caps partway through round 1, rules for the rest of the seed delta never fire, and the capped result is cached.

memory_budget_ignores_seed_facts doesn't catch this because its seed facts derive nothing.

Suggested fix: make contains also consult base_keys (every base-key fact is already in the seed delta and gets merged at the end of round 1). Add a test where the seed data already contains the entailments and exceeds maxFacts.

))
}
};
Ok(literal(value, explicit_dt.unwrap_or(default_dt), None))

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.

Correctness — typed literals in rule heads aren't coerced (reproduced).

{"@value": "2024-01-01", "@type": "xsd:date"} becomes FlakeValue::String tagged xsd:date. The SPARQL head path (head_from_triple, ~L624) does the same for "2024-01-01"^^xsd:date. The result is a flake whose datatype says date while its value is a string:

  • DATATYPE(?d) → xsd:date
  • YEAR(?d) → unbound on the derived fact, but 2024 for the same value asserted through a transaction
  • equality/range comparisons against real dates, and dedup against base facts, won't line up either

Suggestion: run heads through the same coercion the query lowering uses (coerce_value_by_datatype) at parse time on both surfaces, and reject the rule if coercion fails.

if looks_like_compact_iri(s) {
return UnresolvedExpression::Const(UnresolvedFilterValue::Curie(Arc::from(s)));
}
UnresolvedExpression::Const(UnresolvedFilterValue::Bare(Arc::from(s)))

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.

Regression — unquoted (count *) in HAVING no longer parses (from code reading).

An unquoted * used to fall through to UnresolvedFilterValue::String("*"). It now becomes Bare("*"), but the COUNT(*) arm in parse/options.rs:399 still matches only String(s) if s == "*". So "having": "(> (count *) 1)" now fails with "HAVING aggregate argument must be a variable". (count *) is the documented form (jsonld-query.md aggregate list). SELECT goes through a separate string path and isn't affected.

Fix: match String(s) | Bare(s) there, and add a HAVING (count *) test — nothing covers it today.

validate_var_name(var)?;

let expr = parse_filter_value(&arr[i + 1])?;
let expr = parse_expr_with_ctx(&arr[i + 1], ctx)?;

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.

Behavior change — BIND/UNWIND now change what transactions write (from code reading).

parse_expr_with_ctx is used for BIND and UNWIND as well as FILTER, and a plain JSON string goes through the s-expression atom classifier. In a JSON-LD update:

"where": [ … , ["bind", "?link", "http://example.org/home"]],
"insert": {"@id": "?s", "ex:link": "?link"}

this used to write a string literal and now writes a ref. ["bind", "?t", "ex:Done"] with ex in the context does the same. The PR body and jsonld-query.md describe the change as filter-only.

Either scope the IRI classification to FILTER operands, or document it as a write-affecting behavior change (release notes plus a test pinning the new shape).

Comment thread docs/design/rules-engine.md Outdated

The fact cap is checked inside a round, not only between rounds. Memory is now
accounted: each derived flake adds an estimate of its heap footprint, and
exceeding `max_memory_bytes` (the documented 100 MB default) caps the

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.

Docs drift in the design record. "(the documented 100 MB default)" is stale since the memory default became fact-derived. L112 says a bare word is rejected when "compared against a variable that only occurs in IRI position", but lint_unresolved_expr rejects every bare word regardless of position, which is what datalog-rules.md documents.

fixpoint; query results may be missing derived facts. \
Raise the budget via f:reasoningMaxFacts/f:reasoningMaxSeconds \
(ledger config), \"reasoningBudget\" (query), or \
FLUREE_REASONING_MAX_FACTS/FLUREE_REASONING_MAX_SECONDS (server)."

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. The datalog capped warning doesn't mention FLUREE_REASONING_MAX_MEMORY_MB / f:reasoningMaxMemoryMb; the OWL warning above does. Also, the DerivedFactsOutcome::diagnostics doc still says datalog-only reasoning returns None.

Comment thread fluree-db-query/src/lang_support.rs Outdated
@@ -19,7 +19,6 @@ use std::sync::OnceLock;

// Re-exported so the registering layer can construct [`SparqlRuleParts`]

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. An orphaned "Re-exported so the registering layer can construct…" comment is left behind now that the re-export is gone, and SparqlRuleParts (just below) has two stacked doc summaries.

Comment thread fluree-graph-turtle/src/parser.rs Outdated
self.advance()?; // consume @version or VERSION

match self.current().kind {
TokenKind::String | TokenKind::StringEscaped(_) => {}

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. A long string containing an escape lexes as StringEscaped, so @version """1\u002E2""" . gets past the short-string check and is accepted, even though long strings are meant to be rejected here.

if tag_ok && dir_ok {
Ok(TokenKind::LangTag)
} else {
Err(winnow::error::ErrMode::Cut(ContextError::new()))

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 — misleading error for the new strictness. "x"@en--LTR is rejected (correctly, per nt-ttl12-langdir-bad-2), but the error surfaces after the tag has been consumed and reads "unexpected character ' '". Users hitting the new rule will get a confusing message; an explicit "invalid language tag / base direction must be --ltr or --rtl" error would help.

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

Follow-up to the earlier review, covering the Turtle-star write paths (stage.rs, the adapter, graph sync, upsert, memory import) that it skipped. Each comment says whether I reproduced it with a throwaway test on this branch or found it from code reading.

Would want fixed before merge

  • Sync and upsert refuse ordinary edits to annotated data. Deleting a line from a synced claims file, changing an annotated edge's object, or re-pointing a named claim via upsert all hit the invariant (reproduced).
  • Re-upserting an anonymous annotation duplicates the claim (reproduced).
  • The single-target check walks all of a graph's novelty for each new reifier on indexed ledgers (reading).

Predates the PR, but in the code it touches: the edge-delete cascade leaves a live f:reifies* bundle after indexing in named graphs (reproduced, same g: None class as the fix here); the TriG GRAPH-block firewall gap.

Relation to #1832 (rdf:reifies triple terms and TriG-star inside GRAPH blocks; planned to merge after this one):

  • #1832 fills two gaps in this PR's "Turtle-star on every write path": TriG GRAPH blocks, where star is still rejected on this branch, and r rdf:reifies <<( s p o )>>, the only star form N-Triples and N-Quads have. Suggest the PR body says those are out of scope here and covered by #1832.
  • Not covered by #1832: every inline item above except the register heads-up, plus VERSION in TriG. #1832's base predates the VERSION token, but since it reworks trig_meta.rs, adding a VERSION arm during its rebase is the natural place.
  • Register interplay on rebase: see the registers/mod.rs comment.

let net_bundle: Vec<Flake> = net.into_values().collect();
if let Err(e) = EdgeKey::from_reifies_facts(&net_bundle) {
return Err(TransactError::InvariantViolation(format!(
"annotation subject `{ann_sid}` would reify a malformed or \

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.

Correctness: sync and upsert refuse ordinary edits to annotated data (reproduced).

Each of these was refused with this error on this branch:

  • Deleting the first annotated line of a claims file, then re-syncing. Sync A = ex:alice ex:knows ex:bob {| ex:confidence 0.9 |} . + ex:bob ex:knows ex:carol {| ex:confidence 0.5 |} .; sync B = just the second line. Result: Missing("f:reifiesPredicate"), and the ledger keeps the old contents.
  • Changing the object of an anonymous-annotated edge, then re-syncing. ex:alice ex:knows ex:bob {| … |} → … ex:carol {| … |}. Result: Missing("f:reifiesSubject").
  • Re-pointing a named claim through upsert. ex:alice ex:age 42 ~ ex:c1 . → ex:alice ex:age 43 ~ ex:c1 .. Result: Missing("f:reifiesSubject").

(Prepending a new annotated line re-synced fine.)

The error tells the user to "retract the prior attachment in the same transaction". Sync and upsert already do that. From reading, the cause looks like this:

  1. cascade_attachment_retracts retracts the old reifier's whole bundle, including slots this same transaction re-asserts, which the accumulator had already cancelled.
  2. The fold here therefore sees a partial bundle.

It is worse for anonymous annotations: sync labels are positional and the sync skolem is deterministic, so removing an earlier {| |} re-points every later one.

named_graph_annotation_survives_indexing_and_re_sync (L393) pins the re-point refusal as intended, which contradicts the error message's own guidance.

Suggestion: never cascade-retract a fact the transaction itself asserts, and consider skipping the cascade under sync_graph, since the sync wave already computes the exact delta. Also add tests for "delete a line" and "change an annotated edge's object" on a synced claims file.

let mut net: HashMap<ReifiesKey, Flake> = HashMap::new();
for f in current {
if is_reserved_reifies_predicate(&f.p) {
net.insert(reifies_key(&f), f);

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.

Correctness: the edge-delete cascade has the same g: None gap this stamp fixes (reproduced; predates the PR).

Setup: insert ex:alice ex:knows ex:bob with @annotation {"@id": "ex:claim1", …} into a named graph, rebuild the index, then DELETE DATA { GRAPH <g> { ex:alice ex:knows ex:bob } }.

  • Novelty only: the delete transaction retracts the edge plus all four claim1 f:reifies* facts.
  • After indexing: it retracts only the edge, so the claim's bundle stays live and points at a deleted edge.

Both passes of cascade_attachment_retracts (~L181-200 and ~L297-316) decode the scanned bundle with EdgeKey::from_reifies_facts without stamping g. An indexed named-graph bundle decodes as GraphMismatch, and the cascade continues past it.

The code isn't changed in this diff, but it's the defect class the self-review fixed here, and it needs the same stamp in both places plus a test. It will get more reachable once #1832 lands, since that adds TriG-star inside GRAPH blocks.

}

#[tokio::test]
async fn upsert_turtle_replaces_the_annotation_body_on_re_upsert() {

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.

Re-upserting an anonymous annotation duplicates the claim (reproduced).

This test covers only a named reifier (~ ex:claim1). Upserting ex:alice ex:knows ex:bob {| ex:confidence 0.9 |} . twice leaves two claims: {| ex:confidence ?c |} returns 0.9, 0.9. From reading:

  • each upsert skolemizes a fresh reifier;
  • the upsert wave skips blank subjects;
  • the base edge cancels, so no cascade runs.

"Replace the body, keep the edge" therefore holds only for named reifiers. Either document that, or give anonymous reifiers on the upsert path a deterministic identity (as sync does) and add the anonymous twin of this test.

} else if txn.sync_graph.is_some() {
// The payload is a set: a fact it states twice must not out-vote
// the sync wave's single retraction of the current copy.
FlakeAccumulator::mixed_set_assertions(64)

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.

Re-upserting parallel annotations is never a no-op (reproduced).

Upserting ex:alice ex:knows ex:bob ~ ex:c1 {| ex:confidence 0.9 |} ~ ex:c2 {| ex:confidence 0.7 |} . twice produced a second commit (t=2, asserts: 1, retracts: 0) for an identical payload. From reading, the base edge is stated once per claim, and the counting accumulator commits the surplus. The set-semantics fix is applied only under sync_graph. Consider applying mixed_set_assertions to upsert as well, or deduping the adapter's repeated base edges before they reach the accumulator.

Comment thread fluree-db-transact/src/stage.rs Outdated

// Current asserted `f:reifies*` bundle for this SID
// (pre-txn snapshot + novelty), as a deduped set.
let mut current = fluree_db_core::range_with_overlay(

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.

The single-target check isn't linear on indexed ledgers (from code reading).

The in-memory grouping is linear, but this runs one range_with_overlay per touched reifier, and a freshly minted reifier (every anonymous {| |} or << >>) is in neither the persisted dict nor DictNovelty. binary_range then falls into overlay_only_flakes, which walks the graph's entire novelty (for_each_overlay_flake(g, idx, None, None, …)). The cost is O(new reifiers × novelty) on bulk Turtle-star inserts and pushes.

The 9,000-edge measurement in the PR body probably didn't have a binary store behind it.

Suggestion: resolve the subject first and skip the scan when it is absent from both dicts (no prior bundle can exist), or do one grouped walk per graph, as hydrate_list_index_meta_for_retractions does. This is the same absent-subject shape as the overlay-only walk fixed for binary_scan in #1657.

// `emit_reified_triple` and builds a complete, validated bundle.
// Bulk import (`ImportSink`) is the administrative bootstrap path and
// deliberately stays permissive so an export round-trips.
if fluree_db_core::is_reserved_reifies_predicate(&p) {

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.

The firewall doesn't cover TriG GRAPH blocks (from code reading; predates the PR).

The upsert/builder TriG route sends GRAPH <g> { … } bodies through convert_named_graphs_to_templates (fluree-db-api/src/tx.rs). That path never reaches FlakeSink::build_flake and has no reserved-predicate check, so hand-written f:reifiesSubject … triples inside a named-graph block still land. #1832 changes that function (it emits the bundles for TriG-star) but doesn't add the check either. It's easy to add there, because user triples (block.triples) and generated attachments (block.reified) are already separate. Whichever PR owns it, "the firewall covers the Turtle transaction path" should say it excludes TriG GRAPH blocks until then.

}

#[test]
fn import_keeps_turtle_star_annotations_as_annotation_blocks() {

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.

The memory importer can still lose annotations (from code reading).

  • Fulltext fields: inject_fulltext_value (L381) rebuilds mem:content / mem:rationale value objects as {"@value", "@type": "@fulltext"} and drops any @annotation. So mem:content "…" {| ex:source ex:hr |} imports the text, loses the attachment, and leaves the claim body as an orphan node. This test annotates ex:supersedes, so it doesn't reach that path.
  • Batch splitting (plausible): transact_batch (file_sync.rs:~367-393) splits payloads over 512KB into separate inserts, and blank nodes sort first. An anonymous reifier's body and the edge carrying its @annotation can then land in different transactions and skolemize to different Sids.

/// that stays live across an annotation body; that is safe here because
/// literal slots are recycled only at `end_statement`, never inside a
/// statement (see [`Self::add_literal_term`]).
fn supports_reified_triples(&self) -> bool {

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.

Side effect: every GraphCollectorSink user now accepts Turtle-star silently. The R2RML loader (fluree-db-r2rml/src/loader/mod.rs:53) uses this collector and ignores reifications, so a mapping file containing {| |} or ~ r now loads with the attachments quietly dropped instead of being rejected. The trait doc above (~L290-295) still says "graph collectors … keep rejecting Turtle-star input". Either have the R2RML loader refuse a non-empty reifications, or add an opt-in constructor for the adapter and keep the default rejecting.

Comment thread fluree-db-transact/src/stage.rs Outdated
// `touched` keeps the "gate on asserts" property: a reifier is only work
// when the txn ASSERTS one of its facts, so pure retracts (which can only
// shrink a bundle) and non-annotation transactions stay at zero scan cost.
let mut by_reifier: HashMap<&Sid, Vec<&Flake>> = HashMap::new();

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: invariant grouping inconsistency. Grouping is by subject only, not (graph, subject). The same named reifier used in two graphs within one transaction decodes as MixedFlakeGraphs and is reported as "multi-target", while the same writes split across two transactions are accepted. Key by (g, s) or reject both consistently.

];

pub const RDF12_TURTLE_SYNTAX: &[&str] = &[
// triple terms as values (`<<( s p o )>>`, incl. nested) are deferred:

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.

Heads-up for when #1832 rebases onto this. #1832 implements r rdf:reifies <<( s p o )>> on Turtle, N-Triples and N-Quads (base triple asserted, same bundle as ~ r). nt-ttl12-1, -2, -3, -bnode-1 (and possibly -nested-1) are exactly that shape, so they should start passing, and the two-way register policing will fail the rebase until they're un-registered. The same probably applies to some RDF12_TURTLE_EVAL entries, whose expected .nt files use that form. The "graph IR cannot represent" rationale here and in the PR body will be stale at that point. The negative-syntax entries that currently pass only because every <<( )>> is rejected need a recheck then too. turtle12-3/-7/-8 use <<( )>> under ordinary predicates and should stay registered.

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

Approving: the direction is right, and this is a big step up (executor-backed rules, loud rejection, real budgets, and Turtle-star on the converted write paths).

Before merging, please work through the inline feedback in the two earlier reviews. Each comment is marked reproduced or from code reading. These are the items I'd treat as must-fix before merge:

Rules and reasoning

  • Negation still gets past the rule-body check via EXISTS{…} = false, BIND(EXISTS…) and IF(EXISTS…).
  • Typed literals in rule heads aren't coerced, so a derived xsd:date is stored as a string.
  • OWL2-RL can report a false "facts" cap in round 1 when re-derived facts are already stored.
  • A query's maxMemoryMb is dropped when ledger-config reasoning modes apply.
  • A failed OWL pass can be cached as a complete result.

JSON-LD parser

  • Unquoted (count *) in HAVING regressed.
  • BIND/UNWIND IRI classification changes what updates write.
  • Unquoted URLs inside string functions now turn into IRIs.

Turtle and write paths

  • Streaming import drops a statement after a PREFIX line whose IRI contains a \u escape.
  • Sync and upsert refuse ordinary edits to annotated data.
  • Re-upserting an anonymous annotation duplicates the claim.
  • The single-target check walks all of a graph's novelty for each new reifier on indexed ledgers.

The rest are design points, docs and nits. Splitting those into follow-up issues is fine, but please reference the issue numbers, per CLAUDE.md.

Related: #1832 (rdf:reifies triple terms and TriG-star inside GRAPH blocks) merges after this one. It covers the TriG GRAPH-block and rdf:reifies <<( )>> gaps this PR leaves open, but none of the feedback items above. On its rebase, expect the W3C RDF 1.2 register updates (see the registers/mod.rs comment) and the docs conflicts in edge-annotations.md, cookbook-edge-annotations.md and turtle.md.

Review found that the monotonicity guard and the atom classifier were both
scoped by shape rather than by position, and that both are only sound when
scoped by position.

Negation was still reaching the fixpoint. Counting `Not` wrappers catches
`NOT EXISTS`, `!EXISTS` and any odd nesting, but a truth value can be negated
by anything that reads it: `FILTER(EXISTS {…} = false)`, `IF(EXISTS {…}, false,
true)` and `BIND(EXISTS {…} AS ?e) FILTER(!?e)` are all negation, and all three
derived facts. Enumerating the negating operators cannot work either, because
`BIND` lets the negation happen arbitrarily far from the `EXISTS`. So the rule
is inverted: an `EXISTS` is allowed only where its truth value is read directly
and positively — the filter condition itself, or under `AND` / `OR` in such a
position — and every other position rejects by name. That is conservative
(`FILTER(EXISTS {…} = true)` is monotone and is refused), but it fails toward a
named error rather than a wrong answer that is then cached.

The pattern walk is exhaustive now as well, so `IndexSearch`, `VectorSearch`,
`GeoSearch`, `S2Search`, `R2rml` and `ShortestPath` no longer fall through a
wildcard. The graph-source ones are rejected by name: they read data the
fixpoint does not own and the reasoning cache key does not cover, so a derived
fact could outlive the source it came from. No rule surface builds them today,
so this is defensive — the protection that matters is that a surface which
starts producing one has to come back here first.

The atom classifier had the same shape of problem. Scoping it to "unquoted"
rather than to a position let it reach every argument, which regressed
`(count *)` in HAVING to a bare word, turned `(strStarts (str ?s)
http://example.org/p/)` into a string-versus-IRI comparison that matches
nothing, and — worst — changed what a transaction WRITES, since
`["bind", "?link", "http://example.org/home"]` inserted a ref where it used to
insert a literal. An unquoted atom now means an IRI only as the operand of an
RDF-term identity comparison (`=`, `!=`, `in`, `sameTerm`), which is the one
position where a string could never have matched anyway. Everywhere else it is
the string it has always been.

Head literals are coerced to their declared datatype, the conversion the query
lowering has always applied to template literals. A head wrote the value as
spelled and tagged it with a datatype it did not match, so
`{"@value": "2024-01-01", "@type": "xsd:date"}` derived a string labelled
`xsd:date`: `DATATYPE()` said date, `YEAR()` was unbound, range comparisons did
not line up, and the fact did not dedup against the same value asserted through
a transaction. Coercion is also a validity check — a value the datatype rejects
now fails the rule instead of being stored mislabelled.

And OWL 2 RL could report a false `capped: "facts"`. Round 1 registers the seed
in `base_keys` but not in `seen`, so `contains` answered false for it and every
rule that re-derived an already-stored fact pushed it into the round's delta,
where the in-round cap counted it. A ledger that stores its own entailments —
symmetric edges written both ways, a `Student` also typed `Person` — could cap
on facts it derives nothing from, and the truncated closure was then cached. A
400-edge symmetric ledger capped at 100 facts while deriving zero.

Budget plumbing fixed alongside: a query's `maxMemoryMb` was dropped whenever
ledger-config reasoning modes applied, because the mode replacement carries
each budget field across by hand and the new one was not on the list; a failed
OWL pass could be cached under a key that says OWL ran, serving later queries a
closure with no entailments after one transient storage error; a time-capped
result is no longer cached at all, since which closure you get would depend on
what else the machine was doing; `approx_flake_bytes` counts embeddings and
boxed arbitrary-precision numbers, which it had been counting as zero; and the
megabyte conversion saturates rather than truncating on 32-bit targets.
Both are cases where a read of stored facts silently disagrees with the
transaction editing them, and the disagreement was swallowed rather than
raised.

`cascade_attachment_retracts` scans a reifier's own `f:reifies*` facts and
decodes them with `EdgeKey::from_reifies_facts`, which reconciles the
bundle's `f:reifiesGraph` value against the flake-level `g`. Index-decoded
flakes carry `g: None` — the graph is the index they came from, not a field
on the flake — while the transaction's own flakes carry `g: Some(sid)`. An
indexed named-graph bundle therefore decoded as `GraphMismatch`, and the
cascade's `Err(_) => continue` dropped it on the floor. Deleting the base
edge left the claim that reifies it live, still pointing at a triple that no
longer exists; deleting the claim's last metadata fact left the bundle behind
as an orphan. Both passes now stamp the graph back before decoding, the way
`scan_graph_flakes` and `enforce_single_target_reifiers` already did. The
stamping is factored into one `stamp_graph` helper so the next scan that
needs it has something to reach for.

Only the named-graph-plus-indexed cell was affected: the default graph has
`None` on both sides and a novelty-resident bundle has `Some` on both, which
is why the existing cascade tests all passed.

The Turtle splitter had the same shape of bug. A SPARQL-style directive ends
at its operand rather than at a `.`, but an IRI containing a `\u` escape
lexes as `IriEscaped`, which the operand arm did not match. The directive
never closed, so the prefix block ran on to the next `.` and absorbed the
first data statement. Streaming import dropped that triple outright; the
directory-rechunk path, which prepends the prefix block to every chunk,
re-asserted it once per chunk instead.

Each of the three regression tests was checked against its own fix: removing
the pass-1 stamp fails only the base-edge test, removing the pass-2 stamp
fails only the orphan test, and neither fails the other. The cascade tests
count `f:reifies*` facts directly rather than querying the annotation
surface, which joins against the base edge and so cannot tell an orphaned
bundle from a retracted one, and they assert the bundle is visible before the
delete so the counter itself cannot pass them vacuously. The orphan test uses
a string-valued metadata fact deliberately: a bare `0.9` in SPARQL is an
`xsd:decimal` while JSON-LD stores it as an `xsd:double`, so the delete would
match nothing, commit anyway, and pass for the wrong reason.
Three ordinary edits were refused outright, each with the same shape of
error: deleting one annotated line from a claims file and re-syncing, changing
the object of an anonymous-annotated edge, and re-pointing a named claim
through upsert. All three reported that the reifier "would reify a malformed
or multi-target edge", and advised retracting the prior attachment in the same
transaction — which is exactly what the caller had done.

Sync and upsert both hand the accumulator the current state as retractions and
the payload as assertions, and matched pairs cancel, so the flakes that reach
staging are already the minimal delta. A slot whose value does not change
(usually `f:reifiesPredicate` and `f:reifiesGraph`) therefore appears in
neither list. `cascade_attachment_retracts` then saw the base edge being
retracted, decided the reifier was orphaned, and retracted its whole bundle —
including those two unchanged slots, which nothing re-asserted. The surviving
bundle was missing a slot and the invariant check refused it, correctly, for a
bundle the transaction never intended.

A reifier the transaction itself asserts a `f:reifies*` fact for is not
orphaned: it describes some edge after this transaction, and its bundle is the
transaction's to rewrite. The cascade now leaves those alone.
`enforce_single_target_reifiers` still validates the result, so a genuine
multi-target write is refused as before.

`named_graph_annotation_survives_indexing_and_re_sync` asserted the re-point
refusal as intended behaviour. It now asserts the re-point succeeds and that
the claim describes the edge the payload gives it.

Two upsert defects fall out of the same area.

Re-upserting a payload byte-for-byte identical to what was already stored
committed a delta every time. The Turtle-to-JSON-LD adapter states a base edge
once per reifier attached to it, so an edge with two claims asserted that edge
twice while the upsert wave retracted the stored copy once, and the surplus
assertion survived. Upsert's assertion side now has set semantics, which graph
sync already used for this exact reason.

Re-upserting an anonymous annotation duplicated the claim. Every blank-node
structure in an upsert payload was skolemized under a fresh per-transaction
id, so each run minted new subjects and the runs accumulated rather than
collapsing: upserting one file twice left two copies of every anonymous claim
in it, and of every OWL restriction and RDF list. Upsert now scopes its skolem
ids to the payload, the way graph sync scopes them to the target graph. Two
different payloads still get different scopes, so positional labels cannot
collide across unrelated upserts.

That leaves one deliberate asymmetry, now pinned by a test: changing the body
of an anonymous claim adds a second claim rather than replacing the first. An
anonymous claim has no identity its author can refer to, so upsert cannot know
the new body is meant to be the old claim. Naming the reifier is how you ask
for replacement.

`repro_upsert_repeated_ids_create_duplicate_subject_ids` asserted that its
second, identical upsert still committed. It now asserts the no-op, which is
what that test was reaching for in the first place.

Each of the five new tests was written before its fix and watched to fail.
`enforce_single_target_reifiers` scans each touched reifier's stored bundle
before deciding whether the transaction would leave it reifying two edges. On
an indexed ledger that scan is not cheap when it misses: a `Sid` neither the
persisted dictionary nor `DictNovelty` can resolve falls through
`binary_range` into `overlay_only_flakes`, which walks the graph's entire
novelty. Freshly minted reifiers are exactly that shape — every anonymous
`{| … |}` and `<< … >>` is one — so a bulk Turtle-star insert paid one
whole-novelty walk per annotation in the file, and the cost was the product of
the two.

A subject absent from both dictionaries provably has no prior bundle, so the
scan can only come back empty. `subjects_with_prior_rows` decides that for
every touched reifier in one pass, with a point probe against the base
dictionary and at most one novelty walk per graph. It reports "undecidable"
rather than "absent" when an already-indexed ledger has no binary store
attached, so a store that failed to load still surfaces through the scan
instead of silently skipping the check. `generate_upsert_deletions` skips
absent subjects for the same reason, and #1657 fixed the same shape in
`binary_scan`.

Measured on a file-backed ledger, indexed and then given unindexed novelty,
inserting 2,000 annotated edges:

    novelty flakes    before     after
    20,000            124 ms     52 ms
    60,000            270 ms     52 ms

The remaining 52 ms is the insert itself. Isolating the scan, its cost grew
3.04x for 3x the novelty — linear, as expected — and is now gone.

The earlier 9,000-edge figure in the PR body was measured without a binary
store attached, so it never reached this path at all.

`an_indexed_reifier_pointed_at_a_second_edge_is_still_refused` pins the other
half: a reifier that does resolve must still be scanned. Making the skip
unconditional fails it.
Each of these accepted an annotation and then quietly discarded part of it, so
the write reported success and the data said something the author did not.

TriG `GRAPH { … }` blocks had no reserved-predicate firewall. The JSON-LD,
SPARQL UPDATE and Turtle surfaces all refuse a hand-written `f:reifies*`
statement, because an attachment bundle is only well-formed if the annotation
syntax built it, but the TriG route goes through
`convert_named_graphs_to_templates` rather than `FlakeSink::build_flake`, so
such a triple landed and produced a bundle nothing validated. It is refused
there now, with the same message the other surfaces use.

The shared Turtle graph collector began accepting RDF 1.2 reifiers so the
Turtle-to-JSON-LD adapter could re-emit them, which also silently opted in
every other consumer of that collector. The R2RML mapping loader is one, and
it never reads the attachment list, so a mapping file containing `~ r` or
`{| … |}` loaded with its annotations discarded — a mapping quietly meaning
something other than what it says. It now refuses a non-empty list. The trait
doc still claimed graph collectors reject Turtle-star; it now says what is
actually true and where the responsibility sits.

The memory importer lost annotations two ways. `inject_fulltext_value`
rebuilds `mem:content` and `mem:rationale` value objects as `@fulltext`, and
rebuilt them from an empty object, so `mem:content "…" {| ex:source ex:hr |}`
imported the text, dropped the claim, and left the claim's body behind as a
node nothing pointed at. It now carries the attachment across.

Separately, the importer splits payloads over 512KB into separate
transactions, and a blank-node label only means something inside one
transaction. An anonymous annotation's body is a blank-node subject while the
`@annotation` naming it sits on another node, so a split between the two
skolemized them to different subjects and stranded the body. Chunking now runs
over groups rather than single nodes, where a group is a node plus the blank
subjects it reaches, transitively.
The single-target invariant grouped a transaction's `f:reifies*` flakes by
reifier alone. A bundle names its own graph in `f:reifiesGraph`, and
`EdgeKey::from_reifies_facts` checks graph uniformity before it checks
anything else, so folding one reifier's flakes from two graphs into a single
bundle reported `MixedFlakeGraphs` — surfaced to the user as "multi-target",
which it is not.

That state is one graph management produces on purpose: `COPY <g1> TO <g2>`
duplicates annotated edges, reifier IRIs included, and
`add_same_edge_same_reifier_succeeds` already pins that it must work. Two
transactions were therefore free to write what one transaction was refused.
Keying by `(graph, reifier)` removes the asymmetry in the direction the rest
of the system already takes.

A test helper had the same `g: None` blind spot the cascade did: it decoded a
reifier's bundle straight off an index scan, where the graph is the index the
flakes came from rather than a field on them, so an indexed named-graph bundle
came back as `GraphMismatch` and the helper reported a defect that was not
there. It now takes the graph from the bundle's own `f:reifiesGraph`.

The rest are small and independent.

The Datalog fact ceiling fired one fact late. The head was pushed and then
`len() > max_facts` tested, so a budget of N returned N+1 facts and nothing
trimmed the extra. The check now runs before the push, which also stops
charging the memory estimate for a fact that is never kept. `over_budget`'s
between-rules test matches.

`max_facts` was converted with `as usize`. On a 32-bit target a value past
`usize::MAX` wraps, so `"maxFacts": 4294967297` silently became 1 — a ceiling
the caller deliberately raised, turned into the smallest possible one. It
saturates now, like the memory conversion three lines below it that was
already fixed for exactly this.

Two documentation claims were wrong. The `iri` function was described as
resolving its argument against the base "like SPARQL's `IRI()`"; on the
JSON-LD surface there is no base, and the argument is used verbatim. A
comment in the annotation test suite repeated it. And a note dated a change to
4.2.0, which is already tagged — this ships after it.

Two more were imprecise rather than wrong. The filter-operand section said an
unquoted IRI is an IRI operand "in a filter expression", which has been true
only in identity-comparison position since the positional rule landed. And the
budget section said the budget is checked after every derived fact; it now
says the ceiling is checked before each fact is kept, and states the limit the
reviewer asked to see written down: the budget bounds derived facts, not a
rule body's intermediate binding rows.

Finally, a comment in `lang_support.rs` described a re-export that was deleted
with the old pattern matcher, and `SparqlRuleParts` carried two stacked doc
summaries. Both removed.
Two Turtle surface defects, both about a check that could not see what it was
deciding on.

The `@version` directive requires a short quoted specifier, and the check
tested the token kind. But `StringEscaped` is the escape-bearing slow path for
every string lexer, long forms included, so `"""1.2"""` produced the same
token kind as `"1.2"` and passed. Only an escape-free long string lexed as
`LongString` and got rejected. The hole covered `'''…'''` and the SPARQL-style
`VERSION` keyword too. The check now reads the token's span, where a long
string is distinguishable by its three opening quotes, and the error says
"short quoted version specifier" and names a long string as what it found.

A rejected language tag produced an error about the wrong thing in the wrong
place. The lexer returned a message-free `Cut`, so the text came from the
generic handler, which reports the token's start offset but names the
character at the *remaining* input — and the directive scan has already
advanced past the whole tag. `"x"@en--LTR .` therefore read "unexpected
character ' '" with the caret on the `@`: a character that is not where the
message says it is, and no mention of language tags. Rejections now explain
themselves, distinguishing a malformed tag from a malformed base direction.
Uppercase `--LTR` is a plausible-looking spelling, so naming the required one
is the whole fix a reader needs.

Both tests fail against their own code when it is reverted.
…le ids

Four places where the same expression meant different things depending on
where it was written.

Scheme classification was spelled by hand as `http://` and `https://`, so
every other scheme fell through to the compact-IRI branch, found no such
prefix, and became a string. `(= ?id did:key:z6Mk…)` therefore matched
nothing, and in a rule it was rejected outright as an undefined prefix — and a
`did:` operand is a common shape in policy. The classifier now asks
`check_unresolved_iri`, which JSON-LD expansion already uses and which knows
the non-hierarchical schemes.

A context may alias a JSON-LD keyword — `{"type": "@type"}` is ordinary — and
expanding `type:admin` through it produced `@typeadmin`, which is not an IRI
and can never match anything. Expansion now has to yield an absolute IRI
before the atom becomes an IRI operand; otherwise it stays the string it looks
like.

Computed SELECT columns and HAVING parsed their expressions without the
`@context`, so an unquoted `ex:knows` stayed a string there while the same
comparison in a FILTER became an IRI operand. `(as (= ?p ex:knows) ?isKnows)`
was always false, and the identical expression in a filter matched. An
absolute `http://…` was an IRI in both, which is what made the inconsistency
easy to miss. Both positions now get the same resolution the WHERE clause
gets, as a pass over the parsed query once the context is known.

Separately, `f:rule` is multi-cardinality like any other predicate, and a
stored rule's id is its subject, so a subject carrying two rule values kept
only whichever the index scan returned last — silently, and in an order the
author does not control. `add_rule` is now fallible and refuses a second rule
with an id it already holds, naming the subject. This is the same silent-drop
shape the rest of this work is closing: a reasoning query answered over a rule
set that quietly lost a rule is wrong, and being wrong is worse than failing.

Each of the four is pinned by a test that fails when only that fix is reverted.
…nest

The reasoning path collected every OWL-derived flake and rebuilt them into a
fresh overlay for datalog to read through, when OWL's own overlay already held
exactly those facts, the same `sameAs` and the same epoch — it is built
against this base overlay's epoch, and the `sameAs` was cloned from it.
Datalog now reads straight through it. The flakes are still collected, because
the final combined overlay needs them alongside the datalog derivations; what
is gone is the intermediate re-sort and re-permute, once per query.
`datalog_chains_off_owl_entailments` covers the path and fails if the overlay
is not handed over.

Three test corrections, all of which found something.

The reasoning-cache test asserted exact hit counts against a process-wide
counter while the rest of the binary runs in parallel, so any other test's hit
landed between two reads and shifted it. A race can only add hits, so the
assertions are now written in the direction that survives one: a hit that must
happen is `>=`, and the claim that a changed rule must MISS is carried by the
tally, which is per-query and cannot race — the cached closure holds two facts,
so reporting three could not have come from a hit.

The Turtle-star import suite claimed to drive the splitter, and did not: its
fixtures are a few hundred bytes, so the import ran as one work item. Forcing a
1 MB chunk and writing ~3 MB gives it a real multi-chunk import, and it pins
that every edge and claim crosses those boundaries exactly once.

That test still does not reach the splitter, and the comment now says so
rather than implying otherwise, because checking turned up something worth
recording: nothing outside `fluree-graph-turtle` calls `extract_prefix_block`,
`compute_chunk_boundaries` or `StreamingTurtleReader`. The importer chunks by
its own route. The escaped-IRI fix to prefix-block extraction is therefore
pinned where it actually runs, by the splitter's own test, which drives the
extractor and the streaming reader directly — not, as an earlier commit
message here implied, on the bulk-import path.

Finally, a relative IRI with no base in scope is an error rather than silently
kept verbatim, which is right — a relative IRI cannot identify a node, so
keeping it writes invalid data nothing downstream reports — but the message
said only what was wrong. It now says what to do about it.
Two checks whose failure reached much further than the thing they were
checking.

The single-target reifier invariant runs in `stage_flakes`, which put it on
the push path. `insert_turtle` and the permissive bulk-import sink did not
enforce it before this work, so a commit written by an older build can hold a
reifier on two edges — and push would refuse it, permanently, with no way
forward short of rewriting history, to prevent data that is already written.
`StageOptions::replaying_commit` marks flakes that come from an
already-authored commit rather than a transaction being authored now, and
makes authoring invariants advisory there: the violation is logged, naming
what will not decode, and the commit applies. Authoring still refuses it,
which is the case where refusing can still change the outcome. Push sets the
flag.

Rule validation refused a filter operand naming a namespace the ledger had
never seen, on the grounds that it can never equal a stored term. But whether
a namespace exists is ledger state, not something about the rule's text, and a
stored rule is re-validated on every reasoning query — so the check flipped a
stored rule between valid and invalid while the rule sat untouched, and one
invalid stored rule fails every datalog query on the ledger.
`FILTER(?src != <http://blocked.example/x>)` is correct, and true for every
row, and was refused until some `blocked.example` data happened to arrive.

Rules now carry where they came from. A stored rule logs the observation and
runs. A query-time rule still refuses: the author is present, the feedback is
immediate, and nothing persists. The marker is an explicit `RuleOrigin` rather
than something inferred from the id, so the next state-dependent check has to
say which side it belongs on.

Both tests drive the two sides through the same input, so the only difference
is the marker.
@aaj3f

aaj3f commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Worked through all 45 inline comments. Everything correct is folded in, across the nine commits from 58375cf95 to ccb1c0c81. Nothing was deferred that could be closed here, including the nits. Below is the accounting, and the places where checking a claim changed what I thought the answer was.

The four reproduced defects

Sync and upsert refused ordinary edits to annotated data (58375cf95, 17af9c7b6). All three repros fail exactly as described. The cause is what the review guessed. Both paths hand the accumulator the current state as retractions and the payload as assertions, and matched pairs cancel, so a bundle slot whose value does not change — typically f:reifiesPredicate and f:reifiesGraph — appears in neither list. cascade_attachment_retracts then saw the base edge retracted, decided the reifier was orphaned, and retracted its whole bundle including those two slots, which nothing re-asserted. The invariant refused the result correctly, for a bundle the transaction never intended.

The fix is the first half of the suggestion: a reifier the transaction itself asserts a f:reifies* fact for is not orphaned, so the cascade leaves it alone. Not the second half — skipping the cascade entirely under sync_graph would leave the changed slots un-retracted, and the net bundle would then decode as Duplicate instead. named_graph_annotation_survives_indexing_and_re_sync asserted the re-point refusal as intended behaviour; it now asserts the re-point succeeds and that the claim describes the edge the payload gives it.

Re-upserting parallel annotations was never a no-op (17af9c7b6). Applying mixed_set_assertions to upsert, as suggested. The accumulator's own doc comment already described this exact case for sync.

Re-upserting an anonymous annotation duplicated the claim (17af9c7b6). Changing the body duplicated it too, so there was no "replace the body" contract for anonymous reifiers to preserve. Rather than invent an identity scheme, upsert now scopes its skolem ids to the payload the way sync scopes them to the target graph — three lines, and it makes every blank-node-rooted structure in an upsert payload idempotent, not only annotations. repro_upsert_repeated_ids_create_duplicate_subject_ids asserted that its second identical upsert still committed; it now asserts the no-op, which is what that test was reaching for.

One asymmetry is deliberate and now pinned by a test: changing an anonymous claim's body adds a second claim rather than replacing the first. An anonymous claim has no identity its author can refer to, so upsert cannot know the new body is meant to be the old claim. Naming the reifier is how you ask for replacement.

The single-target check was not linear on indexed ledgers (6160a9542). Confirmed, and you were right that the 9,000-edge figure in the body had no binary store behind it — it never reached the path. Measured properly, on a file-backed ledger indexed and then given unindexed novelty, inserting 2,000 annotated edges:

novelty flakes before after
20,000 124 ms 52 ms
60,000 270 ms 52 ms

The remaining 52 ms is the insert. Isolating the scan, its cost grew 3.04× for 3× the novelty — linear — and is gone. Implemented as the first suggestion: resolve the subject first and skip the scan when it is in neither dictionary, factored into a helper that does one novelty walk per graph and answers for every candidate at once. It reports "undecidable" rather than "absent" when an indexed ledger has no binary store attached, so a store that failed to load still surfaces. an_indexed_reifier_pointed_at_a_second_edge_is_still_refused pins the other half: making the skip unconditional fails it.

The indexed named-graph cascade

You flagged it as the same g: None defect class the self-review had just fixed elsewhere, and reproduced it. Both passes are stamped now (58375cf95), and both are pinned: pass one by deleting the base edge, pass two by deleting the claim's last metadata fact. Removing either stamp fails exactly its own test and not the other's.

That work produced the most useful mistake of the round. My first pass-2 test deleted ex:confidence 0.9 via SPARQL, which types a bare 0.9 as xsd:decimal while JSON-LD had stored an xsd:double — so DELETE DATA matched nothing, the transaction committed at t=2 anyway, and every surface-level signal said the delete had worked. A cascade cannot fire on a delete that selected nothing, so the test would have passed for entirely the wrong reason. The tests now assert the bundle is visible before the delete, and use a string-valued metadata fact deliberately, with the reason written down.

Dropped attachments

All three confirmed and fixed in 56983797e.

The TriG GRAPH firewall gap is as described, and adding the check where user triples and generated attachments are already separate was as easy as you said. The R2RML loader now refuses a non-empty reifications rather than loading a mapping that quietly means something other than what it says; the trait doc that still claimed graph collectors reject Turtle-star now says what is true and where the responsibility sits. The memory importer lost annotations both ways: inject_fulltext_value rebuilt value objects from an empty map, and the batch splitter could put a blank-node claim body in a different transaction from the node naming it — chunking now runs over groups, where a group is a node plus the blank subjects it reaches transitively.

Where checking changed the answer

The invariant grouping. You offered "key by (g, s) or reject both consistently" without saying which. I went looking, and the decisive fact is add_same_edge_same_reifier_succeeds: the same reifier on the same edge in two graphs is a state graph management produces on purpose, because COPY <g1> TO <g2> duplicates annotated edges with their reifier IRIs. Rejecting consistently would make COPY of an annotated graph impossible. So it is keyed by (graph, reifier) (be8b02a2f), with a test that writes that state in one transaction — which used to be refused while two transactions were free to do it.

That leaves a real inconsistency I did not close: detect_multi_target_annotations in the annotation arena is graph-blind, and its warning says the transaction path rejects this at stage time. It does not, and should not. Filed as a follow-up rather than changed here, since it is the arena's key and its message, not this PR's.

Can push fail permanently on older commits? Yes, it could. Push goes through stage_flakes, which is where this PR put the invariant, and insert_turtle and the permissive import sink did not enforce it before — so a commit an older build wrote can hold a reifier on two edges, and refusing it would strand the ledger with no way forward short of rewriting history, to prevent data already written. StageOptions::replaying_commit now marks flakes that come from an already-authored commit and makes authoring invariants advisory there: logged, naming what will not decode, and applied. Authoring still refuses, which is where refusing can still change the outcome (ccb1c0c81).

How far a broken stored rule's failure spreads. Your first concern — that validity depends on ledger state — is the one I could close here. A stored rule is re-validated on every reasoning query, so a check consulting ledger state flips it between valid and invalid while the rule sits untouched, and FILTER(?src != <http://blocked.example/x>) is correct and true for every row. Rules now carry where they came from: a stored rule logs the observation and runs, a query-time rule still refuses because the author is present and nothing persists. The marker is an explicit RuleOrigin rather than something inferred from the id, so the next state-dependent check has to say which side it belongs on.

Your second concern — engine-version dependence and the upgrade risk — is a release-notes and tooling question rather than a code change, and write-time f:rule validation needs two decisions before it can be built (whether it blocks or degrades, and what happens to a rule that validates today and not after an upgrade). Both are in the staged follow-up, along with a sketch for a fluree rules check command so an operator can see the answer before upgrading. The seam exists: lang_support.rs already carries the registration pattern for calling the rule parser from the transact side.

The splitter. Chasing the "this test doesn't exercise the splitter" note turned up more than the note claimed. The import suite's fixtures really were under the chunk size, and it now forces a 1 MB chunk and writes ~3 MB. But it still does not reach the splitter, because nothing outside fluree-graph-turtle calls extract_prefix_block, compute_chunk_boundaries or StreamingTurtleReader — the importer chunks by its own route. So the escaped-IRI fix is correct and is pinned by the splitter's own test, which drives the extractor and the streaming reader directly, but its reach is that crate rather than the bulk-import path, which an earlier commit message here implied. The comment in the import test now says so, and whether the splitter is dead code or something that should be in use is a follow-up.

Atom resolution

All three sub-items in e55f60b67, each pinned separately.

Scheme classification now goes through check_unresolved_iri, which JSON-LD expansion already uses — matching http:// and https:// by hand was what made did:key: and urn:uuid: look like compact IRIs with undefined prefixes. Expansion has to yield an absolute IRI before an atom becomes an IRI operand, which keeps keyword aliases like {"type": "@type"} from producing @typeadmin. And computed SELECT columns and HAVING get the same resolution the WHERE clause gets, as a pass over the parsed query once the context is known.

Nits

All of them.

The @version hole was wider than reported: StringEscaped is the escape-bearing slow path for every string lexer, so '''…''' and the SPARQL-style VERSION keyword were affected too. The check reads the token's span now.

A rejected language tag returned a message-free Cut, so the text came from the generic handler, which reports the token's start offset but names the character at the remaining input — already advanced past the whole tag. Rejections explain themselves now, distinguishing a malformed tag from a malformed base direction, because uppercase --LTR is a plausible-looking spelling and naming the required one is the whole fix.

The fact cap was off by one and kept the extra fact; the check runs before the push now, which also stops charging the memory estimate for a fact that is never retained. max_facts as usize truncated on 32-bit targets exactly as the memory conversion three lines below it did before it was fixed. The iri base-resolution claim was wrong in the docs and in a test comment. The orphaned comment in lang_support.rs described a re-export deleted with the old pattern matcher, and SparqlRuleParts carried two stacked doc summaries.

Two of your notes were already stale against the branch — the 100MB figure in the budget docs and the approx_flake_bytes undercount were both fixed in 603b16bc0. The mb half of the wasm32 truncation was fixed there too; the max_facts half was not, and is now.

run_body materializing every batch before any budget check is real and unchanged. It is a sentence in the budget docs, as you suggested, rather than a fix: the budget bounds derived facts, not a rule body's intermediate binding rows.

Also changed

The reasoning path collected every OWL-derived flake and rebuilt them into a fresh overlay for datalog to read through, when OWL's own overlay already held those facts with the same sameAs and the same epoch. Datalog reads straight through it now (811ac8324). The flakes are still collected because the final combined overlay needs them; the intermediate re-sort is gone. The other two efficiency notes — the second copy in an entry-count-bounded LRU, and load_rule_set running before the cache lookup — need their own design (a byte-aware bound, and a cheaper key that does not require parsing to compute) and are in the follow-up list.

The cache hit-counter flake was real. The counter is process-wide and the rest of the binary runs in parallel, so the assertions are now written in the only direction a race cannot fake: a hit that must happen is >=, and the claim that a changed rule must MISS is carried by the tally, which is per-query — the cached closure holds two facts, so reporting three could not have come from a hit.

One more flake, found rather than inferred: it_bounded_overlay_translation::selective_brackets_stay_bounded failed once under a full parallel run and passed in isolation, both with and without this branch. Recorded in the follow-ups.

The @base change is real and was undisclosed, so it is in "Behavior changes to note" now, with an actionable message. I kept the strict behaviour rather than restoring lenience: a relative IRI cannot identify a node, so keeping it verbatim wrote invalid data that nothing downstream reported.

Still open

VERSION in TrigMetaParser and nquads_to_trig, and the RDF 1.2 negative-test registers, both belong to #1832's rebase and are written up in the staged follow-ups with what to re-check. Every follow-up above has a drafted issue body; they need numbers before the PR body's Follow-up: line can name them.

All gates are green locally: every touched crate's tests, clippy on each, and fmt in both workspaces including testsuite-sparql.

`assert_eq!(x, false)` and `>= n + 1` are both denied under `-D warnings`.
Neither changes what the assertions mean: the first becomes `assert!(!x)`, and
`hits() >= hits_before + 1` becomes `hits() > hits_before`, which is the same
comparison on integers and reads as what it checks.

Caught by CI, not locally, because `cargo clippy` reported the crate clean from
a cached result — the last edit before that run was in this test file, and the
test target was not re-linted. Forcing the target to rebuild reproduces it.
…essed

Two documentation pages told readers that a bare `{| … |}` block mints a fresh
reifier on every ingest, so re-upserting a file adds a second claim and every
`fluree sync` run commits a delta. Neither half is true now, and the sync half
was never true.

What is true, established by running each case rather than reading for it:

    re-sending the same file    sync      upsert
    unchanged payload           no-op     no-op
    changed annotation body     replaced  second claim added

Sync scopes blank-node identity to the target graph, so the same source label
names the same reifier across payloads and a changed body lands on the claim
already there. Upsert scopes it to the payload, so a changed body is a
different payload and mints a different reifier. Naming the reifier gives
replacement on both. The pages say that now, with the table, and the cookbook
points at it rather than repeating a summary that can drift out of step again.

Both sync cells are pinned by tests, which is what the behaviour was missing:
it had been described in prose twice and asserted nowhere, which is how the
description came to disagree with the code. The two upsert cells were pinned
earlier in this round.
The typed-literal head coercion landed on the JSON-LD surface only, and the
SPARQL surface was worse than the defect it was meant to fix: the declared
datatype was not mislabelled, it was discarded. The same head, same data, the
only difference being which surface wrote it:

    rule head                                  DATATYPE(?d)   YEAR(?d)
    JSON-LD {"@value": …, "@type": xsd:date}   xsd:date       2024
    SPARQL  "2024-01-01"^^xsd:date             xsd:string     unbound

`head_from_triple` reads the datatype from the template's `dtc` and otherwise
guesses one from the value. `lower_construct_template` built that template
through `lower_triple_pattern`, which ends at `TriplePattern::new(s, p, o)`
and leaves `dtc` unset — correct for a WHERE pattern, where a constraint would
change what matches, but a CONSTRUCT template is written rather than matched.
So `coerced_literal` ran with `xsd:string` as its target and coercing a string
to a string changed nothing.

The template now lowers its object with the constraint, the way the RDF-star
and annotation paths already did. That leaves `lower_triple_pattern` with no
callers, and it is removed rather than left behind: its whole behaviour was
dropping the datatype, and the next person to reach for it would be reaching
for this bug.

Both tests added with the original fix used the JSON-LD `insert` shape, which
is why nothing caught this. There are now SPARQL counterparts of each.

The coercion one is a true twin and fails when the datatype carry is reverted.
The rejection one is deliberately not: on this surface `lower_typed_literal`
parses the literal while lowering the template, so a value its datatype cannot
accept never becomes a head at all, and the refusal comes from lowering rather
than from coercion. It passes with or without the carry. Its comment says so,
and says which layer owns the check on each surface, rather than implying it
proves something it does not.

Also: the colliding-rule-id error had lost its line continuations, so it
rendered with eighteen literal spaces mid-sentence, and its parenthetical
promised to name the two colliding rules while always printing the same name
twice — two rules collide precisely because they share a subject, and a rule's
name is that subject decoded. The parenthetical is gone. A scan of every
string literal changed in this round found no other collapsed message.
@aaj3f

aaj3f commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my own accounting above: one of the 45 landed on half the surfaces it needed.

The typed-literal head coercion covered JSON-LD rule heads only. Your comment asked for it at parse time on both surfaces, and the SPARQL path turned out to be the worse of the two shapes you described — the declared datatype was not mislabelled there, it was discarded:

rule head DATATYPE(?d) YEAR(?d)
JSON-LD {"@value": "2024-01-01", "@type": "xsd:date"} xsd:date 2024
SPARQL "2024-01-01"^^xsd:date xsd:string unbound

head_from_triple reads the datatype from the template's dtc and otherwise guesses one from the value. lower_construct_template built that template through lower_triple_pattern, which ends at TriplePattern::new(s, p, o) and leaves dtc unset. That is right for a WHERE pattern, where a constraint changes what matches, but a CONSTRUCT template is written rather than matched, so coerced_literal ran with xsd:string as its target and coercing a string to a string did nothing.

The template now lowers its object with the constraint, the way the RDF-star and annotation paths already did. That left lower_triple_pattern with no callers and it is removed rather than left behind, since dropping the datatype was its entire behaviour.

Both tests I added with the original fix used the JSON-LD insert shape, which is exactly why nothing caught this. There are SPARQL counterparts of each now. The coercion one is a true twin and fails when the datatype carry is reverted. The rejection one is deliberately not a twin: on the SPARQL surface lower_typed_literal parses the literal while lowering the template, so a value its datatype cannot accept never becomes a head at all and the refusal comes from lowering rather than coercion. It passes with or without the carry, its comment says so, and it records which layer owns the check on each surface instead of implying it proves something it does not.

Two smaller things in the same commit. The colliding-rule-id error had lost its line continuations and rendered with a run of literal spaces mid-sentence, and its parenthetical promised to name the two colliding rules while always printing the same name twice — two rules collide precisely because they share a subject, and a rule's name is that subject decoded. A scan of every string literal changed in this round found no other collapsed message.

W3C suites run green here, which is the check that matters for a change to CONSTRUCT lowering: SPARQL 36 tests, RDF 3 suites, plus the full workspace. All nine CI checks green at 12a413749.

@aaj3f
aaj3f merged commit ed8f1f2 into main Sep 14, 2026
16 checks passed
@aaj3f
aaj3f deleted the feat/rules-see-claims branch September 14, 2026 21:59
aaj3f added a commit that referenced this pull request Sep 14, 2026
`cargo fmt` joins a `\`-continued string literal onto one line and the
continuations become the indentation they were hiding, so the message reached
the user with runs of eighteen spaces mid-sentence. Same mechanism that
produced this in the colliding-rule-id message during #1823, reintroduced here
by writing the new message the same way.

`concat!` is immune: each piece is its own literal, so there is nothing for fmt
to reflow. Worth preferring for any message long enough to want wrapping.

Found by running the CLI built from this branch rather than by reading the
source, which is also how the original instance was found.
aaj3f added a commit that referenced this pull request Sep 15, 2026
`detect_multi_target_annotations` counted live edges per annotation IRI
across every graph, so `COPY <g1> TO <g2>` — which duplicates annotated
edges with their reifier IRIs — made a correct ledger warn about itself,
and the warning claimed the transaction path rejects the shape when it
does not. The staging twin, `enforce_single_target_reifiers`, has keyed by
`(graph, reifier)` since #1823 for the same reason; this is the read-side
half that was never aligned. A comment now points each at the other so the
two rationales cannot drift apart again.

The offender list needed one further correction. It is built from a map
keyed by `(graph, reifier)` but reports reifiers, so a reifier that offends
in two graphs arrives twice; `dedup` ran before `sort_unstable`, and
`Vec::dedup` only collapses adjacent equals. With `HashMap::iter` as the
source — reseeded per map — the pair was collapsed only when the hash order
happened to put the entries side by side, and one fixed input reported 2 or
3 offenders depending on the run. Sorting first makes the dedup total.

`the_offender_count_does_not_vary_between_runs` loops 500 times precisely
because a single pass passes under the bug better than half the time: as a
one-shot assertion it would have been a flaky test rather than a failing
one. Reverting only the two-line swap fails it at `left: 3, right: 2`.
aaj3f added a commit that referenced this pull request Sep 15, 2026
`detect_multi_target_annotations` counted live edges per annotation IRI
across every graph, so `COPY <g1> TO <g2>` — which duplicates annotated
edges with their reifier IRIs — made a correct ledger warn about itself,
and the warning claimed the transaction path rejects the shape when it
does not. The staging twin, `enforce_single_target_reifiers`, has keyed by
`(graph, reifier)` since #1823 for the same reason; this is the read-side
half that was never aligned. A comment now points each at the other so the
two rationales cannot drift apart again.

The offender list needed one further correction. It is built from a map
keyed by `(graph, reifier)` but reports reifiers, so a reifier that offends
in two graphs arrives twice; `dedup` ran before `sort_unstable`, and
`Vec::dedup` only collapses adjacent equals. With `HashMap::iter` as the
source — reseeded per map — the pair was collapsed only when the hash order
happened to put the entries side by side, and one fixed input reported 2 or
3 offenders depending on the run. Sorting first makes the dedup total.

`the_offender_count_does_not_vary_between_runs` loops 500 times precisely
because a single pass passes under the bug better than half the time: as a
one-shot assertion it would have been a flaky test rather than a failing
one. Reverting only the two-line swap fails it at `left: 3, right: 2`.
bplatz added a commit that referenced this pull request Sep 15, 2026
…iple-term

Brings in #1823 (rules see claims), which put Turtle-star on the
upsert / graph sync / memory-import paths through GraphCollectorSink —
the same parser this branch taught `r rdf:reifies <<( s p o )>>` and
TriG GRAPH-block star forms.

Conflicts were docs only; each keeps both sides' facts:
- concepts/edge-annotations, cookbook-edge-annotations, transactions/turtle:
  main's per-path coverage, anonymous-reifier re-send semantics, VERSION
  directive and rdf:type caveat, plus this branch's rdf:reifies <<( )>>,
  N-Triples / N-Quads, and GRAPH-block annotations. Main's "TriG: default
  graph only" and "<<( )>> rejected at parse time" lines are dropped.
- reference/compatibility merged cleanly but carried the same two stale
  limits; corrected here.

Build fix: main's `named_graph_block_refuses_a_reserved_reifies_predicate`
builds a NamedGraphBlock without this branch's `reified` field.

testsuite-sparql/Cargo.lock picks up fluree-db-query's indexmap dependency,
which main's lock was already missing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:datalog Reasoner, rules, reasoningDefaults area:transact Staging, commit, import/bulk-import, novelty, retraction semantics enhancement New feature or request

Projects

None yet

2 participants