Repository navigation
Description
An ungrouped aggregate over a datalog-derived predicate returns 0 (or an empty aggregate) while the identical pattern without the aggregate returns the derived rows. No error, no warning — the query succeeds and the answer is wrong.
owl2rl-derived facts aggregate correctly, and GROUP BY over the same datalog predicate is also correct, which narrows this considerably.
Minimal repro
Three triples and a rule that copies :knows to :acq:
@prefix : <http://example.org/> .
:a :knows :b . :b :knows :c . :c :knows :d .{ "@context": {"ex":"http://example.org/","f":"https://ns.flur.ee/db#"},
"@id": "ex:r1",
"f:rule": {"@type":"@json","@value":{
"@context":{"ex":"http://example.org/"},
"where": {"@id":"?a","ex:knows":{"@id":"?b"}},
"insert": {"@id":"?a","ex:acq":{"@id":"?b"}} }} }$ fluree create --direct iso:main --from plain.ttl
$ fluree insert -l iso:main -f rule.json
Then, all with # PRAGMA reasoning: datalog:
| query | result | expected |
|---|---|---|
SELECT ?a ?b WHERE { ?a :acq ?b } |
3 rows | 3 rows |
SELECT (COUNT(*) AS ?n) WHERE { ?a :acq ?b } |
0 | 3 |
SELECT (COUNT(?a) AS ?n) WHERE { ?a :acq ?b } |
0 | 3 |
SELECT ?a (COUNT(?b) AS ?n) WHERE { ?a :acq ?b } GROUP BY ?a |
3 rows, counts correct | correct |
SELECT (COUNT(*) AS ?n) WHERE { ?a :knows ?b } (base predicate, no reasoning) |
3 | 3 |
Both surfaces
The JSON-LD path behaves the same way, with top-level "reasoning":"datalog":
select ["?a","?b"] -> [["ex:a","ex:b"],["ex:b","ex:c"],["ex:c","ex:d"]]
select ["(count ?a)"] -> [[0]]
and (count ?a) over the base ex:knows returns [[3]], so the aggregate itself is fine.
What narrows it
owl2rlis not affected. On the same ledger,# PRAGMA reasoning: owl2rlwith a symmetric-property axiom gives 10 rows for the non-aggregate form and10forCOUNT(*). So it is not "aggregates cannot see a reasoning overlay" in general — the owl2rl overlay is visible to the aggregate path and the datalog one is not.GROUP BYis not affected. The grouped form over the same datalog predicate returns the right groups and the right counts, so the derived facts are reaching some aggregate path.- Annotations are not involved. The repro rule body is a plain triple pattern. I first hit this with a rule that reads edge annotations, but it reproduces with the simplest possible rule.
That combination suggests the ungrouped aggregate path takes a different route to the row source than both the grouped path and the non-aggregate path, and that route misses the datalog derived-facts overlay specifically.
Why it matters
It is a silent wrong answer on a shape people reach for early — "how many of these did my rule derive" is the natural first thing to ask after writing a rule, and it answers 0. Someone checking whether their rule works this way would conclude it does not, while a SELECT of the same pattern shows it plainly does.
It also makes any rule-driven metric quietly wrong rather than obviously broken.
Environment
Reproduces on main @ 3d89e8f and on the v4.2.0 release, so it is long-standing rather than a regression from the datalog engine replacement in #1823.
Adjacent, much smaller
On the JSON-LD path, "opts": {"reasoning": "datalog"} is silently ignored — the query runs with no reasoning and returns 0 rows — while top-level "reasoning": "datalog" works. If opts is not a supported location for that key, rejecting an unknown key there would be kinder than returning an empty result.
Activity
aaj3f commentedon Sep 16, 2026
Correcting my own issue. I had this audited properly against
main@3d89e8f71with a release binary built from that commit, and everything below was run, not traced — which matters, because the mechanism I guessed at in the body is wrong and both of the facts I used to narrow it are false.This is not a datalog bug, and it is not a reasoning bug
The root cause is one hoisted check in the ungrouped-
COUNTfast path,fluree-db-query/src/fast_count.rs:66-68:sid_to_p_idresolves throughfind_predicate_id(fluree-db-binary-index/src/read/binary_index_store.rs:1828), which is a lookup in the persisted index dictionary only. A predicate that lives solely in novelty or in a reasoning overlay has no entry there.The damage is where that check sits rather than what it says.
count_rows_operatorhas two lanes — Lane 1 (fast_count.rs:70-79) is a metadata-only PSOT directory sum, correctly guarded byoverlay_free && ctx.to_t == store.max_t(); Lane 2 (:81-93) iscount_predicate_overlay_delta, a base count plus a bounded novelty rescan. Under Lane 1's guard "absent ⇒ 0" is perfectly sound, because no overlay can contribute. Under Lane 2 it is simply false. The check is above the split, so the unsound reading gets applied unconditionally. My "different route to the row source" hunch was right about there being a different route and wrong about everything after that: the route doesn't miss the datalog overlay, it never reaches any overlay, because it short-circuits before lane selection happens.Routing stamp on every failing case below, so nobody has to take my word for which operator is serving these:
The real headline: insert a property, count it, get 0
No rules. No reasoning. No PRAGMA. A plain
fluree insertof one triple on a brand-new predicate against an indexed ledger:fluree insertofex:a ex:likes ex:z, predicate never indexedSELECT ?a ?b WHERE { ?a :likes ?b }SELECT (COUNT(*) AS ?n) WHERE { ?a :likes ?b }GROUP BY ?a:a | 1COUNT(*)withFLUREE_DISABLE_QUERY_FAST_PATHS=1fluree index iso:mainCOUNT(*):acq, after the samefluree indexCOUNT(*)So the accurate summary is "insert a property, count it, get 0 until background indexing catches up", and on any write-active server that window is permanently open for whatever predicate was introduced most recently. The datalog case in my original repro is the same defect with a window that never closes, because a derived predicate never enters the persisted dictionary at all.
Both narrowing claims in the body are wrong
owl2rlis affected. My probe used a symmetric-property axiom over:knows, which derives more flakes for a predicate that is already in the base index — so it resolves ap_id,overlay_has_noveltyis true, Lane 1 is skipped and Lane 2 merges the overlay properly. It escaped by data shape, not by reasoning mode. Swap in anowl:inverseOfaxiom that mints a predicate with zero base assertions and it fails identically:GROUP BYis not evidence that "the derived facts are reaching some aggregate path". It escapes for a structural reason with nothing to do with overlays:implicit_single_aggregate(operator_tree.rs:596-612) requiresGrouping::Implicit,GROUP BYproducesGrouping::Explicit, sodetect_predicate_count_rowsnever matches and the gate atoperator_tree.rs:2743is skipped entirely. The plainSELECTescapes for a different structural reason again — the generic range path handles the same dictionary miss correctly, mapping it tooverlay_only_flakes(fluree-db-query/src/binary_range.rs:425-433), i.e. "the base scan cannot match" rather than "nothing matches". Which is the semanticsfast_count.rs:66should have had.Confirmed on SPARQL, JSON-LD and Cypher — they share the IR, and Cypher's
RETURN count(*)gives 0 with fast paths on and 1 with them off over the same data.The environment call in the body holds, and now has a commit behind it
I wrote that this is long-standing rather than a regression from #1823. That is right, and the commit is
b9fbfe35c(2026-06-02, "perf: overlay novelty-delta for single-predicate and UNION COUNT(*)"). Before it the whole operator sat behind a singlefast_path_storegate that already required!overlay_has_novelty, under which the shortcut was sound. That commit replaced the one gate with the two lanes so the operator could keep firing under novelty — the perf win — and left thesid_to_p_idshortcut sitting above the split, where its soundness precondition no longer holds. A gate-relaxation seam, and #1823 is unrelated except that it made datalog materialization good enough that people started asking "how many did my rule derive", which is how a three-and-a-half-month-old defect surfaced now.Worth saying that
fast_count.rs:66is the only site in the fast-path family that gets this wrong —fast_predicate_scalar_agg.rs:516-525,fast_union_star_count_all.rs:754-758,fast_group_count_firsts.rs:1285-1289and three of its own siblings in the same file (fast_count.rs:225-227,:812-815,:934-939) all branch explicitly on novelty and defer.What I think we should do with the issue itself
As filed this is
P1/area:datalogand reads as a datalog aggregate defect. It is anarea:queryfast-path defect that returns silent wrong counts with no reasoning enabled, on any ledger carrying uncommitted novelty. I'd retitle and relabel in place rather than file a superseding issue, since the repro and the fix are the same thing:P1→P0(drop everything: data correctness), which is what a silently wrongCOUNTon a plain insert is.area:datalog→area:query.I've applied those two. The title I've left alone, because the two candidates read quite differently and I'd rather not pick unilaterally — either "Ungrouped
COUNTreturns 0 for any predicate that is not in the persisted index — insert a property, count it, get 0", or, shorter, "COUNT(*)over a novelty-only or overlay-only predicate returns 0". Happy for anyone to just make the call and rename it; the first is more useful to someone scanning the issue list, the second is more accurate about the mechanism.I've deliberately not edited the body either, so the original narrowing paragraph stands and this comment has something to point at.
Fix
In flight — roughly 8 lines, and it is a move rather than a rewrite: push the
sid_to_p_idmiss down into each lane, so Lane 1 keeps returning 0 (where that is sound) and Lane 2 returnsOk(None)and defers to the generic pipeline, which is the shape the three siblings in the same file already use. It costs the hot path nothing — the lookup is one hashmap probe either way, it just moves inside theif— and the deferral only ever fires when the base index has zero rows for that predicate, so the generic fallback's work is bounded by the overlay rows it has to count anyway. Measured 192µs generic vs 185µs for the wrong fast answer, which is noise.The tests are the bigger half, and the coverage gap is worth naming because it is the reason this lived three and a half months: every datalog/rules suite is memory-backed (
it_datalog_rules.rs,it_datalog_rules_annotations.rs,it_reasoning_join_repro.rs,it_datalog_rules_sparql.rs,it_rules_source.rs— allFlureeBuilder::memory()), socount_rows_operatorreturnsOk(None)on its first line and the fast path is never exercised at all. Those suites are green vacuously. And the differential harnessit_differential_fastpath.rsdoes build indexed ledgers, but itsOverlaycondition only ever adds new subjects on existing predicates — no condition anywhere introduces a predicate that exists only in the overlay, which is the exact hole this lives in. So the regression test has to be file-backed with routing stamps on both sides (aMustFirecase on an indexed predicate is the non-vacuity canary; without it a mis-built fixture makes everyMustNotFirepass for the wrong reason), and widening that harness condition is probably the thing that actually closes the family.Separately, the
opts.reasoningfootnote at the bottom of the issue still stands and I'd lean toward honoring it as an alias rather than erroring —parse_object_var_parsing(fluree-db-query/src/parse/options.rs:514-522) already readsoptsfirst and falls back to top level, so the codebase is itself inconsistent about where a query-level key lives, and rejecting unknownoptskeys generally isn't viable given the server injects its own (fluree-db-api/src/authorization.rs:99). That one is a small API-surface call rather than a technical one though — happy to be argued out of it.[-]Ungrouped aggregates over datalog-derived predicates return 0 while the same pattern returns rows[/-][+]COUNT(*) over a novelty-only or overlay-only predicate returns 0[/+]test(query): pin fluree#1863 overlay-only predicate counts on all thr…