Skip to content

Store: add count_quads_for_pattern - #1

Open
jdsika wants to merge 1 commit into
mainfrom
feat/count-quads-for-pattern
Open

jdsika wants to merge 1 commit into
mainfrom
feat/count-quads-for-pattern

Conversation

@jdsika

@jdsika jdsika commented Nov 16, 2026

Copy link
Copy Markdown

Summary

Adds count_quads_for_pattern to Store, Snapshot and Transaction, and exposes
it in pyoxigraph.

Counting the quads matching a pattern currently requires iterating quads_for_pattern,
which decodes every match into a Quad even though the caller only wants a number.
In pyoxigraph each match additionally becomes a Python object. The new method counts
at the StorageReader level, on encoded quads, so no decoding, allocation or Python
conversion happens.

This implements the API requested in upstream issue
oxigraph#1262 ("[Feature] Store -
CountForPattern"
), for exactly the reason stated there.

This is the fork-first PR. It is opened against ASCS-eV:main so the change can be
reviewed and exercised here, following the same flow already used for
ASCS-eV/linkml. The upstream PR to
oxigraph/oxigraph follows only after this review.

Why we need it

oxrdflib — the bridge that lets rdflib use oxigraph as a backend — implements
len(graph) as:

SELECT (COUNT(DISTINCT TRIPLE(?s, ?p, ?o)) AS ?c) WHERE { ... }

It cannot call len(store) instead, because len(store) counts quads across all
graphs while rdflib needs distinct triples within one context. pyoxigraph offers
quads_for_pattern (decoding iterator) and __len__ (everything, no pattern) — but no
counting primitive that takes a pattern. That gap is in oxigraph, which is why the fix
belongs here rather than in oxrdflib.

This path is hot for us: our SHACL validation pipeline counts pattern matches
constantly, and perf/rdfs-inference-indexed (merged in ontology-management-base
as oxigraph#119) worked around it rather than fixing the cause.

Benchmark

10,100 quads (10,000 in a named graph, 100 in the default graph), release build,
best of 7 runs, counting the 10,000 quads of the named graph:

Method Time vs new
SELECT (COUNT(DISTINCT TRIPLE(?s,?p,?o))) — what oxrdflib runs 4.323 ms 11.0× slower
sum(1 for _ in store.quads_for_pattern(None, None, None, g)) 2.172 ms 5.5× slower
SELECT (COUNT(*)) 1.231 ms 3.1× slower
store.count_quads_for_pattern(None, None, None, g) 0.394 ms —
len(store) (whole store, native, for reference) 0.190 ms lower bound

The new method lands within ~2× of len(store), which is the practical floor for a
scan-based count.

Implementation

File Change
lib/oxigraph/src/storage/mod.rs StorageReader::count_quads_for_pattern — the actual work
lib/oxigraph/src/store.rs Store / Snapshot / Transaction methods + rustdoc with a doctest
python/src/store.rs Store.count_quads_for_pattern binding
lib/oxigraph/tests/store.rs 4 integration tests
python/tests/test_store.py 2 tests
CHANGELOG.md one Rust bullet, one Python bullet

313 insertions, 0 deletions, no public API changed.

Both backends are handled: the RocksDB arm iterates and propagates per-item Results
with quad?; so an I/O error mid-scan cannot silently truncate the count; the memory
arm uses .count().

Counting the iterator is exact: RocksDB's quads_for_pattern dispatches each
bound/unbound combination to its own index with no post-filtering, and the
default-graph and named-graph indexes are disjoint.

Deliberately not done

The memory backend already keeps per-term counts (DashMap<EncodedTerm, (Weak<QuadListNode>, u64)>)
to choose the smallest index. For a pattern with exactly one bound term, that count
would give O(1) instead of O(matches). It is not used here because it is not
obvious that those counts are correct for a reader pinned to an older version or after
deletions, and a wrong count is far worse than a slow one. Worth a follow-up if a
maintainer can confirm the semantics.

Also out of scope, both plausible follow-ups: Dataset.count_quads_for_pattern in
pyoxigraph and the equivalent JS binding.

Testing

Every Rust check from upstream's .github/workflows/tests.yml, run locally:

Check Result
cargo fmt -- --check pass
cargo clippy -p oxigraph --all-targets --no-default-features -- -D warnings -D clippy::all pass
cargo clippy -p oxigraph --all-targets -- -D warnings -D clippy::all pass
cargo clippy -p pyoxigraph --all-targets -- -D warnings -D clippy::all pass
cargo test -p oxigraph --no-default-features pass — 15 store tests, 63 doctests
cargo test -p oxigraph (RocksDB) pass — 32 store tests, 63 doctests
cargo doc -p oxigraph --no-deps pass

Python job:

Check Result
uv run --locked -m unittest 206 passed
uv run --locked sphinx-build -M html . build pass
uv run --locked python generate_stubs.py pyoxigraph pyoxigraph.pyi --ruff pass
uv run --locked ty check generate_stubs.py tests pass
uv run --locked ruff format --check . / ruff check . pass
uv run --locked -m mypy.stubtest pyoxigraph --allowlist=mypy_allowlist.txt pass
uv run --locked sphinx-lint docs pass

One pre-existing test, test_store.TestStore.test_update_load, was skipped locally:
it runs LOAD <https://www.w3.org/1999/02/22-rdf-syntax-ns> and this machine has no
direct internet egress. It is unrelated to this change and runs normally in CI.

Test design

test_count_quads_for_pattern (memory) and test_count_quads_for_pattern_on_disk
(RocksDB, feature-gated) both run a 192-combination cross-check: 4 subjects ×
3 predicates × 4 objects × 4 graph names — unbound, matching, and deliberately
non-existent terms in each position — asserting
count_quads_for_pattern(...) == quads_for_pattern(...).count(). The fixture puts the
same triple in both the default graph and a named graph, which is where a naive
implementation double-counts.

Plus test_count_quads_for_pattern_on_empty_store and
test_count_quads_for_pattern_isolation (a transaction sees its own uncommitted write;
a snapshot taken earlier stays pinned).

Mutation testing

A green suite proves nothing unless it goes red when the code is wrong, so the
implementation was deliberately broken three ways:

Injected bug Caught
Swap the predicate and object filters yes — the 192-combination cross-check
Ignore the graph_name filter yes
Off-by-one (count - 1) yes, by 2 tests

All four new tests were also confirmed to execute by name, including the
feature-gated on-disk one.

Honest limitation: removing the quad?; error propagation in the RocksDB arm is not
caught by any test — provoking a mid-scan I/O error needs fault injection that oxigraph
does not have. It is in the diff because it is correct, not because a test forced it.

Review checklist

  • Is count_quads_for_pattern the name upstream wants? [Feature] Store - CountForPattern oxigraph/oxigraph#1262 says CountForPattern; this name was chosen to mirror quads_for_pattern.
  • Should the Transaction variant stay (symmetry with quads_for_pattern/len) or be dropped for minimalism?
  • Is the deferred memory-backend O(1) fast path actually safe? If so it is a worthwhile follow-up.
  • Should Dataset and the JS binding get the same method before going upstream?

Counting the quads matching a pattern currently requires iterating over
`quads_for_pattern`, which decodes every match into a `Quad` even though
the caller only wants a number. In pyoxigraph the cost is higher still,
because each match additionally becomes a Python object.

`count_quads_for_pattern` counts at the `StorageReader` level, on the
encoded quads, so no decoding, allocation or Python conversion happens.
The method is added to `Store`, `Snapshot` and `Transaction` for
consistency with `quads_for_pattern`, and exposed in pyoxigraph.

The memory backend already keeps per-term counts for index selection,
which could make single-bound-term patterns O(1). That is left out here
because those counts are not obviously correct for a reader pinned to an
older version.

Closes oxigraph#1262

Signed-off-by: Carlo van Driesten <[email protected]>
@jdsika jdsika closed this Nov 16, 2026
@jdsika jdsika reopened this Nov 16, 2026
@jdsika

jdsika commented Nov 16, 2026

Copy link
Copy Markdown
Author

CI results

Actions are now enabled on this fork, so upstream's full Change tests matrix ran:
run 43914467096.

39 pass, 3 fail — all 3 failures are external-service uploads this fork cannot
authenticate to. No code failures.

Highlights, in particular the things that cannot be checked on a single Linux box:

Job Time
clippy (full workspace, RocksDB) 18m45s
test_windows pass
test_macos 18m00s
test_linux_i686 (32-bit — relevant for the usize return) 14m17s
test_linux_address_sanitizer 7m57s
test_linux_dynamic_linking 15m55s
test_linux_msv pass
python 9m05s
python_msv_windows (Python 3.9) 16m11s
semver_checks (confirms the change is purely additive) pass
rustdoc 8m40s
fuzz_changes × 12 (incl. sparql_update_eval --features rocksdb) ~6m each
clippy_wasm_* × 4, test_wasip1, js pass
fmt, clang_fmt, toml-fmt, typos, deny, zizmor, shellcheck, spec_links, debian_compatibility pass

The three failures

Job Failing step Why
codecov codecov/codecov-action the preceding cargo llvm-cov … succeeded — the whole suite ran under coverage instrumentation and passed. Only the upload failed.
codspeed_testsuite CodSpeedHQ/action cargo codspeed build -p oxigraph-testsuite succeeded. Only the upload failed.
codspeed CodSpeedHQ/action same

Both services authenticate via OIDC (id-token: write) against a project registered
for oxigraph/oxigraph; this fork is not registered with either, so the token
exchange fails. In every case I checked the steps individually: the build/test step
passed and only the upload step failed.

These will pass on the upstream PR, where the service registrations exist.

@jdsika

jdsika commented Nov 17, 2026

Copy link
Copy Markdown
Author

CI is green

Run https://github.com/ASCS-eV/oxigraph/actions/runs/44049773533: 39 pass, 3 skipped, 0 fail.

The three earlier red jobs (codspeed, codspeed_testsuite, codecov) failed only at the upload step (CodSpeed 401 Unauthorized, Codecov Repository not found) because the fork is not registered with either service. They are now skipped unless the repository is oxigraph/oxigraph. That guard is a separate fork-only change, #2, merged into fork main. This PR's commit is unchanged (1d3774a, +313/−0), so it remains a faithful preview of the upstream PR and does not contain the guard.

Reminder for the upstream PR: branch from upstream/main, not fork main.

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.

1 participant