Repository navigation
fix(query): answer unbound for a calendar field the value does not carry - #1667
Conversation
`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
left a comment
There was a problem hiding this comment.
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;
ComponentFoldmakes 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 }", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)carriedSECONDS(gYear)absent,SECONDS(gMonth)absentSECONDS(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 }", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]), |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
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.
|
Both optional items are folded in, @aaj3f — pushed as SECONDS pinsYou were right that this was the real hole. Five cases: carried on Mutation-checked by deleting the gate in One wrinkle worth recording: a carried SECONDS renders as a JSON string ( Fused-lane routing — no production change neededAdded, but the premise turned out not to hold, so it's worth correcting for the next person.
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 — The
|
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:gYearhas a year and nothing else, soDAY("2005"^^xsd:gYear)has no answerin 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:
YEAR("2005"^^xsd:gYear)MONTH/DAY("2005"^^xsd:gYear)DAY("2005-07"^^xsd:gYearMonth)YEAR("--03"^^xsd:gMonth)YEAR("---17"^^xsd:gDay)YEAR("13:45:00"^^xsd:time)DAY("2005-07-17"^^xsd:date)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:datewithxsd:gYear, which isordinary 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:
AVG(DAY(?o))COUNT(DAY(?o))SUM(DAY(?o))FILTER(DAY(?o) < 15)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)histogramgot 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 theaggregates 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:datekeeps its time-of-day fieldsat 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/DAYof a date, the overwhelmingly common uses, are genuine eitherway — 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 flipif 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 columnIO. Each carried its own copy of the defaults, and they had already drifted:
Longonxsd:gYear, while the generic pathlet the same value reach the epoch-millis fallback instead;
xsd:date;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 keepsdefaults of its own. The one surviving 1970 outside that table is
xsd:date'sstorage encoding, which counts days from the epoch.
The fused lane also gains an explicit
Absentstate rather than a bareOption,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 thefast-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:datemidnight convention has its own pin. Unit tests influree-db-core::temporalcheck the presence table against an independentlyspelled-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/.monthaccessors sharethis path), 1440
fluree-db-queryunit tests, 789fluree-db-coretests, the 764query-binary tests, clippy
--all-features --all-targets -D warnings, andcargo fmt --check.Review follow-up
SECONDS pins.
eval_secondsreturnsxsd:decimaland so does not route througheval_datetime_component— it repeats the presence check itself, and the suite had no SECONDScase at all, so removing that gate entirely passed every pin. Five cases now cover it: carried on
xsd:timeandxsd:dateTime, absent onxsd:gYearandxsd:gMonth, and the midnight conventionon
xsd:date. Mutation-checked — dropping the gate fails exactly the two absent cases, on bothlanes. (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::openalready stampsfast-path outcomeunder the operator's label, so the fused lanes stamp as
SUM(DAY)/SUM(YEAR)despitefast_predicate_scalar_agg.rscontaining no directstamp_fast_pathcall — grepping a file forstamp 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_componentconsistency nit is deliberately not folded in — seethe review thread.