Skip to content

fix(query): answer unbound for a calendar field the value does not carry - #1667

Merged
bplatz merged 3 commits into
mainfrom
fix/datetime-component-fabrication
Aug 20, 2026
Merged

bplatz merged 3 commits into
mainfrom
fix/datetime-component-fabrication

Conversation

@bplatz

@bplatz bplatz commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Follows up the side observation at the end of #1652 — deliberately left out of
#1666, which fixed that issue's three reported shapes. Those were fast-vs-generic
divergences with an unambiguous oracle: make the fast lane match the generic
pipeline and no correct query changes. This one is different in kind. Both lanes
already agree; the question is whether what they agree on is right. It changes
results for queries that return numbers today, so it wants its own review.

Stacked on #1666 (base fix/fastpath-count-divergences) — review that one first;
this branch's own commit is the second one.

The behavior

xsd:gYear has a year and nothing else, so DAY("2005"^^xsd:gYear) has no answer
in the data. Every temporal value was promoted to a whole instant and the field
read off the promoted result, so absent fields came back as the promotion's
filler — day 1, month 1, and from the Unix epoch year 1970 — indistinguishable in
the answer from a value that was really there:

expression was now
YEAR("2005"^^xsd:gYear) 2005 2005 (carried)
MONTH/DAY("2005"^^xsd:gYear) 1 unbound
DAY("2005-07"^^xsd:gYearMonth) 1 unbound
YEAR("--03"^^xsd:gMonth) 1970 unbound
YEAR("---17"^^xsd:gDay) 1970 unbound
YEAR("13:45:00"^^xsd:time) 1970 unbound
DAY("2005-07-17"^^xsd:date) 17 17 (carried)

Why it is worth changing

On a predicate that is entirely year-only — the shape in the report — the filler
is close to harmless: a nonsense query gets a nonsense number.

It is not harmless on a predicate mixing xsd:date with xsd:gYear, which is
ordinary in bibliographic data where some records are dated and some are
year-only. With three dated rows (days 17, 20, 30) beside three year-only rows:

query was now
AVG(DAY(?o)) 11.67 22.33
COUNT(DAY(?o)) 6 3
SUM(DAY(?o)) 70 67
FILTER(DAY(?o) < 15) 3 rows 0 rows

The filter is the sharpest one. Every dated row has a day ≥ 15, so the honest
answer is none — and the fabricated day 1 made it select precisely the three rows
with no day at all while excluding all three that had one. The result was not
merely wrong, it was anti-correlated with the question. A MONTH(?o) histogram
got a fake January spike sized to however many year-only records existed.

What changed

Component extraction consults the datatype before promoting, and yields unbound
where the lexical form carries nothing (SPARQL makes the accessor a type error on
such an operand, and this engine already demotes expression errors to unbound in
queries — DAY("hello") has always been unbound). Unbound then falls out of the
aggregates for free, since SUM/AVG/COUNT skip it.

The check runs before the epoch-millis fallback as well, so a declined temporal
value cannot be re-fabricated by it. A bare integer is still read as epoch
milliseconds, which LDBC-style datasets depend on.

One judgment call, flagged for review: xsd:date keeps its time-of-day fields
at the midnight the XSD timeline maps it to. That one reads as a documented
convention rather than invented data — a date does begin at midnight, and
YEAR/MONTH/DAY of a date, the overwhelmingly common uses, are genuine either
way — so it stays, pinned by test so the narrowing cannot quietly widen. The
consistent-purist alternative is to make HOURS(date) unbound too; easy to flip
if reviewers prefer it.

Consolidating the three copies

Three lanes read these fields: the per-row evaluator, its no-chrono fast extractor,
and the fused SUM(DAY(?o)) scan that folds a homogeneous leaflet with no column
IO. Each carried its own copy of the defaults, and they had already drifted:

  • the fast extractor guarded a bare Long on xsd:gYear, while the generic path
    let the same value reach the epoch-millis fallback instead;
  • only the fused lane knew about xsd:date;
  • the fused lane's constant-fold was the same "which fields are absent" table
    written a third time and inverted.

All three now consult one presence table and one defaults table in
fluree-db-core::temporal, beside the temporal types themselves, and none keeps
defaults of its own. The one surviving 1970 outside that table is xsd:date's
storage encoding, which counts days from the epoch.

The fused lane also gains an explicit Absent state rather than a bare Option,
so a future non-SUM consumer — an AVG that must not count the row, a COUNT that
must not either — has to decide for itself instead of inheriting SUM's silent
zero. That implicit-default pattern is what produced the bug in the first place.
A field the datatype does not carry now folds a whole leaflet to nothing with no
IO, where it previously read a fabricated 1 per row.

Testing

New it_datetime_component_presence.rs, 28 cases, each run twice under the
fast-path kill switch — fast-vs-generic agreement is what proves the three lanes
still share one answer — and each pinned against a hand-computed value on both
lanes, so a generic regression fails as loudly as a fast-path one. Carried fields
are pinned alongside absent ones so the narrowing cannot overshoot, and the
xsd:date midnight convention has its own pin. Unit tests in
fluree-db-core::temporal check the presence table against an independently
spelled-out table and assert the two index representations classify alike.

Green locally: the full W3C suite (36 suites, 0 failures, including the SPARQL 1.1
accessor tests), the Cypher suite (231 tests — its .year/.month accessors share
this path), 1440 fluree-db-query unit tests, 789 fluree-db-core tests, the 764
query-binary tests, clippy --all-features --all-targets -D warnings, and
cargo fmt --check.

Review follow-up

SECONDS pins. eval_seconds returns xsd:decimal and so does not route through
eval_datetime_component — it repeats the presence check itself, and the suite had no SECONDS
case at all, so removing that gate entirely passed every pin. Five cases now cover it: carried on
xsd:time and xsd:dateTime, absent on xsd:gYear and xsd:gMonth, and the midnight convention
on xsd:date. Mutation-checked — dropping the gate fails exactly the two absent cases, on both
lanes. (A carried SECONDS renders as a JSON string, being a decimal.)

Fused-lane routing. The three fused SUM cases pinned their answer but not the lane, and the
fallback computes the same number, so a silent disable was invisible here. They now assert the
site proceeded.

This needed no production change. FastPathOperator::open already stamps fast-path outcome
under the operator's label, so the fused lanes stamp as SUM(DAY) / SUM(YEAR) despite
fast_predicate_scalar_agg.rs containing no direct stamp_fast_path call — grepping a file for
stamp sites understates coverage for anything built on FastPathOperator. Mutation-checked:
forcing the operator to decline fails exactly the three routing assertions and no value
assertion
, which is precisely the blind spot they close.

The eval_seconds / eval_datetime_component consistency nit is deliberately not folded in — see
the review thread.

`xsd:gYear` has a year and nothing else, so `DAY("2005"^^xsd:gYear)` has no
answer in the data. Every temporal value was promoted to a whole instant and
the field read off the promoted result, so absent fields came back as the
promotion's filler — day 1, month 1, and from the Unix epoch year 1970 —
indistinguishable in the answer from a value that was really there.

On a predicate that is entirely year-only the filler is close to harmless: a
nonsense query gets a nonsense number. It is not harmless on a predicate
mixing `xsd:date` with `xsd:gYear`, which is ordinary in bibliographic data
where some records are dated and some are year-only. Three dated rows (days
17, 20, 30) beside three year-only rows gave `AVG(DAY(?o))` 11.67 against a
true 22.33, `COUNT(DAY(?o))` six where three rows have a day, and — sharpest
— `FILTER(DAY(?o) < 15)` selected precisely the three rows with no day at all
while excluding all three that had one.

Component extraction now consults the datatype before promoting, and yields
unbound where the lexical form carries nothing (SPARQL makes the accessor a
type error on such an operand, and this engine demotes expression errors to
unbound in queries). Unbound then falls out of the aggregates for free, since
SUM/AVG/COUNT skip it. The check runs before the epoch-millis fallback too,
so a declined temporal value cannot be re-fabricated by it; a bare integer is
still read as epoch milliseconds, which LDBC-style datasets depend on.

`xsd:date` keeps its time-of-day fields at the midnight the XSD timeline maps
it to. That one is a documented convention rather than invented data — a date
does begin at midnight, and YEAR/MONTH/DAY of a date, the overwhelmingly
common uses, are genuine either way — and it is pinned by test so the
narrowing cannot quietly widen.

Three lanes read these fields: the per-row evaluator, its no-chrono fast
extractor, and the fused `SUM(DAY(?o))` scan that folds a homogeneous leaflet
with no column IO. Each carried its own copy of the defaults, and they had
already drifted — the fast extractor guarded a bare `Long` on `xsd:gYear`
while the generic path let it reach the epoch-millis fallback, and only the
fused lane knew about `xsd:date`. All three now consult one presence table and
one defaults table in `fluree-db-core::temporal`, beside the temporal types
themselves, and none of them keeps defaults of its own: the fast extractor
supplies only the fields its datatype carries, and the promotion builds its
filler from the shared table. The one surviving 1970 outside that table is
`xsd:date`'s storage encoding, which counts days from the epoch. The fused lane gains an explicit `Absent` state rather than a bare
`Option`, so a future non-SUM consumer — an AVG that must not count the row, a
COUNT that must not either — has to decide for itself instead of inheriting
SUM's silent zero. An absent field now folds a whole leaflet to nothing with
no IO, where it used to read a fabricated 1 per row.

Verified green: the full W3C suite (36 suites, including the SPARQL 1.1
accessor tests), the Cypher suite whose `.year`/`.month` accessors share this
path, and the 764 query-binary tests. The new pins run every case twice,
under the fast-path kill switch, because fast-vs-generic agreement is what
proves the three lanes still share one answer.

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

I'm in favor of this change, @bplatz — the FILTER example (day-1 filler selecting precisely the rows with no day while excluding every row that had one) makes the case better than any spec citation could, and the shape of the fix is right.

I verified the semantics change lands everywhere it must and nowhere it mustn't: the only component readers in the crate are the three lanes touched here (comparison/ORDER BY promotion is structurally out of reach — parse_datetime_from_binding has no callers outside eval/datetime.rs), Cypher's .year/.month share the evaluator (231 tests green), the epoch-millis LDBC fallback still fires for bare integers but can no longer re-fabricate a declined temporal value, and I probed the plain-string accessor question at HEAD and base — unbound everywhere, so no hidden behavior change there. Mutation checks confirm the new suite bites on both the gate (21 failures) and the fused fold's arithmetic (exactly one, fast lane only).

Note that CI didn't run yet, as this is a stacked PR, but my local CI tests were all green.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ single shared table in core replaces three per-lane copies; ComponentFold makes the absent case explicit for future consumers; SPARQL/JSON-LD share the evaluator so parity holds by construction, and Cypher inherits it (verified, not just assumed).
  • Performance (speed first, memory second): ✔ one enum match per row added on the accessor path, no allocation; absent fields now fold whole leaflets with zero IO; promotion refactor shape-identical. No regression risk.
  • Testing: ✔ 23 dual-lane hand-pinned cases plus 6 core table tests, mutation-checked; W3C functions category green with the stale-register check. (Nits: no SECONDS pins, and the fused cases can't assert routing since the operator doesn't stamp.)
  • Conventions: ✔ thorough multi-line commit body that flags its own judgment call for review; fmt/clippy clean on the changed crates. (Body says 22 cases; the file has 23 — cosmetic.)

Verified locally at branch HEAD (9733d04): fluree-db-core --lib calendar_field 6 passed; fluree-db-query --lib 1402 passed; it_datetime_component_presence pass; it_query_cypher 231 passed; testsuite-sparql sparql11_functions pass; two mutation checks red in exactly the right places; fmt + clippy clean.

Approving so this can merge as soon as it's retargeted onto main with #1666's fixes in and real CI green — the SECONDS pins and the routing-stamp item are worth a look. If you agree, would prefer we fold in now rather than defer/punt to follow-up

// xsd:date -> midnight is a kept convention, pinned so it can't widen.
Case {
name: "HOURS(date) keeps the midnight convention",
sparql: "SELECT (HOURS(?o) AS ?h) (MINUTES(?o) AS ?m) WHERE { ?s ex:date ?o }",

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. There's no SECONDS case anywhere in the suite, and SECONDS is the one accessor with its own evaluator and its own copy of the gate (fluree-db-query/src/eval/datetime.rs:96-102) — so a broken or inverted condition there would pass every existing pin.

Two or three cases would close it: SECONDS(gYear) unbound, SECONDS(date) = 0 (the midnight-convention pin for the field the suite doesn't cover), and SECONDS(time) carried. Cheap insurance for the one lane the shared table doesn't force through eval_datetime_component.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done — five cases, in 5c1e88181.

Your three plus two more, since xsd:dateTime was also uncovered for this accessor and xsd:gMonth is the cheapest second absent case:

  • SECONDS(time) carried, SECONDS(dateTime) carried
  • SECONDS(gYear) absent, SECONDS(gMonth) absent
  • SECONDS(date) = 0, the midnight-convention pin

Mutation-checked exactly as you framed it: deleting the presence check in eval_seconds outright now fails precisely the two absent cases, on both lanes, and moves nothing else. Before these, that mutation was silent across the entire suite — so this was the one lane the shared table could not police, as you said.

One wrinkle for the record: a carried SECONDS renders as a JSON string ([["0"]]), because it returns xsd:decimal where the other accessors return xsd:integer. My first pass pinned [[0]] and failed on all three carried cases.

},
Case {
name: "fused SUM(YEAR) over a year-only predicate is carried",
sparql: "SELECT (SUM(YEAR(?o)) AS ?v) WHERE { ?s ex:gyear ?o }",

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 — more of a question than a suggestion. The three fused-lane cases pin the answer but not the routing, and predicate_scalar_agg_operator stamps no fast-path outcome (zero stamp_fast_path sites in fast_predicate_scalar_agg.rs), so a regression that silently disables the fused lane would pass this suite — the fallback computes the same number.

My mutation check proves the lane serves MIXED SUM(DAY) today, but nothing pins that it keeps doing so. #1666 just introduced must-fire stamps for its operator; adding a stamp to this one and reusing the span-capture pattern here would extend that guarantee.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added — but the premise turned out not to hold, and that part is worth recording.

predicate_scalar_agg_operator builds a FastPathOperator, and FastPathOperator::open already stamps fast-path outcome using the operator's label as the site. So these lanes have been stamping all along as SUM(DAY) and SUM(YEAR), despite fast_predicate_scalar_agg.rs containing zero stamp_fast_path calls. Grepping a file for stamp sites undercounts anything built on that operator — I'd assumed the same thing you did until the assertions passed on the first run without any production change.

So the fix was three MustFire assertions plus a span-capture window, nothing else.

Mutation-checked by forcing the operator's compute to decline: exactly the three routing assertions fail, and no value assertion does. That is the blind spot you were describing, demonstrated rather than argued — the fallback returns the identical number, so the values alone can never see it.

I've posted the same correction on #1669, since I had scoped its "audit unstamped fast paths" item on the same wrong premise. That audit is smaller than written: it needs to separate lanes that genuinely emit nothing from lanes that emit under a label nobody has asserted on yet, where only a test is needed.

// A value that carries no seconds (a bare `xsd:gYear`, say) has
// no answer here; report unbound rather than the promotion's
// zero. See `eval_datetime_component`.
if let Some(kind) = temporal_kind_of_binding(binding) {

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 (consistency nit). eval_seconds still calls parse_datetime_from_binding when the binding's kind is unrecognized, while eval_datetime_component routes unrecognized kinds to epoch-millis only. Empirically there's no reachable difference today (I probed string literals both ways — unbound everywhere, indexed and unindexed, HEAD and base), so this is purely about the two accessors reading differently to the next person; gating SECONDS's parse the same way would make them uniform.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not folded in — and on investigation I think the framing needs revising, so flagging rather than quietly declining.

The asymmetry is larger than the two accessors reading differently. eval_datetime_component sends an unrecognized kind to the epoch-millis fallback; eval_seconds sends it to parse_datetime_from_binding, which returns None for any non-temporal datatype — and SECONDS has no epoch-millis path at all. So on LDBC-style data where datetimes are stored as epoch-ms longs, MINUTES(?t) resolves and SECONDS(?t) is unbound. Your probe used string literals, which are unbound both ways; bare longs are the reachable case.

That said, it is pre-existing — base eval_seconds has the same structure, this PR only added the presence gate on top — and it looks deliberate rather than accidental: epoch_millis_component explicitly returns None for CalendarField::Second, commented "SECONDS is fractional (xsd:decimal) and has its own evaluator."

Which means a mechanical unification changes no behavior (the epoch-ms route returns None for Second anyway), and closing the actual gap means giving SECONDS a fractional epoch-ms path — a behavior change with its own oracle, and unbound-to-a-number is precisely the class this PR argues deserves its own review rather than riding along. So I'd rather not widen scope here.

Happy to file it separately if you think the LDBC gap is worth closing — or to leave it, if the deliberate exclusion is the intended contract and it just wants a comment saying so.

(TemporalKind::Time, &[Hour, Minute, Second]),
(TemporalKind::GYear, &[Year]),
(TemporalKind::GYearMonth, &[Year, Month]),
(TemporalKind::GMonth, &[Month]),

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. Pinning carries against an independently spelled-out table (and asserting the two index representations classify alike) is exactly how a single-source-of-truth table should be tested — a typo can't pass by agreeing with itself.

///
/// `Absent` is the case that matters: the value's datatype does not carry the
/// field (`DAY` of an `xsd:gYear`), so the per-row expression is unbound. SUM
/// skips unbound, hence [`Self::sum_contribution`] scores it 0 — but any future

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. ComponentFold::Absent as an explicit state, with sum_contribution making the SUM decision locally, is the right shape — the implicit-default pattern is what produced this bug, and a future AVG/COUNT consumer now has to decide rather than inherit a silent zero. The whole-leaflet Absent fold with no column IO is a nice perf side effect.

@bplatz
bplatz requested review from aaj3f and zonotope August 20, 2026 03:09
Base automatically changed from fix/fastpath-count-divergences to main August 20, 2026 03:18
bplatz added 2 commits August 19, 2026 23:19
SECONDS returns xsd:decimal and so does not route through
eval_datetime_component — it repeats the presence check itself, and the
suite had no SECONDS case at all, so removing that gate entirely passed
every pin. Five cases now cover it: carried on time and dateTime, absent
on gYear and gMonth, and the midnight convention on date. Mutation-checked:
dropping the gate fails exactly the two absent cases on both lanes.

The three fused SUM cases pinned their answer but not the lane they were
served by, and the fallback computes the same number — so a silent disable
of the fused scalar-agg operator was invisible here. They now assert the
site proceeded, via the fast-path outcome stamps.

No production change was needed for that: FastPathOperator::open already
stamps under the operator's label, so the fused lanes stamp as SUM(DAY) and
SUM(YEAR) without any direct stamp_fast_path call in
fast_predicate_scalar_agg. Mutation-checked: forcing the operator to decline
fails exactly the three routing assertions and no value assertion, which is
the blind spot these close.

A carried SECONDS renders as a JSON string, being xsd:decimal.
@bplatz

bplatz commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

Both optional items are folded in, @aaj3f — pushed as 5c1e88181. Merged main in first (clean, ort), so the branch now carries #1666's fixes and CI ran green on it before this commit.

SECONDS pins

You were right that this was the real hole. Five cases: carried on xsd:time and xsd:dateTime, absent on xsd:gYear and xsd:gMonth, and the midnight convention on xsd:date — the field the suite otherwise never touched.

Mutation-checked by deleting the gate in eval_seconds outright: exactly the two absent cases fail, on both lanes, and nothing else moves. Before these, that mutation was silent across the whole suite.

One wrinkle worth recording: a carried SECONDS renders as a JSON string ([["0"]]), since it returns xsd:decimal rather than the xsd:integer the other accessors return. My first pass pinned [[0]] and failed on all three carried cases.

Fused-lane routing — no production change needed

Added, but the premise turned out not to hold, so it's worth correcting for the next person.

predicate_scalar_agg_operator builds a FastPathOperator, and FastPathOperator::open already stamps fast-path outcome using the operator's label as the site. So the fused lanes stamp as SUM(DAY) and SUM(YEAR) today, despite fast_predicate_scalar_agg.rs containing zero stamp_fast_path calls — counting call sites per file understates coverage for anything built on that operator. The fix was three assertions and a span-capture window, no instrumentation.

Mutation-checked by forcing the operator to decline: exactly the three routing assertions fail, and no value assertion does — which is the blind spot you were pointing at, demonstrated rather than argued.

I've posted the same correction on #1669, since I had scoped item 4 there on the same wrong premise; the audit is smaller than I wrote, and should separate lanes that emit nothing from lanes that emit under a label nobody asserts on. Items 1–3 and 5 stand — it_differential_fastpath still asserts no routing at all, and the duplicate "fast path produced result" surface is still in place.

The eval_seconds consistency nit — not folded in

I'd rather leave this one, and the reasoning has changed since your note. The asymmetry is larger than "the two accessors read differently": eval_datetime_component sends an unrecognized kind to the epoch-millis fallback, while eval_seconds sends it to parse_datetime_from_binding, which returns None for any non-temporal datatype — and SECONDS has no epoch-millis path at all. So on LDBC-style data MINUTES(?epochMs) resolves while SECONDS(?epochMs) is unbound. Your probe used string literals, which are unbound both ways; bare longs are the reachable case.

That is pre-existing (base eval_seconds has the same structure) and looks deliberate — epoch_millis_component explicitly returns None for Second, commented "SECONDS is fractional (xsd:decimal) and has its own evaluator." So a mechanical unification changes nothing, and closing the actual gap means giving SECONDS a fractional epoch-ms path: a behavior change with its own oracle, which is exactly the kind this PR argues deserves separate review rather than a quiet widening. Happy to file it separately if you agree it's worth having.

Case count in the body is now 28.

@bplatz
bplatz merged commit c952299 into main Aug 20, 2026
15 checks passed
@bplatz
bplatz deleted the fix/datetime-component-fabrication branch August 20, 2026 11:04
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