Skip to content

Round-trip generic xsd:duration through the binary index - #1544

Merged
zonotope merged 14 commits into
mainfrom
fix/null-xsd-duration
Jul 28, 2026
Merged

zonotope merged 14 commits into
mainfrom
fix/null-xsd-duration

Conversation

@zonotope

Copy link
Copy Markdown
Contributor

Issue #1326 reported that generic xsd:duration values (mixed year-month and day-time components, e.g. P1Y2M3DT4H5M6S) do not survive a reindex: after the binary index is built, SELECTing the value returns null and a bound generic-duration object matches nothing. The subtypes xsd:yearMonthDuration and xsd:dayTimeDuration were unaffected (they have inline encodings).

The data was never lost. The index build stores a generic duration as the string-dictionary id of its canonical lexical form (o_kind=LEX_ID, resolver's DurationStr arm), but the read side's DecodeKind::Duration arm was an unimplemented stub returning FlakeValue::Null. A knock-on effect: the overlay-translation encoder deliberately refused to translate novelty durations into binary rows — because the decode would null them — forcing the raw-flake fallback lane.

Changes

  • fluree-db-binary-index/src/read/binary_index_store.rs:
    • decode_value_v3's DecodeKind::Duration arm now resolves the string-dict id and parses it (temporal::Duration::parse), returning FlakeValue::Duration with a FlakeValue::String fallback on parse failure — the same shape as the neighboring Date/Time/DateTime arms. This single arm also serves decode_value_no_graph (a thin wrapper).
    • BinaryGraphView::decode_value gains a Duration novelty arm mirroring StringDict: an overlay row can carry a novelty string id (when the canonical lexical was interned by an unrelated novelty string literal), which the base-only resolve cannot see and would abort the scan. Duration is also added to the dict-touch charge set, since its decode performs the same forward-pack lookup as StringDict.
    • BinaryGraphView::decode_value_from_kind (the Binding::EncodedLit path) had the same gap one layer down: its LEX_ID novelty branch returned FlakeValue::String unconditionally; it now resolves the OType from (ObjKind, dt_id, lang_id) and parses durations to the correct variant.
  • fluree-db-query/src/binary_scan.rs:
    • value_to_otype_okey gains a FlakeValue::Duration arm keying overlay rows by the canonical form's dict id, mirroring the index resolver so overlay rows key identically to base rows of the same value (equality is value-based: Duration's PartialEq compares months+micros, and canonicalization is unique per value). A resolve miss — the normal novelty-only case, since DictNovelty never interns duration lexicals — is mapped to ErrorKind::Unsupported, the one error kind every translation lane routes to its raw-flake path; the SPOT-cursor lane drops other kinds, so a plain NotFound would have silently lost novelty durations there.
    • value_to_otype_okey_simple (the V6 fast-path encoder) gains all three duration arms: inline encodings for the subtypes, and a generic-duration arm keyed via store.find_string_id(canonical) with a base-dict miss surfacing as NotFound ("provably absent", matching the String arm's contract) so bound-duration COUNT queries take the conclusive overlay-only route instead of declining to a full predicate scan.

Tests

New fluree-db-api/tests/it_duration_index_roundtrip.rs (wired into grp_index), seven cases:

  • Insert → reindex → read parity with the novelty serialization, plus yearMonthDuration/dayTimeDuration controls.
  • A bound generic-duration object matching exactly one subject after reindex.
  • A SPARQL COUNT with a bound generic-duration object (the V6 count fast-path shape).
  • A non-canonical lexical (P0Y14MT0S): the novelty read preserves the original form, the indexed read returns the canonical P1Y2M — pinning the value-based-storage boundary shared by all temporal types.
  • A negative mixed duration round-tripping identically on both paths.
  • A novelty duration over a binary base (overlay path).
  • A retraction of an indexed duration cancelling the base row through the base/overlay merge.

The core round-trip and bound-object tests were verified to fail before the fix with exactly the issue's symptoms (@value: null, empty match). One subtlety the tests encode: only mixed durations exercise the generic path — pure year-month or day-time lexicals coerce to the inline-encoded subtypes at parse time.

Fixes #1326

@zonotope
zonotope requested review from aaj3f and bplatz July 24, 2026 11:20

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

Fix looks right. The decode arm genuinely mirrors the neighbouring Date/Time/DateTime arms, String fallback included. clippy clean on both touched crates, fmt clean, grp_index passes (79) including all 7 new tests.

I probed two edges the tests don't cover, both fine — recording so nobody re-litigates them:

  • Stored P0Y14MT0S, then queried as the original lexical, as canonical P1Y2M^^xsd:duration, and as P1Y2M^^xsd:yearMonthDuration: matches / matches / no-match, identical on the novelty and indexed paths. The subtype non-match is correct RDF term semantics.
  • A pure year-month lexical explicitly typed xsd:duration ("P1Y2M"^^xsd:duration) round-trips and matches correctly through the generic path.

The second one does suggest the framing in the PR body and the test-file header — "pure year-month or day-time lexicals coerce to the inline-encoded subtypes at parse time" — is narrower than the actual behavior: an explicitly xsd:duration-typed pure year-month literal stays generic. Behavior is correct; the stated premise just understates which shapes reach the generic path.

Three notes inline, none blocking.

// persisted dict is the normal novelty-only case. That miss must
// surface as Unsupported: the SPOT-cursor translation lane routes only
// Unsupported to its raw-flake path and DROPS other error kinds, while
// the binary-range lane raw-routes any error — Unsupported is the one

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 reasoning here checks out — translate_overlay_flakes_with_untranslated (:2536-2541) really does route only Unsupported to the raw-flake lane and drop everything else with a bare warn!.

But that means this arm is working around the drop rather than fixing it, and the hazard is live for the other arms too: resolve_subject_v3 returns NotFound when a subject is in neither the persisted nor the novelty dict, and that overlay flake is then dropped outright — silent wrong results, no raw fallback.

Should the else branch push to untranslated as well? That would close the class and make the error-kind choreography here unnecessary. Happy for it to be a follow-up, but worth deciding explicitly rather than leaving the next arm to rediscover it.

Comment thread fluree-db-query/src/binary_scan.rs Outdated
// signal every lane preserves.
FlakeValue::Duration(d) => {
let str_id = resolve_string_v3(&d.to_canonical_string(), store, dict_novelty)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Unsupported, e))?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This catches everything resolve_string_v3 can return, not just the intended novelty miss — a genuine dict or mmap I/O error from store.find_string_id becomes Unsupported too.

Results stay correct (the raw lane preserves the value), but a corrupt dictionary turns into an invisible slow path instead of an error. Worth rewriting only the NotFound case and letting real I/O errors through.

// A LEX_ID value decodes per its datatype: generic
// durations intern their canonical lexical form but
// decode as FlakeValue::Duration, not String.
let registry = OTypeRegistry::builtin_only();

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.

builtin_only() is new(&[]), which pushes 15 entries into a fresh Vec — so this allocates on every decoded row. There's same-file precedent at :2112, so it's pre-existing practice rather than something this PR invents, but this is a hotter path than that one.

A LazyLock static would cover it, since builtin-only is stateless. Or skip the registry entirely: this branch only needs to know whether dt_id is the duration datatype.

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The diagnosis here is exactly right and the core fix is correct, minimal, and well-tested: the write path was never broken, the data was never lost, and restoring the DecodeKind::Duration decode is a read-only change that needs no index-format bump — I traced RawObject::DurationStr through resolver.rs:1036/:1810 and confirmed the persisted encoding is byte-identical to main, so downstream fluree/solo's EXPECTED_INDEX_FORMAT_VERSION needs no invalidation. The main decode arm has real teeth (corrupting it turns 5 of the 7 new tests red with the original @value: null symptom), and the Unsupported error-kind reasoning at binary_scan.rs:3038 is genuinely good engineering that I verified rather than trusted.

Two things maybe deserve some consideration before merge.

First, ORDER BY DESC(?d) LIMIT k over generic durations returns dict-insertion order, not value order, because is_post_desc_orderable admits XSD_DURATION through the contiguous is_temporal() range even though its o_key is a string-dict id — I proved the fast path and the fallback disagree, and the one-line exclusion I verified fixes it; the defect predates the PR but on main it is masked by the null values this PR removes, so shipping as-is converts a loud failure into a silent wrong answer.

Second, the third claimed fix at binary_index_store.rs:2343 cannot execute — builtin_only() has no custom-datatype table and a duration's dt_id is always custom, which I proved by exhausting all 16,384 dt_id values — so it is dead code that allocates a Vec on every novelty string decode across ~17 hot call sites. Both are small fixes and the PR is close.

Adherence to repo commitments:

  • Performance (speed first, memory second): ✖ CRITICAL — a per-row Vec allocation added to BinaryGraphView::decode_value_from_kind (:2343) for a branch that provably never fires, on the per-binding materialization path. The rest is neutral-to-positive (the :2309 fuel charge is correctly accounted; the V6 encoder arms move bound-duration COUNTs off a full predicate scan). No bench covers binary-index decode.
  • Testing: ⚠️ The 7 new tests are correctly wired into grp_index.rs:4-5 (the autotests = false trap avoided) and the core arm's teeth are verified — but three of the PR's new branches (:2343, binary_scan.rs:3423, :3427) can be corrupted with all 2,097 tests still green, and nothing covers the ORDER BY DESC divergence.

Notes without a diff anchor

Observation — no range-pushdown hazard (fluree-db-query/src/binary_scan.rs:2000-2020, not in this diff). I specifically went looking for one and there isn't one. supports_range enumerates only XSD_DATE/DATE_TIME/TIME/G_YEAR/G_YEAR_MONTH/G_MONTH/G_DAY/G_MONTH_DAY, so no duration type — generic or subtype — can drive range_min_okey/range_max_okey. The integer point-seek at :2066 is gated on matches!(lo, FlakeValue::Long(_)). FILTER(?d > "P30D"^^xsd:duration) therefore never reaches a key comparison and falls back to value-level class_cmp (fluree-db-core/src/query_bounds.rs:193-201), which uses the partial-order-aware temporal_cmp. The exclusion is real and it triggers. That is exactly the right design, and it makes the is_post_desc_orderable gap above look like a genuine oversight rather than a policy choice.

Observation — negative per-component lexicals (fluree-db-core/src/temporal.rs:1806, not in this diff). Duration::parse accepts negative per-component lexicals like P-1MT1H that XSD forbids, which can produce a Duration with months and micros of opposite sign; to_canonical_string then renders P-1MT1H and P1MT-1H identically as -P1MT1H, so two PartialEq-distinct values collide on one dict id. Entirely pre-existing (it lives in the write path this PR doesn't touch) and reachable only through already-invalid input, so I would not gate on it — noting it so it isn't "discovered" later as a duration-indexing bug.

Observation — STR() over a duration. FILTER(STR(?d) = "P3Y1M1DT1H") returns empty on both the novelty and indexed paths. Identical across paths, so not a PR regression, but STR() over a duration appears not to yield the lexical form. Possibly worth its own issue.

// Unsupported to its raw-flake path and DROPS other error kinds, while
// the binary-range lane raw-routes any error — Unsupported is the one
// signal every lane preserves.
FlakeValue::Duration(d) => {

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.

Real location: fluree-db-query/src/fast_path_common.rs:292.

Blocking, CRITICAL: this PR converts a loudly-broken query into a silently-wrong one.

is_post_desc_orderable admits every o_type in is_temporal(), and is_temporal() is the contiguous range XSD_DATE (0x0013) ..= XSD_DURATION (0x001D) (fluree-db-core/src/o_type.rs:284). But XSD_DURATION is the one member of that range whose o_key is not an order-preserving encoding — it is a string-dictionary id, assigned in interning order, exactly as your own resolver comment says (fluree-db-indexer/.../resolver.rs:1037: "General xsd:duration has no total order — store as canonical string"). The function's doc comment even states it excludes dict-backed types "because ids are assigned by insertion order, not lexicographic value order" — generic duration is dict-backed and slips in through the temporal range anyway.

So a predicate whose objects are all generic durations passes single_orderable_o_type (fast_post_order_limit.rs:320, and combined_orderable_o_type at :344), takes the reverse-POST ORDER BY DESC(?o) LIMIT k fast path, and returns rows in dict-insertion order.

Verified end-to-end, not inferred. Inserting ex:a P3Y1M1DT1H, ex:b P1Y1M1DT1H, ex:c P2Y1M1DT1H (insertion order deliberately ≠ value order) and running SELECT ?s ?d WHERE { ?s ex:took ?d } ORDER BY DESC(?d) LIMIT 3:

novelty (fallback path): ex:a P3Y…, ex:c P2Y…, ex:b P1Y…   ← correct
indexed (binary path):   ex:c P2Y…, ex:b P1Y…, ex:a P3Y…   ← dict-id order
dayTimeDuration control: ex:a PT3H, ex:c PT2H, ex:b PT1H   ← correct (inline encode_i64)

The two paths disagree, which per §3 is the worst outcome. The ordering defect itself is pre-existing — I confirmed it reproduces with fluree-db-binary-index and fluree-db-query reverted to the merge-base — but on main every value in that result set is null, so a user hits an obviously-broken result and files a bug. After this PR the values render correctly and only the order is wrong, which nobody notices. That is a real regression in failure visibility, and this PR is the right place to fix it because this PR is what makes the path reachable with real data.

One-line fix, which I applied and re-ran — indexed output then matched the fallback exactly, and the dayTimeDuration control was unaffected:

// XSD_DURATION sits inside is_temporal()'s range but is dict-backed
// (o_key = string-dict id of the canonical lexical), so it is NOT
// order-preserving. Excluded here.
o_type == OType::XSD_BOOLEAN.as_u16()
    || ot.is_numeric()
    || (ot.is_temporal() && o_type != OType::XSD_DURATION.as_u16())

Please also add a regression test asserting the indexed and novelty results agree for ORDER BY DESC over a generic-duration predicate — without one, the next person to widen the temporal range reintroduces this. Note that this is strictly about the storage order being wrong; XSD's genuine partial order (P1M vs P30D incomparable) is a separate, correctly-handled concern — Duration's PartialOrd returns None for indeterminate pairs and its Ord is honestly documented as "storage order only" (fluree-db-core/src/temporal.rs:1911-1938).

(Commenting here because fluree-db-query/src/fast_path_common.rs is not in this diff.)

// A LEX_ID value decodes per its datatype: generic
// durations intern their canonical lexical form but
// decode as FlakeValue::Duration, not String.
let registry = OTypeRegistry::builtin_only();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocking: this branch can never execute, and it costs an allocation per row to not execute.

The PR body says this closes the Binding::EncodedLit gap "one layer down". It does not. OTypeRegistry::builtin_only() is new(&[]), so its dt_otypes table holds only the 15 reserved DatatypeDictIds (0–14, o_type_registry.rs:31-54) — and xsd:duration is not reserved. A duration's dt_id is a dynamically-assigned custom id ≥ RESERVED_COUNT, so resolve_by_dt falls off the end of the table and returns OType::customer_datatype(dt_id) (:120-127), whose tag is TAG_CUSTOMER and whose decode_kind() is therefore DecodeKind::StringDict, never DecodeKind::Duration (o_type.rs:316). The if is dead.

Proven by exhaustion rather than by reading: over all 16,384 possible dt_id values × several lang_ids, builtin_only().resolve(ObjKind::LEX_ID, dt, lang).decode_kind() returns Duration zero times. A registry built with the xsd:duration IRI resolves dt_id=15 → OType::XSD_DURATION / DecodeKind::Duration correctly, which confirms the mechanism is the missing custom-datatype table and nothing else.

This is also why it is untested: corrupting the branch body to Ok(FlakeValue::Null) leaves all 2,097 tests I ran green.

On top of being dead, it allocates. builtin_only() runs Vec::with_capacity(15) + 15 pushes on every novelty LEX_ID row — i.e. every plain novelty string, not just durations — and decode_value_from_kind has ~17 call sites across materializer / join / sort / group_aggregate / eval / bm25 / fulltext. This is the per-binding materialization path. bplatz called out the allocation; I am marking it blocking because the branch buys nothing in exchange.

Two options. If the EncodedLit lane genuinely needs to type durations, it needs a registry that knows the custom datatypes — the same one the index build used — not builtin_only(); note the persisted twin at :2112 has the identical mis-resolution, so both would need it and it is a larger change than this PR. If it does not (and I could not produce a query that visibly regresses — see below), delete the branch and drop the allocation with it. Either way, please correct the PR body, which currently claims a fix that does not run.

In fairness to scope: I tried to demonstrate user-visible fallout and could not. ORDER BY ASC, GROUP BY ?d, and MIN/MAX over generic durations all return correctly-typed xsd:duration values on both the novelty and indexed paths, so those shapes are not routing through this branch. I am not claiming a live wrong-result bug here — I am claiming dead code, a wasted hot-path allocation, and an inaccurate PR description.

Comment thread fluree-db-query/src/binary_scan.rs Outdated
// signal every lane preserves.
FlakeValue::Duration(d) => {
let str_id = resolve_string_v3(&d.to_canonical_string(), store, dict_novelty)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Unsupported, e))?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Optional; seconding bplatz with a confirmation.

map_err(|e| Error::new(ErrorKind::Unsupported, e)) blankets everything resolve_string_v3 can return, and that function propagates store.find_string_id(value)? verbatim (:2869), so a genuine mmap/dict I/O error is relabelled as "unsupported value type" and quietly routed to the raw-flake lane. Results stay correct, which is why this is not blocking, but a corrupt dictionary becomes an invisible slow path instead of an error. Rewrite only ErrorKind::NotFound and let real I/O errors through.

Separately, since your comment at :3040 correctly notes the miss is the normal novelty case, that path builds a format!-ed error string (:2882-2886) on every novelty duration flake purely to throw it away — worth a cheap sentinel instead.

OType::XSD_G_MONTH_DAY,
ObjKey::encode_g_month_day(g.month(), g.day()).as_u64(),
)),
FlakeValue::YearMonthDuration(d) => 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. (Applies to both :3423 and :3427.)

The YearMonthDuration and DayTimeDuration arms in value_to_otype_okey_simple are new capability, not part of #1326 — the subtypes were never broken. Corrupting both (offsetting the encoded key by 7) leaves all 2,097 tests green, so nothing covers them.

They look correct to me (encode_year_month_dur/encode_day_time_dur are the same inline encodings the resolver writes at resolver.rs:1020,1028), and widening the V6 fast path to them is a genuine win — but a bound-yearMonthDuration COUNT test would cost one #[tokio::test] and would pin the pairing. Alternatively, split them out; they are unrelated to the bug in the title.

OType::XSD_DAY_TIME_DURATION,
ObjKey::encode_day_time_dur(d.micros()).as_u64(),
)),
// Generic duration: keyed by the string-dict id of its canonical

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Praise.

The Unsupported error-kind comment is the best thing in the diff. I verified the claim rather than taking it: translate_overlay_flakes_with_untranslated (:2536-2541) really does route only ErrorKind::Unsupported to untranslated and drop every other kind with a bare tracing::warn!. Writing down why the error kind is load-bearing is what stops the next person from "tidying" it into NotFound and silently losing novelty durations.

bplatz's follow-up question — whether the else branch should push to untranslated too, which would close the class for resolve_subject_v3's NotFound as well — is the right one and deserves an explicit decision (a follow-up issue is a fine answer).

DecodeKind::IriRef
| DecodeKind::StringDict
| DecodeKind::JsonArena
| DecodeKind::Duration

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Praise.

Adding Duration to the dict-touch fuel charge set. The decode now performs a forward-pack lookup exactly like StringDict, so it must be charged like one. Easy to forget, invisible in tests, and would have shown up as a fuel-accounting drift much later.

@@ -0,0 +1,340 @@
//! Regression tests: generic `xsd:duration` values must round-trip through

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Praise.

The generic_duration_non_canonical_input_canonicalizes_on_reindex case, which pins P0Y14MT0S → P1Y2M, is the most valuable test in the file. It documents the value-based-storage boundary as intended behaviour instead of leaving it to be rediscovered as a bug.

The header comment noting that only mixed durations exercise the generic path (pure year-month/day-time lexicals coerce to the inline subtypes at parse time) is the kind of note that saves the next reader an hour.

@zonotope
zonotope merged commit 979baea into main Jul 28, 2026
13 checks passed
@zonotope
zonotope deleted the fix/null-xsd-duration branch July 28, 2026 19:16
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.

Generic xsd:duration does not round-trip on the binary index path (decode stub returns Null)

3 participants