Skip to content

fix: accounting-grade exactness for xsd:decimal and unbounded xsd:integer - #1332

Merged
bplatz merged 24 commits into
mainfrom
fix/decimal-exactness
Jun 16, 2026
Merged

bplatz merged 24 commits into
mainfrom
fix/decimal-exactness

Conversation

@bplatz

@bplatz bplatz commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Summary

A review of the engine's numeric handling identified several areas where xsd:decimal and large xsd:integer values needed correction. The storage layer (BigDecimal → NumBig arena) represents these values exactly, but a number of paths into and through it converted via f64 or narrowed to i64 before that representation was reached, which could lose precision or cause values to mismatch. This PR closes those gaps so decimal and big-integer handling is exact end to end: ingestion, query evaluation, aggregation, comparison/dedup, validation, reasoning, and graph-source materialization.

Behavior is unchanged for string/boolean/double data and ordinary i64-range integers; the fixes add type-specific arms that the common paths skip.

Ingestion — exact values from every entry point

Previously only two ingest lanes preserved decimals exactly (JSON-LD string @value, default-graph Turtle). Now exact across the board:

  • SPARQL query constants — 19.99 and "19.99"^^xsd:decimal lower to exact BigDecimal in triple patterns, FILTER/BIND, and VALUES instead of f64.
  • SPARQL UPDATE — INSERT/DELETE DATA and templates persist exact decimals; a delete written with a different scale (1.5 vs 1.50) still matches the stored fact.
  • JSON-number @value — a JSON number typed xsd:decimal is recovered exactly via its shortest round-trip form rather than stored as f64.
  • Bulk-import / graph adapter — JSON-number decimals keep their declared xsd:decimal datatype (they were landing as xsd:double).
  • TriG GRAPH blocks — bare decimals parse exactly, matching the default-graph path; the named-graph transact path now parses all typed literals instead of storing mislabeled strings.
  • Unbounded xsd:integer — integers beyond i64 now promote to BigInt in both the Turtle and SPARQL lexers and in typed-literal lowering. Previously a large bare integer silently became 0, and a typed one errored or degraded to a string.

Query engine — exact values produce correct answers

  • SUM / AVG include arena-backed (indexed) decimals; previously those rows contributed nothing, so a sum over an indexed decimal column was wrong and shifted after indexing. GROUP_CONCAT no longer drops decimals/bigints.
  • GROUP BY / DISTINCT / MINUS / joins / VALUES key decimals by canonical numeric value, so the same value served encoded from the index and decoded from novelty unifies into one group/row, and scale variants (1.5 / 1.50) no longer split.
  • GRAPH scope — NumBig handles are per-(graph, predicate); values escaping a GRAPH { … } block are now decoded against their own graph's arena instead of silently resolving to a different value in the outer graph.
  • Numeric-filter COUNT fast path defers to the exact pipeline on decimal rows instead of counting them as non-matches (an undercount), and bails from a manifest read rather than launching a doomed leaf/partition scan first.

Storage identity

  • The NumBig arena keys decimals on their normalized value, so 1.5 and 1.50 share one handle and one persisted encoding ((o_type, o_key) is fact identity — two encodings broke retract matching). Legacy pre-normalization arenas load with handles preserved and ambiguous lookups decline cleanly.
  • FlakeValue's Hash is now consistent with its cross-type numeric Eq: equal binary-fraction values like Double(2.5) and Decimal(2.5) hash to the same bucket.

Validation, reasoning, graph sources

  • SHACL range facets (sh:minInclusive etc.) and sh:lessThan/lessThanOrEquals compare decimals and bigints via exact cross-type ordering. Previously every decimal value unconditionally failed every range facet.
  • Datalog reasoner gains exact Decimal/BigInt binding variants: decimal objects now match in rule bodies (they matched nothing before), overflow integers no longer zero out, derived facts round-trip losslessly, and equality is exact rather than epsilon-based.
  • R2RML decimal formatting keeps the sign for values between −1 and 0 (-0.5 was materializing as "0.5", corrupting literals and template-generated IRIs).

Performance

Non-decimal paths are unaffected (new arms sit after the existing fast arms). Decimal paths trade a few previously-instant-but-wrong answers for correct ones (e.g. the COUNT fast path defers). One follow-up worth noting: exact decimal constants now resolve to arena handles, so equality lookups currently scan-and-post-filter rather than prefilter-narrow — addressed by #1328 (prefilter arena threading) and #1325 (inline small-decimal encoding).

Testing

New it_decimal_exactness.rs integration suite (12 tests) covers the full loop — exact round-trips, high-precision survival, cross-path retract identity, mixed index/novelty grouping, per-graph arena decoding, and mixed-type COUNT — plus unit tests at each layer. Full workspace suite passes (excluding the known LocalStack testcontainer flakes); clippy clean with --all-features --all-targets; W3C SPARQL suite stable at 250/327 with no regressions.

bplatz added 22 commits June 12, 2026 16:57
Decimal literals (bare 19.99 grammar form and explicit ^^xsd:decimal) were
parsed to f64 and lowered as FlakeValue::Double in every constant position:
triple patterns, FILTER/BIND expressions, and VALUES rows. Values like 19.99
have no exact binary representation, so query constants could never exactly
equal stored BigDecimal values, and VALUES rows carried a Double value
mislabeled with an xsd:decimal datatype.

Decimal lexicals now parse with BigDecimal and lower as FlakeValue::Decimal
across all three lowering sites. Typed-literal lowering splits xsd:decimal
from the xsd:double/xsd:float f64 lane, and the filter-constant passthrough
now admits Decimal/BigInt instead of demoting them to strings.
INSERT DATA / DELETE DATA / Modify templates parsed decimal literals (bare
and ^^xsd:decimal typed) to f64 and persisted FlakeValue::Double under an
xsd:decimal datatype constraint. Every decimal ingested via SPARQL UPDATE
was silently approximated, and a DELETE could fail to match the same value
written exactly via the JSON-LD path (two persisted encodings).

Adds an exact Decimal variant to the query-parse LiteralValue (resolved to
FlakeValue::Decimal with an xsd:decimal datatype in VALUES and template
lowering) and routes all four UPDATE lowering sites through BigDecimal.

Integration tests cover the full loop: insert exact decimal, query it back
by exact constant and FILTER equality, high-precision (>f64) round-trip,
and DELETE DATA retract identity.
A JSON number @value typed xsd:decimal was coerced through f64 and stored
as FlakeValue::Double — sometimes still labeled xsd:decimal — so exactness
depended on whether the client serialized the value as a JSON string or a
JSON number, and the same logical value could persist under two encodings.

JSON-number decimals now parse to exact BigDecimal via the number's
shortest round-trip representation (recovering the written lexical up to
f64's ~17 significant digits; digits beyond that are lost at JSON parse
time and unrecoverable here). Long/BigInt → xsd:decimal convert exactly
instead of widening to f64.

Replaces the lossy-policy test with exact-value assertions and adds a
cross-path integration test: JSON-LD number ingest matched and retracted
by SPARQL decimal constants.
…apter

A JSON number @value declared xsd:decimal was converted to f64 and emitted
as LiteralValue::Double; the sink then re-inferred the datatype from the
value, so the fact landed as a corrupted double typed xsd:double — the
declared datatype was silently dropped. This is the adapter behind both
transact graph ingestion and bulk import.

Decimal-typed numbers now route their lexical through the typed-string
literal path (same pattern as f:embeddingVector), whose shared parser
produces an exact BigDecimal under the declared xsd:decimal datatype.
Bare decimal literals inside GRAPH blocks (trig_meta, serving both /upsert
and bulk TriG import) were parsed as f64 and re-typed xsd:double, while the
same literal in the default graph parsed exactly as xsd:decimal — graph
placement changed both the value and the datatype.

GRAPH-block decimals now keep their lexical and route through the
typed-literal lane. On the transact named-graph path that lane previously
stored raw String flakes mislabeled with the declared datatype (diverging
from bulk import); it now parses lexicals with the shared coercion, so
decimals, integers, and temporals land as proper typed values there too.
…y zeroing

Both the Turtle and SPARQL lexers parsed bare integer literals with
.parse::<i64>().unwrap_or(0): any integer past i64::MAX silently became 0 —
the worst possible failure mode for numeric data. xsd:integer is unbounded,
so these must promote, not corrupt.

Turtle/TriG: a new span-based IntegerOverflow token routes the lexical
through the typed-literal lane (xsd:integer), which already promotes to
BigInt downstream; GRAPH blocks get the same treatment in trig_meta.

SPARQL: a new BigInteger token/AST literal carries the lexical and lowers
to FlakeValue::BigInt (dt xsd:integer) in patterns, FILTER, VALUES, and
both SPARQL UPDATE template lanes, with signed-literal recombination.

End-to-end test: a 30-digit integer round-trips through Turtle ingestion,
SPARQL projection, and constant matching.
Non-streaming SUM/AVG skipped the decode gate (only the streaming
group-aggregate path resolved NUM_BIG through the graph view), and
binding_to_numeric has no NUM_BIG arm — so indexed decimals and overflow
integers contributed nothing to the aggregate. A SUM over an indexed
decimal column silently returned the wrong total (and totals changed after
indexing, since novelty rows still counted).

apply_aggregate now materializes NUM_BIG-encoded group members through the
graph view for Sum/Avg, leaving inline NUM_INT/NUM_F64 encodings on their
native accumulator lanes. GROUP_CONCAT gains Decimal/BigInt arms (it
silently dropped both).

Integration test: SUM/AVG over indexed (arena-backed) decimals is exact.
…raints

The range-facet comparator (sh:minInclusive/maxInclusive/minExclusive/
maxExclusive) matched only Long/Double/String/Boolean variants, and every
constraint handler treats a non-comparable pair as a violation — so any
xsd:decimal (or beyond-i64 integer) value unconditionally failed every
range facet regardless of the actual number. sh:lessThan/lessThanOrEquals
likewise rejected mixed integer-vs-decimal property pairs as incompatible,
and compared Long against Double through a lossy f64 cast.

Both comparators now delegate numeric pairs to FlakeValue::numeric_cmp,
core's exact cross-type ordering (BigDecimal promotion where f64 would
lose precision).
The overlay lane of the numeric-filter COUNT fast path compared rows by
encoded o_key and treated every o_type other than inline XSD_INTEGER /
XSD_DOUBLE as a non-match. Decimal rows (arena-keyed, no value order in
o_key), other integer-family widths, and rows hit by a non-encodable
threshold (e.g. a decimal constant against integer leaflets) were silently
excluded from the count — while the base lane correctly bails per-leaflet
in the same situations.

The overlay lane now flags unsupported-numeric rows and defers the whole
count to the general aggregate pipeline, matching the base lane. Genuinely
non-numeric objects still count as non-matches (the comparison errors,
same as the general pipeline).

Integration test covers integer + decimal rows across base and novelty
with both integer and decimal thresholds.
FlakeValue's Eq is numeric across variants — Double(2.5) == Decimal(2.5) —
but the non-integer Double arm hashed raw f64 bits while the Decimal arm
hashed normalized (scale, digits). Equal binary-fraction values (2.5, 0.25,
1e20 vs its BigInt twin, ...) landed in different hash buckets, breaking
HashSet/HashMap dedup, set membership, and hash-join probes whenever both
representations of a value coexist (e.g. legacy double-stored decimals
alongside exactly-ingested ones).

Every finite f64 is exactly a decimal, so the Double arm now routes through
the same canonical-decimal hasher as the Decimal arm: integer values hash
like integers (matching Long/BigInt), non-integer values hash normalized
(scale, digits). i64-range integer doubles keep their existing fast path.
The arena deduped BigDecimals on raw (unscaled, scale) bytes, so 1.5 and
1.50 — the same xsd:decimal value — minted two handles. (o_type, o_key) is
persisted fact identity: two encodings of one value break retract matching
and equality between rows that entered with different input scales.

get_or_insert_bigdec and find_bigdec now normalize before keying, so every
value has exactly one handle and one persisted encoding. The NBA1 load path
appends entries positionally (handles must stay stable even if a legacy
arena holds scale-variant duplicates) and registers both the raw and
normalized reprs first-wins, so pre-normalization arenas keep working and
new lookups resolve against them.

End-to-end test: a fact indexed as 1.50 is matched and retracted by 1.5.
…rfaces

GROUP BY, DISTINCT, MINUS, semijoin, subquery, hash-join, and VALUES keys
handled NUM_BIG (arena-backed decimal/bigint) bindings by their encoded
identity — a per-(graph, predicate) handle — while decoded rows from
novelty, VALUES, or BIND keyed by value (via a scale-sensitive Debug-string
catch-all). The same decimal split groups, escaped DISTINCT, and failed to
join across representations; scale variants (1.5 vs 1.50) split even
within one representation.

Normalization at these surfaces now decodes NUM_BIG bindings through the
graph view (the encoded form is not canonical for one value across
predicates), and decoded decimals/bigints key by canonical numeric form
(normalized lexical) instead of Debug formatting. equality_norm bundles the
store + graph view so every operator threads both.

Integration test: a value asserted via index and novelty (plus a scale
variant) yields one DISTINCT row and one group.
NumBig arena handles are scoped per (graph, predicate). A GRAPH pattern
runs its inner scan against the named graph's g_id, but encoded NUM_BIG
bindings that escape the scope (projection, ORDER BY, joins outside the
GRAPH block) were later decoded against the OUTER graph's view — resolving
the handle in the wrong arena and silently returning a different value
(handle 0 of the default graph instead of handle 0 of the named graph).

GraphOperator now decodes NUM_BIG bindings against the scope's own graph
view before merging inner rows, and only when the inner g_id differs from
the surrounding query's. Subject/string/predicate dictionaries are
store-global, so all other encoded kinds still escape late-materialized.

Differential test: same handle slot in two graphs' arenas (19.99 default,
42.42 named) — the named-graph projection must return 42.42.
format_decimal computed the integer part with truncating division, which
returns 0 for values like -5/10 — dropping the sign entirely: -0.5
materialized as "0.5", corrupting literals, join keys, and
template-generated IRIs from graph-source decimal columns.

Format from the absolute value and apply the sign explicitly. Also guards
the negative-scale lane against i128 multiply overflow (appends zeros
instead) and handles i128::MIN via unsigned_abs.
…ution

The datalog engine's BindingValue had no Decimal/BigInt variants, so rule
execution corrupted big numerics at every step: flake bindings converted
decimals through f64 and zeroed every overflow integer
(parse::<i64>().unwrap_or(0) on a value that is >i64 by construction),
derived facts re-emitted those corrupted values into the reasoning
overlay, object matching had no decimal arm (decimal constants and joins
silently matched nothing), and equality used epsilon comparison that
conflates adjacent doubles.

BindingValue/ObjectMatch gain exact Decimal/BigInt variants that round-trip
losslessly into derived flakes; object matching and binding equality
compare numeric pairs exactly via FlakeValue::numeric_cmp (BigDecimal
promotion instead of f64 casts); rule filters gain decimal/bigint
comparison support.
The bare-token fix left the typed lexical form behind: query constants
like "123...890"^^xsd:integer still parsed through i64 and errored, and
SPARQL UPDATE's typed-value coercers fell back to a string-valued literal
under the integer datatype. xsd:integer is unbounded — both now promote to
BigInt past i64 (xsd:int/xsd:long stay bounded and error, per spec).

Integration test extends the round-trip: typed-form INSERT DATA and a
typed query constant matching both bare- and typed-ingested values.
Both numeric-compare COUNT lanes could run a full scan that was guaranteed
to end in a fallback: a uniformly-decimal (NUM_BIG) predicate, or a
decimal threshold over uniform integer rows, can never produce an encoded
fast answer, but the base lane still opened and scanned leaves before
bailing per-leaflet, and the overlay lane scanned every partition before
checking its unsupported-row flag — doubling the work against the general
pipeline that ultimately answers.

Both lanes now consult the predicate's POST global extent (a manifest
read) first: uniform unsupported o_type or a non-encodable threshold for
the uniform type defers immediately. Unsupported values arriving only via
novelty still take one overlay pass, bounded by novelty size.
Pre-normalization arenas can hold the same decimal value under several
scale-variant handles. The load path registered the normalized lookup
first-wins, so single-handle consumers saw only one of them: a translated
retract keyed on that handle would silently miss base rows encoded under a
duplicate, and the planned bound-object prefilter (#1328) would have the
same blind spot.

The arena now records duplicate handles at load (empty for any arena
written post-normalization), exposes find_bigdec_handles for every
encoding of a value, and find_numbig_handle declines (None) when a value
is ambiguous — overlay translation then falls back to decoded-value
comparison, which is handle-agnostic. Single-handle arenas are unaffected.
term_to_binding labeled every typed literal xsd:string (except vectors).
Binding::Lit equality includes the datatype, so a typed VALUES constant
like "…"^^xsd:integer could never join against stored values carrying
their real datatype. The binding now resolves the declared datatype IRI
through the encoder, falling back to xsd:string only for unknown IRIs.

Integration test: a typed-integer VALUES row joins both bare- and
typed-ingested values.
The uniform-extent pre-check missed mixed predicates: integer/double rows
plus decimals still launched the leaf (or overlay partition) scan before
bailing. POST sorts by o_type, so a mixed predicate containing decimals
puts the unsupported kind on an extent boundary (inline xsd:decimal and
arena NUM_BIG both sort after the supported types) — when either boundary
o_type is an unsupported numeric, those rows are guaranteed present and
both lanes now defer from the manifest read alone. An unsupported numeric
strictly interior to the extent (e.g. floats under a string boundary)
still falls through to the per-leaflet bail.
@bplatz
bplatz requested review from aaj3f and zonotope June 13, 2026 02:58
bigdecimal 0.4's Display switches to E-notation past a magnitude threshold
(0.0000001 -> "1E-7"), which is invalid xsd:decimal lexical form — that is
xsd:double's space. This surfaced because exact storage now keeps small
decimals as BigDecimal instead of f64 doubles, so they reach the decimal
serialization arms that call to_string() directly.

FlakeValue's Display and every user-facing decimal serialization site
(SPARQL JSON/XML-adjacent, JSON-LD, typed, CONSTRUCT, CSV/TSV, hydration,
GROUP_CONCAT, STR()) now use BigDecimal::to_plain_string(). Internal
hashing/keying paths are unchanged. Normal and money-magnitude values are
unaffected; only values past the exponent threshold change.

Adds a regression test asserting plain-form output and STR() for 0.0000001.

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

🔦

@bplatz
bplatz merged commit 3a87605 into main Jun 16, 2026
14 checks passed
@bplatz
bplatz deleted the fix/decimal-exactness branch June 16, 2026 17:47
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