Skip to content

fix(turtle): a redeclared prefix must change what later names mean - #1565

Merged
aaj3f merged 5 commits into
mainfrom
fix/turtle-prefix-redefinition
Aug 5, 2026
Merged

aaj3f merged 5 commits into
mainfrom
fix/turtle-prefix-redefinition

Conversation

@aaj3f

@aaj3f aaj3f commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Two correctness fixes against main

Both found while building the RDF toolkit, both independent of it, both small enough that one review slot beats two.

  1. fix(turtle) — a redeclared prefix silently didn't change what later prefixed names meant. Data corruption, no error.
  2. fix(api) — a literal NUL byte in an admin.rs comment made the whole file binary to every text tool, so plain grep reported "no match" for patterns that occur 23 times in it.

1. A redeclared prefix must change what later names mean

Silent data corruption in the Turtle parser. Turtle allows a prefix to be rebound part-way through a document; the parser ignored the rebinding for any prefixed name it had already seen.

@prefix e: <http://a/> .   e:x <http://p/> "1" .
@prefix e: <http://b/> .   e:x <http://p/> "2" .

Both statements land on <http://a/x>. The second should be <http://b/x>. No error, no warning — the document says one thing and the graph holds another.

Cause

prefixed_term_cache is keyed by span text (e:x). That text identifies an IRI only relative to the bindings in force when the entry was made, and nothing invalidated it when a binding changed.

Two neighbours were not affected, and the PR pins both so the scope is demonstrated rather than asserted:

  • iri_term_cache keys on the resolved IRI, so a different base produces a different key and never collided.
  • @base redeclaration was always correct — a prefix namespace is resolved once, when its directive is read, and prefixed names never consult the base at lookup time.

Fix

On a prefix directive, clear the expansion cache if the prefix rebinds to a different namespace. Only if.

Redeclaring the same binding is the common case rather than a curiosity: chunked import prepends the file's prefix block to every chunk over a pre-seeded prefix map, so the parser sees each prefix declared twice by construction. Every cached expansion stays correct through that, and clearing there would cost hit rate across the entire import path for no correctness gain.

The per-term path is untouched. The diff adds no instruction to resolve_prefixed_term or sink_term_iri — the only executable change is inside the prefix-directive handler. Added work is one hash lookup per prefix directive, of which a document has a handful, against a cache consulted once per prefixed name, of which it has millions. That is a structural property of the diff, not a benchmark result; a wall-clock A/B on this host was noise-dominated (a 4× swing between runs of identical code under concurrent load) and is not offered as evidence.

Clearing is coarse on purpose: a rebind invalidates only that prefix's entries, but finding them means scanning every key, so we drop them all. A per-lookup epoch check would make rebinding O(1) at the cost of a comparison on every cache hit — the wrong trade when the overwhelming majority of documents rebind nothing.

The comparison is on meaning, not spelling, and both directions matter. parse_prefix_directive resolves the namespace before storing it, so prefixes holds resolved IRIs. The same spelling under two different bases (@prefix e: <a/> under <http://x/> then under <http://y/>) names two namespaces and must clear; two spellings that resolve alike (<http://x/a/> and <a/> under <http://x/>) name one and must not. Comparing raw text would get each backwards.

The "only when" needs its own guard

Clearing on a same-binding redeclaration produces identical triples — just colder — because iri_term_cache absorbs the repeated work before it reaches the sink. So a mutation deleting the condition passed every gate in the first version of this PR; confirmed by running it, with all eleven triple-level tests still green.

The cache hit/miss counters are the only place the behaviour is observable, so a test-only parse_reporting_cache exposes them and two tests read them: same-binding redeclaration must leave the cache warm (1 hit, 1 miss), a real rebinding must drop it (0 hits, 2 misses). The same mutation now fails the first.

Blast radius — honest version

This is not serial-only. Bulk import is affected, and this fix is necessary but not sufficient there.

The PrefixAfterData guard lives in compute_chunk_boundaries (the whole-file pre-scan behind TurtleChunkReader). Import does not use that reader. fluree-db-api/src/import.rs uses StreamingTurtleReader exclusively, which has no such guard — verified empirically: a 4000-statement file with a mid-file redefinition is accepted, its extracted prefix block is only the head binding @prefix e: <http://a/> ., and the redefinition is delivered in a chunk like any other data.

So a mid-document redefinition reaching import hits two independent defects, and prefix_redefinition_blast_radius.rs executes the split rather than asserting it. The corpus is 4000 statements of e:s{i} <http://p/> e:tag . with a redefinition half way through, parsed the way import parses it (prelude seeded, prefix block prepended).

The e:tag object is the load-bearing part. It repeats on every line, so it is cached under the first binding and requested again after the rebinding — which is the only shape in which this bug can appear at all. Counting inside the carrier chunk (the one that actually contains the redefinition), post-redefinition triples whose object still resolves to http://a/tag:

  1. Carrier chunk — 379 stale without the fix, 0 with it. This is the cache bug, and this assertion is what distinguishes the fix; verified by reverting the parser to the merge base. Fixed here.
  2. Later chunks — 1621 subjects mis-resolved. The head-extracted prefix block is prepended to each chunk, so they parse with the original binding and never see the redefinition. Not fixed here; that is the §1.4 chunker work (mid-file directive detection → serial fallback), and it needs the splitter, not the parser.

An earlier version of this test used a literal object and asserted only that no subject was mis-resolved in the carrier chunk. That was vacuous — every subject is a distinct span, so no prefixed name was ever looked up twice and the cache was never consulted for a span it held. It passed against a parser with the fix entirely removed. Caught in review; the corpus and the assertion above are the remediation.

The later-chunk defect is asserted live (> 0) rather than #[ignore]d: an ignored test runs nowhere and rots, while this one fails the moment §1.4 lands and tells whoever closed it to come here. The 1621 is a printed diagnostic, not part of the assertion, so ordinary chunking changes cannot make it flap.

Also noted, not addressed: PrefixCheck only matches a directive keyword at line start, so even the guarded pre-scan path would miss … . @prefix e: <…> . written mid-line. Same §1.4 bucket.

Discovery

Found while wiring term validation for H-8 (burn-down cause C), when a probe of the prefix path returned two statements on one subject. Nothing about it is specific to validation — it reproduces on plain parse, on main at 5598ffd6a, with no feature flags.

Tests

Ten, in fluree-graph-turtle/tests/prefix_redefinition.rs. Eight fail without the fix (verified by stashing the parser change and re-running). The two that pass either way are @base and same-binding redeclaration — the pair that shows the fix is scoped correctly rather than accidentally.

Covered: the verbatim repro; SPARQL-style PREFIX; other prefixes left alone; rebinding back and forth; the default (empty) prefix; namespace-only names (e:); same-binding redeclaration as a no-op; the pre-seeded-map shape chunked import uses; @base unaffected; and a 1000-statement case where a partial invalidation would show as a partial failure.


2. Name U+0000 in a comment instead of embedding one

fluree-db-api/src/admin.rs line 283 carried a literal NUL byte inside a comment that meant to name the character — "callers can otherwise sneak a <NUL> past". The lines immediately above spell the same class correctly (U+0000..=U+001F, U+007F); this is the one that got away.

The cost is not cosmetic. A single NUL makes the whole file binary to every text tool:

  • file(1) reported it as data, not source.
  • Search behaviour then splits by grep implementation, and naming which one matters:
    • ugrep 7.5.0 — what grep resolves to in the dev environment this was found in — exits 1 and prints nothing for a pattern occurring 23 times in the file. Not "binary file matches", not a warning: a clean, confident "not found".
    • BSD grep 2.6.0-FreeBSD (/usr/bin/grep, GNU-compatible; what CI and most contributors get) prints Binary file … matches and exits 0. It withholds the matching lines but does not lie about the match.

So the severe reading holds for anyone on ugrep and the milder one for everyone else — both worse than a file that simply works. After: file reports UTF-8 text and both greps find all 23. (An earlier draft of this claim asserted the silent-exit-1 behaviour universally; it was measured in one shell. Corrected on review.)

Comment-only and byte-precise — one line, the NUL replaced by the text U+0000. 670 fluree-db-api lib tests unchanged, full suite re-run at the tip.

Found by the control-byte guard built for the RDF-toolkit work, which flagged this as its second literal NUL; the first was in a Turtle test fixture and is fixed on that branch. Riding here rather than standing alone because a one-byte PR against main is not worth its own review slot.


Gates

Gate Result
nextest turtle + graph-ir + json-ld + format + transact + vocab 720 passed, 0 failed
nextest -p fluree-db-api (full) 2929 passed, 11 skipped
clippy --all-targets --no-deps 0 warnings
cargo fmt --all --check clean
cargo check --all-targets on excluded testsuite-sparql / testsuite-shacl clean

@aaj3f
aaj3f requested review from bplatz and zonotope July 30, 2026 13:37
aaj3f added a commit that referenced this pull request Jul 30, 2026
…he fix

The blast-radius test's `wrong_in_carrier == 0` proved nothing. Verified
before fixing: with `bind_prefix` deleted outright — the parser reverted to the
merge base, no fix at all — BOTH tests in the file still passed.

The corpus was the problem. Subjects were `e:s{i}`, a distinct span every time,
and predicates were full IRIs, so no prefixed name was ever looked up twice.
The expansion cache was never consulted for a span it already held, which is
the only shape in which a stale entry can be served. The test walked the whole
blast radius and never touched the defect it was named for.

Every line now carries `e:tag` as its object. It is cached under the first
binding and requested again after the rebinding, so a stale cache serves the
old namespace for a span whose meaning has changed. The new assertion counts
post-redefinition triples inside the CARRIER chunk — the one that actually
contains the redefinition — whose object still resolves to `http://a/tag`:

  fix removed (parser at merge base):  379   -> assertion FAILS
  fix present:                           0   -> assertion passes

`wrong_in_carrier` stays 0 in both cases, which is the demonstration that it
was never the discriminating assertion.

Kept unchanged: the subject-index chunk attribution, and the §1.4 tripwire on
later chunks. The tripwire's count moved 1438 -> 1621 with the corpus, which is
why it remains a printed diagnostic and an inequality rather than an equality —
ordinary chunking changes must not make it flap.

Found by an independent adversarial review of #1565. Two doc corrections ride
along: the meaning-vs-spelling cases are pinned in the ADVERSARIAL file (they
need a moving `@base`, which the other file never varies), and the clearing
comment now states the real trade — `retain` scans every key too, so the cost
is the same order; what it would buy is keeping other prefixes warm, and what
it costs is a predicate that has to compare up to the colon, since the obvious
`starts_with(prefix)` evicts `ex:name` when `e` rebinds. Simplicity over
post-rebind hit rate, not cost over cost.
aaj3f added a commit that referenced this pull request Aug 3, 2026
…he fix

The blast-radius test's `wrong_in_carrier == 0` proved nothing. Verified
before fixing: with `bind_prefix` deleted outright — the parser reverted to the
merge base, no fix at all — BOTH tests in the file still passed.

The corpus was the problem. Subjects were `e:s{i}`, a distinct span every time,
and predicates were full IRIs, so no prefixed name was ever looked up twice.
The expansion cache was never consulted for a span it already held, which is
the only shape in which a stale entry can be served. The test walked the whole
blast radius and never touched the defect it was named for.

Every line now carries `e:tag` as its object. It is cached under the first
binding and requested again after the rebinding, so a stale cache serves the
old namespace for a span whose meaning has changed. The new assertion counts
post-redefinition triples inside the CARRIER chunk — the one that actually
contains the redefinition — whose object still resolves to `http://a/tag`:

  fix removed (parser at merge base):  379   -> assertion FAILS
  fix present:                           0   -> assertion passes

`wrong_in_carrier` stays 0 in both cases, which is the demonstration that it
was never the discriminating assertion.

Kept unchanged: the subject-index chunk attribution, and the §1.4 tripwire on
later chunks. The tripwire's count moved 1438 -> 1621 with the corpus, which is
why it remains a printed diagnostic and an inequality rather than an equality —
ordinary chunking changes must not make it flap.

Found by an independent adversarial review of #1565. Two doc corrections ride
along: the meaning-vs-spelling cases are pinned in the ADVERSARIAL file (they
need a moving `@base`, which the other file never varies), and the clearing
comment now states the real trade — `retain` scans every key too, so the cost
is the same order; what it would buy is keeping other prefixes warm, and what
it costs is a predicate that has to compare up to the colon, since the obvious
`starts_with(prefix)` evicts `ex:name` when `e` rebinds. Simplicity over
post-rebind hit rate, not cost over cost.
aaj3f added a commit that referenced this pull request Aug 3, 2026
…close

`prefix_redefinition_blast_radius.rs` arrived with #1565 from main, where two
of its assertions pinned DEFECTS rather than properties, deliberately, so they
would fail the moment the chunker workstream landed and send whoever closed
the gap here. Both fired on the integration branch. This is that visit.

What actually changed is not "the chunker now handles such a file". It
REFUSES it: a mid-file directive makes a document unchunkable — only the first
chunk would carry the redefinition — so the reader thread raises
`PrefixAfterData` and stops.

The important part is how that refusal reaches a consumer, because the old
test is what made it look alarming. `recv_chunk` reports the closed channel as
a benign `Ok(None)`, so a consumer that only drains sees a SHORT READ AND NO
ERROR: 1797 of 4000 statements on this corpus. The error lives on the reader
thread and only `join()` surfaces it. Every live import call site joins, and
`import.rs` carries a comment saying exactly why. The old test drained without
joining, which is why it read as truncation.

So the replacement asserts the distinguishing fact rather than the symptom:
drain, then join, and require `Err(PrefixAfterData)`. That is the assertion
that tells "refused" apart from "silently truncated", and it would fail if the
join contract were ever dropped.

`the_guard_misses_a_mid_line_directive` becomes
`the_guard_catches_a_mid_line_directive` — detection now fires at any token
start, not just at line start.

The parser property the file also carried — a prefixed name reused across a
rebinding must follow the rebinding rather than the span cache — was entangled
with the chunk-carrier machinery, which no longer exists because there is no
carrier chunk. It is now its own test on a document that is never chunked,
since it is a property of the parser either way.

One latent hazard noted, not fixed: `ImportSource::recv_next` returns
`Ok(None)` on a closed channel without joining. It has no callers today; a
future one would inherit the silent-short-read shape.
aaj3f added a commit that referenced this pull request Aug 3, 2026
The flip the plan predicted: `a_mid_file_directive_falls_back_to_serial_rather
_than_refusing` asserted that exactly one term after a mid-file rebinding
denotes the new namespace. It is two, and the second one is the fix.

The trailing statement is `ex:z ex:p "z" .`, so its subject AND its predicate
both sit after the rebinding. Before #1565 only the subject moved: `ex:z` is a
span the document had never used, while `ex:p` had been expanded 80,000 times
and came back from the span cache under the old binding. Asserting one
occurrence was asserting the bug. The count is now two and the last line is
pinned whole, so it cannot drift back to one for some unrelated reason.

Fold-ins recorded at the wave close, applied here because this is where the
branches converged:

- The dead-reader comment claimed receiver ownership stops workers and the
  shutdown flag only makes them prompt. The reviewer's four-way mutation table
  says otherwise: either mechanism ALONE keeps the run live, and only removing
  both hangs. The old phrasing reads as though the flag were an optimization,
  which invites deleting a second liveness guarantee that no single-mutation
  test can catch. Restated as: either alone suffices, keep both, and the
  mutation that proves it removes both.

- `list_items_land_in_the_default_graph_because_the_protocol_has_no_quad_form`
  is now `list_items_without_a_graph_land_in_the_default_graph`. The protocol
  HAS the quad form — `emit_quad_list_item` landed with the M2 work — so the
  old name asserted a reason that had stopped being true.

- `chars::unicode_escape_value` documents the one hazard its signature cannot
  express: it takes `&str`, so it can never see a partial UTF-8 sequence, but a
  caller slicing RAW BYTES can panic before reaching it. Both current readers
  slice a `&str` at their own scanner's positions, so the class is structurally
  out of reach for them — a third reader over `&[u8]` would have to bound its
  own slice. The guarantee lives at the call site, not here.

- The CLI tests' `EXIT_DOCUMENT_INVALID` was a bare `1`. It now binds to
  `fluree_db_cli::error::EXIT_ERROR`, so the assertions track the contract
  instead of a literal that would keep passing if the binary's code changed.

@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 fix is correct, minimal, and the reasoning behind it is written down rather than assumed. One ask before merge (inline on the blast-radius test), plus three optional notes.

Verified by mutation rather than by reading

  • Removing the fix (if false && rebinds, i.e. merge-base behaviour): lib a_rebinding_drops_the_cached_expansion fails, prefix_redefinition.rs fails 8 of 10, adversarial fails 6 of 9, blast-radius fails 1 of 2. The body's claim — eight fail, and the two survivors are @base and same-binding redeclaration — is exactly right, down to which two survive.
  • Clearing unconditionally (if true): caught only by a_same_binding_redeclaration_keeps_the_cache_warm. All 21 triple-level tests stay green. That is the whole case for parse_reporting_cache, and I would have pushed back on adding a test-only parse path without seeing it.
  • Confirmed in code, not just in the prose, that resolve_iri_term resolves before calling sink_term_iri — so iri_term_cache really does key on the resolved IRI and the @base immunity claim holds. The sinks are safe too: PreludeSink appends in document order (last wins on seed), FlakeSink allocates a code per distinct namespace (both are genuinely present in the document), GraphCollectorSink only records.

The "only when it rebinds" condition, the resolved-vs-raw comparison argued in both directions, and the coarse whole-cache clear are all the right calls.

The ask

The two load-bearing assertions in prefix_redefinition_blast_radius.rs go vacuous below a 16 KB chunk size — measurements inline. Short version: with the parser fix removed and the chunk size changed to 4096, the test passes. It sits one power of two above a cliff, and it is the same vacuity the earlier review already caught once, reproduced along a different axis.

Optional, worth a quick look

Three inline: the parse_with_prefixes_base seeding loop bypasses bind_prefix; the two deliberate reverse-assertions print messages that read backwards at the only moment they ever appear; and the prefixed_term_cache field doc still carries the pre-fix framing that the method doc was correctly moved away from.

The admin.rs half

Right, and the severe reading of it reproduces here. With ugrep 7.5.0 resolving grep, on main:

grep -c "ledger" fluree-db-api/src/admin.rs   ->  (nothing), exit 1
/usr/bin/grep -c "ledger" (same file)         ->  222, exit 0
file(1)                                       ->  "data"

A clean, confident "not found" for a pattern that occurs 222 times. It is also the only .rs file in the repo carrying a NUL. Worth its ride-along.

// is greater than zero (verified by reverting the parser to merge-base).
// With it, every one of them resolves to the new namespace.
assert_eq!(
stale_objects_in_carrier, 0,

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.

This is the one thing I would like fixed before merge: the assertion is vacuous below a 16 KB chunk size.

It depends on the carrier chunk actually containing post-redefinition statements, and nothing asserts that it does. Measured across chunk sizes on this exact corpus:

chunk_size=   1024  chunks=3930  carrier=2000  post-redefinition triples IN carrier = 0
chunk_size=   2048  chunks=3857  carrier=2000  post-redefinition triples IN carrier = 0
chunk_size=   4096  chunks=3711  carrier=2000  post-redefinition triples IN carrier = 0
chunk_size=   8192  chunks=3418  carrier=1795  post-redefinition triples IN carrier = 0
chunk_size=  16384  chunks=2833  carrier=1795  post-redefinition triples IN carrier = 379   <- the value used here
chunk_size=  65536  chunks=   2  carrier=   0  post-redefinition triples IN carrier = 379
chunk_size=1048576  chunks=   1  carrier=   0  post-redefinition triples IN carrier = 2000

The definitive check — parser mutated to if false && rebinds (fix removed entirely), line 69 changed from 16 * 1024 to 4096:

post-redefinition subjects still on the OLD namespace: in carrier chunk = 0, in later chunks = 2000
post-redefinition objects still resolving to http://a/tag inside the carrier chunk = 0
test result: ok. 2 passed; 0 failed

The test passes against a parser with no fix in it. wrong_in_carrier two assertions down has the same problem.

This is the failure the module doc describes remediating — "it passed against a parser with the fix entirely removed" — closed along the object axis and left open along the chunk-boundary axis. It also narrows one claim in the PR body: "ordinary chunking changes cannot make it flap" is true of the wrong_after_carrier > 0 diagnostic, but these two do not flap, they go silently vacuous, which is the worse failure mode.

Suggested fix, one counter: tally post-redefinition triples in the carrier chunk regardless of which namespace they resolved to, and assert!(… > 0) before asserting that the resolutions are correct. Non-vacuity then holds structurally instead of being a property of the 16 * 1024 constant.

"within the carrier chunk the fix must hold"
);
assert!(
wrong_after_carrier > 0,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional. The technique is right — an #[ignore] would rot, and this fails loudly the moment §1.4 lands, which is the signal you want.

But the message is written for the state that holds today, so it prints backwards at the only moment it will ever be read. Whoever closes §1.4 gets a failing assertion reading "later chunks are still mis-resolved" precisely because they no longer are. Phrasing it for the failure direction — "if this fails, §1.4 has landed: flip to == 0 and delete this note" — puts the instruction where the CI output actually shows it. The module doc has exactly that; the assertion message doesn't.

let res = compute_chunk_boundaries(&mid_line, ds2, 1024);
println!("mid-line directive (data_start={ds2}) => {res:?}");
assert!(
res.is_ok(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional, same shape as the wrong_after_carrier note above: when someone teaches PrefixCheck to match a mid-line directive, this fails with a message asserting that it doesn't. Worth phrasing for the failure direction.

/// directive parser; it is what makes this comparison the right one. Both
/// cases are pinned in `tests/prefix_redefinition_adversarial.rs` (A1 and
/// A2) — they need a moving `@base`, which the other file never varies.
fn bind_prefix(&mut self, prefix: String, namespace: String) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional. parse_with_prefixes_base seeds the map with a direct parser.prefixes.insert(...) rather than coming through here, so the invariant this function establishes is a convention rather than a structure.

Safe today — that loop runs at construction against an empty cache, so there is nothing to invalidate. But it is the entry point chunked import uses, and it is the one place a future change ("re-seed after the prelude", "top up bindings between chunks") reintroduces precisely this bug with no test able to catch it, because the seeding happens before any name is cached. Routing that loop through bind_prefix costs nothing on an empty cache and makes the invariant self-enforcing.

/// expanded IRI for the current prefix mappings, so it serves as the cache key.
/// The span text (e.g., `"ex:name"` or `"ex:"`) identifies the expanded
/// IRI **for the prefix bindings in force**, so it serves as the cache key
/// only as long as those bindings hold. [`Self::bind_prefix`] is what

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional nit. This is the right correction, but its twin on the prefixed_term_cache field declaration (~line 38) still reads "which uniquely identifies the expanded IRI for a given prefix mapping", with no mention of invalidation and no pointer to bind_prefix.

Both sentences said the same thing before this PR and only one was fixed — and the field doc is the one a reader scanning the struct hits first, which is roughly how this got written in the first place.

@aaj3f

aaj3f commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

All four landed in 2a97f0c, the ask verified by your own scenario.

The ask — structural non-vacuity. The carrier loop now counts post-redefinition triples in the carrier regardless of how they resolved, and asserts > 0 before either correctness assertion can claim anything. Verified with your exact reproduction: parser mutated to if false && rebinds, chunk size dropped to 4096 — the test now FAILS on the witness ("VACUOUS: the carrier chunk holds no post-redefinition triples…") where it previously passed clean. Non-vacuity is now a property of the test rather than of the 16 * 1024 constant, which was your framing and is the right one. Your point about the PR body also holds: these two assertions didn't flap, they went silently vacuous, and the witness converts that failure mode into a loud one.

The reverse-assertions both print for the failure direction now — the §1.4 tripwire says "if this fails, the chunker fix has landed: flip to == 0 and delete the tripwire note," and the mid-line-directive one says "if this fails, PrefixCheck has learned mid-line directives — flip to is_err()." You're right that the only moment those messages are ever read is the moment the old phrasing was backwards.

The seeding loop routes through bind_prefix with a comment carrying your argument: a no-op on the empty cache today, but this is the entry point chunked import uses, and any future re-seed-after-caching would reintroduce exactly this bug with no test positioned to see it. Structural beats conventional.

The field doc now states the invalidation contract and points at bind_prefix — and your diagnosis of how the stale sentence survived (the field doc is what a struct-scanning reader hits first, which is roughly how the bug got written) is the part worth keeping.

Suite green at the new head (129/129), fmt/clippy clean. The admin.rs NUL rider stands as shipped — your live ugrep reproduction (a confident exit-1 "not found" for a pattern occurring 222 times) is a better demonstration of the severity than anything in the PR body.

aaj3f added 5 commits August 5, 2026 11:57
Turtle lets a prefix be rebound part-way through a document. The parser
ignored the rebinding for any prefixed name it had already seen, so

    @Prefix e: <http://a/> .   e:x <http://p/> "1" .
    @Prefix e: <http://b/> .   e:x <http://p/> "2" .

put BOTH statements on <http://a/x>. No error, no warning — the document
says one thing and the graph holds another.

Cause: `prefixed_term_cache` is keyed by span text (`e:x`), which identifies
an IRI only relative to the bindings in force when the entry was made, and
nothing invalidated it when a binding changed. `iri_term_cache` was never
affected — it keys on the RESOLVED IRI — and neither was `@base`, since a
namespace is resolved once, when its directive is read. A test pins both, so
the scope of this fix is demonstrated rather than asserted.

Fix: on a prefix directive, clear the expansion cache IF the prefix rebinds to
a different namespace. Only if. Redeclaring the same binding is the common
case, not a curiosity — chunked import prepends the file's prefix block to
every chunk over a pre-seeded map, so the parser sees each prefix declared
twice by construction — and every cached expansion stays correct through it.

The per-term path is untouched: the diff adds no instruction to
`resolve_prefixed_term` or `sink_term_iri`. Added work is one hash lookup per
prefix DIRECTIVE, of which a document has a handful, against a cache consulted
once per prefixed NAME, of which it has millions. Clearing is coarse — a
rebind strands only that prefix's entries, but finding them means scanning
every key — and rare enough that O(cache) once beats a per-lookup epoch check
on the hot path.

Ten tests, eight of which fail without the fix; the two that pass either way
are `@base` and same-binding redeclaration, which is what shows the scope is
right. Found while wiring term validation for H-8; nothing about it is
specific to validation and it reproduces on plain `parse`.
Review fold. The fix was right; what it lacked was anything that could tell if
half of it were deleted.

THE GAP: `bind_prefix` clears the expansion cache only when a prefix actually
rebinds, and that "only when" was invisible in parser output. Clearing on a
same-binding redeclaration yields identical triples — just colder — because
`iri_term_cache` absorbs the repeated work before it can reach the sink. So a
mutation dropping the condition passed every gate in the PR. Confirmed by
running it: with the clear made unconditional, all eleven triple-level tests
still pass.

The guard is the review's `parse_reporting_cache` — test-only, returns the
prefixed-name cache hit/miss counters — plus two tests reading them: a
same-binding redeclaration must leave the cache warm (1 hit, 1 miss), a real
rebinding must drop it (0 hits, 2 misses). The same mutation now fails the
first one. That is the whole point: the counters are the only place this
behaviour is observable.

Also documented, from the review: the comparison in `bind_prefix` is on
MEANING, not spelling. `parse_prefix_directive` resolves the namespace before
storing it, so `prefixes` holds resolved IRIs — and both directions of that
matter. Same spelling under two different bases names two namespaces and MUST
clear; two spellings under one base name one namespace and must NOT. Comparing
raw text would get each backwards. It was load-bearing and undocumented.

Two review probe files adopted as permanent regression tests, credited:

- `prefix_redefinition_adversarial.rs` (9 tests) attacks what the fix's own
  tests could not reach, because they never vary the base: the missed-clear and
  spurious-clear cases above, A→B→A epochs with overlapping and disjoint names,
  the coarse whole-cache clear with twenty live prefixes, terms nested in `[ ]`
  and `( )`, escaped local names, a pre-seeded relative binding, and mixed
  directive spellings.
- `prefix_redefinition_blast_radius.rs` (2 tests) executes the PR's
  blast-radius claim instead of asserting it, and now quantifies it: of the
  post-redefinition statements, 0 are mis-resolved inside the chunk carrying
  the redefinition — the fix holds there — and 1438 are mis-resolved in later
  chunks, which is the §1.4 chunker gap this PR explicitly does not close. It
  also confirms the guarded pre-scan path WOULD reject the file, which is what
  makes "import uses the unguarded reader" the operative fact.

That 1438 is an assertion of a live defect, kept live on purpose rather than
`#[ignore]`d: an ignored test runs nowhere and rots, while this one fails the
moment §1.4 lands and tells whoever closed it to come flip the number to 0.

Wording fold: "a rebind invalidates only that prefix's entries, but finding
them means scanning every key, so we drop them all", used consistently.
…he fix

The blast-radius test's `wrong_in_carrier == 0` proved nothing. Verified
before fixing: with `bind_prefix` deleted outright — the parser reverted to the
merge base, no fix at all — BOTH tests in the file still passed.

The corpus was the problem. Subjects were `e:s{i}`, a distinct span every time,
and predicates were full IRIs, so no prefixed name was ever looked up twice.
The expansion cache was never consulted for a span it already held, which is
the only shape in which a stale entry can be served. The test walked the whole
blast radius and never touched the defect it was named for.

Every line now carries `e:tag` as its object. It is cached under the first
binding and requested again after the rebinding, so a stale cache serves the
old namespace for a span whose meaning has changed. The new assertion counts
post-redefinition triples inside the CARRIER chunk — the one that actually
contains the redefinition — whose object still resolves to `http://a/tag`:

  fix removed (parser at merge base):  379   -> assertion FAILS
  fix present:                           0   -> assertion passes

`wrong_in_carrier` stays 0 in both cases, which is the demonstration that it
was never the discriminating assertion.

Kept unchanged: the subject-index chunk attribution, and the §1.4 tripwire on
later chunks. The tripwire's count moved 1438 -> 1621 with the corpus, which is
why it remains a printed diagnostic and an inequality rather than an equality —
ordinary chunking changes must not make it flap.

Found by an independent adversarial review of #1565. Two doc corrections ride
along: the meaning-vs-spelling cases are pinned in the ADVERSARIAL file (they
need a moving `@base`, which the other file never varies), and the clearing
comment now states the real trade — `retain` scans every key too, so the cost
is the same order; what it would buy is keeping other prefixes warm, and what
it costs is a predicate that has to compare up to the colon, since the obvious
`starts_with(prefix)` evicts `ex:name` when `e` rebinds. Simplicity over
post-rebind hit rate, not cost over cost.
The review measured that below a 16 KB chunk size the carrier chunk holds
zero post-redefinition triples, so both carrier == 0 assertions pass
against a parser with the fix entirely removed — the same vacuity the
earlier review caught on the object axis, reproduced along the
chunk-boundary axis. A structural witness now counts post-redefinition
triples in the carrier regardless of resolution and fails the test before
the correctness assertions can claim anything: non-vacuity is a property
of the test, not of the 16 * 1024 constant. Verified by the review's own
scenario — fix removed, chunk size 4096 — which now fails on the witness.

Riders from the same review: the two deliberate reverse-assertions print
their message for the failure direction (the moment they are actually
read); parse_with_prefixes_base seeds through bind_prefix so the
invalidation invariant is structural rather than conventional at the one
entry point a future re-seed would silently bypass; and the
prefixed_term_cache field doc carries the invalidation contract its
method doc already had.
…came

Rebasing onto main brought in #1552's GraphSink protocol, where finish()
is a trait lifecycle method returning a result rather than the collector
sink's accessor — the accessor is now into_graph(). Same rename-plus-old-
caller seam class as the #1529 x #1552 materialize break: this branch's
tests compiled standalone against their old base while the PR's merge
result did not, which is why local suites were green while CI was red.
All seven call sites move; every sink is an owned local at end of life,
so the consuming accessor fits without restructuring.
@aaj3f
aaj3f force-pushed the fix/turtle-prefix-redefinition branch from 2a97f0c to a207106 Compare August 5, 2026 15:59
@aaj3f

aaj3f commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

CI red was the #1529 × #1552 seam class recurring here: this branch predates #1552's merge, whose GraphSink protocol turns finish() into a trait lifecycle method — so the tests' sink.finish() collector calls compiled standalone against the old base while the PR's merge result did not (local suites green, CI red, same mechanism as the materialize break). Fixed by rebasing onto main (zero conflicts; the admin.rs NUL rider auto-dropped as already-upstream) and moving all seven call sites to into_graph(). Suite 163/163 at the new head a207106, fmt/clippy clean. The vacuity-witness commit from the previous push rides atop unchanged.

@aaj3f
aaj3f merged commit b6a680e into main Aug 5, 2026
15 checks passed
@aaj3f
aaj3f deleted the fix/turtle-prefix-redefinition branch August 5, 2026 16:50
aaj3f added a commit that referenced this pull request Aug 6, 2026
…close

`prefix_redefinition_blast_radius.rs` arrived with #1565 from main, where two
of its assertions pinned DEFECTS rather than properties, deliberately, so they
would fail the moment the chunker workstream landed and send whoever closed
the gap here. Both fired on the integration branch. This is that visit.

What actually changed is not "the chunker now handles such a file". It
REFUSES it: a mid-file directive makes a document unchunkable — only the first
chunk would carry the redefinition — so the reader thread raises
`PrefixAfterData` and stops.

The important part is how that refusal reaches a consumer, because the old
test is what made it look alarming. `recv_chunk` reports the closed channel as
a benign `Ok(None)`, so a consumer that only drains sees a SHORT READ AND NO
ERROR: 1797 of 4000 statements on this corpus. The error lives on the reader
thread and only `join()` surfaces it. Every live import call site joins, and
`import.rs` carries a comment saying exactly why. The old test drained without
joining, which is why it read as truncation.

So the replacement asserts the distinguishing fact rather than the symptom:
drain, then join, and require `Err(PrefixAfterData)`. That is the assertion
that tells "refused" apart from "silently truncated", and it would fail if the
join contract were ever dropped.

`the_guard_misses_a_mid_line_directive` becomes
`the_guard_catches_a_mid_line_directive` — detection now fires at any token
start, not just at line start.

The parser property the file also carried — a prefixed name reused across a
rebinding must follow the rebinding rather than the span cache — was entangled
with the chunk-carrier machinery, which no longer exists because there is no
carrier chunk. It is now its own test on a document that is never chunked,
since it is a property of the parser either way.

One latent hazard noted, not fixed: `ImportSource::recv_next` returns
`Ok(None)` on a closed channel without joining. It has no callers today; a
future one would inherit the silent-short-read shape.
aaj3f added a commit that referenced this pull request Aug 6, 2026
The flip the plan predicted: `a_mid_file_directive_falls_back_to_serial_rather
_than_refusing` asserted that exactly one term after a mid-file rebinding
denotes the new namespace. It is two, and the second one is the fix.

The trailing statement is `ex:z ex:p "z" .`, so its subject AND its predicate
both sit after the rebinding. Before #1565 only the subject moved: `ex:z` is a
span the document had never used, while `ex:p` had been expanded 80,000 times
and came back from the span cache under the old binding. Asserting one
occurrence was asserting the bug. The count is now two and the last line is
pinned whole, so it cannot drift back to one for some unrelated reason.

Fold-ins recorded at the wave close, applied here because this is where the
branches converged:

- The dead-reader comment claimed receiver ownership stops workers and the
  shutdown flag only makes them prompt. The reviewer's four-way mutation table
  says otherwise: either mechanism ALONE keeps the run live, and only removing
  both hangs. The old phrasing reads as though the flag were an optimization,
  which invites deleting a second liveness guarantee that no single-mutation
  test can catch. Restated as: either alone suffices, keep both, and the
  mutation that proves it removes both.

- `list_items_land_in_the_default_graph_because_the_protocol_has_no_quad_form`
  is now `list_items_without_a_graph_land_in_the_default_graph`. The protocol
  HAS the quad form — `emit_quad_list_item` landed with the M2 work — so the
  old name asserted a reason that had stopped being true.

- `chars::unicode_escape_value` documents the one hazard its signature cannot
  express: it takes `&str`, so it can never see a partial UTF-8 sequence, but a
  caller slicing RAW BYTES can panic before reaching it. Both current readers
  slice a `&str` at their own scanner's positions, so the class is structurally
  out of reach for them — a third reader over `&[u8]` would have to bound its
  own slice. The guarantee lives at the call site, not here.

- The CLI tests' `EXIT_DOCUMENT_INVALID` was a bare `1`. It now binds to
  `fluree_db_cli::error::EXIT_ERROR`, so the assertions track the contract
  instead of a literal that would keep passing if the binary's code changed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants