Skip to content

COUNT(*) over a novelty-only or overlay-only predicate returns 0 #1863

Closed

Description

@aaj3f

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

  • owl2rl is not affected. On the same ledger, # PRAGMA reasoning: owl2rl with a symmetric-property axiom gives 10 rows for the non-aggregate form and 10 for COUNT(*). 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 BY is 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

  1. added
    bug
    P1
    area:datalog
    on Sep 16, 2026
  2. aaj3f commented on Sep 16, 2026

    @aaj3f
    ContributorAuthor

    Correcting my own issue. I had this audited properly against main @ 3d89e8f71 with 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-COUNT fast path, fluree-db-query/src/fast_count.rs:66-68:

    let Some(p_id) = store.sid_to_p_id(&pred_sid) else {
        return Ok(Some(build_count_batch(out_var, 0)?)); // predicate absent => 0
    };

    sid_to_p_id resolves through find_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_operator has two lanes — Lane 1 (fast_count.rs:70-79) is a metadata-only PSOT directory sum, correctly guarded by overlay_free && ctx.to_t == store.max_t(); Lane 2 (:81-93) is count_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:

    $ RUST_LOG=fluree::fastpath=debug fluree -v query -l iso:main -f q_count.rq
    DEBUG fluree::fastpath: fast-path outcome site="COUNT rows" outcome="proceed"
    

    The real headline: insert a property, count it, get 0

    No rules. No reasoning. No PRAGMA. A plain fluree insert of one triple on a brand-new predicate against an indexed ledger:

    setup query result expected
    fluree insert of ex:a ex:likes ex:z, predicate never indexed SELECT ?a ?b WHERE { ?a :likes ?b } 1 row 1 row
    same SELECT (COUNT(*) AS ?n) WHERE { ?a :likes ?b } 0 1
    same same, GROUP BY ?a :a | 1 correct
    same COUNT(*) with FLUREE_DISABLE_QUERY_FAST_PATHS=1 1 1
    same, after fluree index iso:main COUNT(*) 1 1 — self-heals
    datalog rule deriving :acq, after the same fluree index COUNT(*) 0 3 — never heals

    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

    owl2rl is 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 a p_id, overlay_has_novelty is true, Lane 1 is skipped and Lane 2 merges the overlay properly. It escaped by data shape, not by reasoning mode. Swap in an owl:inverseOf axiom that mints a predicate with zero base assertions and it fails identically:

    :knownBy a owl:ObjectProperty ; owl:inverseOf :knows .     # PRAGMA reasoning: owl2rl
    SELECT ?x ?y   WHERE { ?x :knownBy ?y }   -> 3 rows
    SELECT (COUNT(*) AS ?n) WHERE { ?x :knownBy ?y }  -> 0      <-- site="COUNT rows" outcome="proceed"
    same with FLUREE_DISABLE_QUERY_FAST_PATHS=1       -> 3
    

    GROUP BY is 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) requires Grouping::Implicit, GROUP BY produces Grouping::Explicit, so detect_predicate_count_rows never matches and the gate at operator_tree.rs:2743 is skipped entirely. The plain SELECT escapes for a different structural reason again — the generic range path handles the same dictionary miss correctly, mapping it to overlay_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 semantics fast_count.rs:66 should 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 single fast_path_store gate 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 the sid_to_p_id shortcut 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:66 is 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-1289 and 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:datalog and reads as a datalog aggregate defect. It is an area:query fast-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 wrong COUNT on 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 COUNT returns 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_id miss down into each lane, so Lane 1 keeps returning 0 (where that is sound) and Lane 2 returns Ok(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 the if — 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 — all FlureeBuilder::memory()), so count_rows_operator returns Ok(None) on its first line and the fast path is never exercised at all. Those suites are green vacuously. And the differential harness it_differential_fastpath.rs does build indexed ledgers, but its Overlay condition 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 (a MustFire case on an indexed predicate is the non-vacuity canary; without it a mis-built fixture makes every MustNotFire pass for the wrong reason), and widening that harness condition is probably the thing that actually closes the family.

    Separately, the opts.reasoning footnote 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 reads opts first and falls back to top level, so the codebase is itself inconsistent about where a query-level key lives, and rejecting unknown opts keys 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.

  3. added
    P0
    area:query
    and removed
    P1
    area:datalog
    on Sep 16, 2026
  4. changed the title [-]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[/+] on Sep 16, 2026
  5. added a commit that references this issue on Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P0area:querybug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions