Repository navigation
Description
Summary
OPTIONAL { ?child skos:broader ?c }, where ?c is bound by the required side and sits in the
object position, is executed as "whole predicate, filtered per required row":
- CPU is
required rows x triples of the predicate; - memory grows by about 170 KB per required row, and stays resident after the response.
On a real vocabulary (61,505 concepts in one scheme, 18,748 skos:broader triples) opening the
scheme in the new Vocabularies page took the standalone server to 43 GB of RSS in about 25 s, at
which point the kernel OOM killer stopped it (48 GB machine, two such queries in flight). The same OPTIONAL with the subject bound, the same join without
OPTIONAL, and the same OPTIONAL with ?c supplied through VALUES all answer in a few
milliseconds.
Versions
fluree/dbrevffeeec554(the revision pinned by solo9fdbb65f1a);
fluree-db-query/src/optional.rsis identical atac1e8a61b.fluree-aistandalone0.10.0-dev.41+g9fdbb65f1,release-fastprofile, Linux x86_64.- Single ledger, data indexed (
index-t == t).
Reproduction
gen.py and the comparison queries are at the end of this issue.
python3 gen.py # repro.ttl: 20,000 concepts in ex:scheme, 5,000 skos:broader triples
# create a ledger "optional-repro", then:
curl ... -X POST $BASE/v1/fluree/insert/optional-repro -H 'content-type: text/turtle' --data-binary @repro.ttl
curl ... -X POST $BASE/v1/fluree/query/optional-repro -H 'content-type: application/json' --data-binary @1-reverse-optional.jsonThe failing query (1-reverse-optional.json):
{
"@context": { "skos": "http://www.w3.org/2004/02/skos/core#", "ex": "http://example.org/" },
"select": ["?c", "?child"],
"where": [
{ "@id": "?c", "skos:inScheme": { "@id": "ex:scheme" } },
["optional", { "@id": "?child", "skos:broader": "?c" }]
]
}Run it under a memory limit (container or cgroup). The memory stays resident after the response
has been sent: 3.5 GB still held 10 s later, back to 150 MB once the next query had been served.
Measurements
Synthetic ledger, server restarted before each reverse-OPTIONAL run, peak RSS of the server process
(idle RSS is about 95 MB):
| Query | Required rows | Result rows | Time | Peak RSS |
|---|---|---|---|---|
2-inner-join (same pattern, no OPTIONAL) |
20,000 | 5,000 | 0.01 s | 99 MB |
3-forward-optional (OPTIONAL { ?c skos:prefLabel ?pref }) |
20,000 | 20,000 | 0.06 s | 127 MB |
4-values-reverse-optional (?c from VALUES) |
20,000 | 24,500 | 0.15 s | 164 MB |
1-reverse-optional, with a filter keeping 11,111 required rows |
11,111 | 12,110 | 1.23 s | 1,991 MB |
1-reverse-optional |
20,000 | 24,500 | 2.19 s | 3,290 MB |
5-sparql-reverse-optional (SPARQL spelling) |
20,000 | 24,500 | 2.23 s | 3,538 MB |
That is 160 to 171 KB per required row, whatever the size of the predicate.
Customer vocabulary, runs in sequence on one server:
| Scheme members (required rows) | skos:broader triples |
Time | Memory |
|---|---|---|---|
| 295 | 18,748 | 0.11 s | 128 MB peak |
| 1,172 | 18,748 | 0.42 s | 335 MB peak |
| 2,137 | 18,748 | 0.76 s | 452 MB peak |
| 4,089 | 18,748 | 1.46 s | 843 MB peak |
| 61,505 (query of the Vocabularies page, 6 OPTIONALs) | 18,748 | never completed | OOM-killed at 43 GB |
Results are correct in every case that completes; this is a cost problem, not a correctness one.
Analysis
Two things compound, both in fluree-db-query/src/optional.rs.
1. An EncodedSid binding is not substituted in object position
PatternOptionalBuilder::substitute_pattern resolves a late-materialised subject to an IRI
(PatternPosition::Subject, Binding::EncodedSid arm, through ctx.graph_view()), but the object
arm leaves it free:
Binding::EncodedSid { .. } | Binding::EncodedPid { .. } => {
// Late materialized IRI: no decode context here; leave unbound.
}ctx is a parameter of the function, so the decode context is available there. With the object
left free:
- the batched probe is declined (
build_batchneeds a subject column), so the operator takes the
per-row path; - the substituted pattern is
?child skos:broader ?cwith nothing bound, i.e. the whole predicate; cache_keygives every row the same key (theutoken), so the scan runs once, but each
required row receives a deep clone of the whole result ((**cached).clone()) andunify_check
walks all of it.
Hence required rows x predicate triples clone-and-compare steps: 10^8 for the synthetic case
(2 s), 1.15 x 10^9 for the customer scheme.
When the same value arrives as Binding::Iri / Sid (the VALUES variant) it is substituted and
the cost disappears, which is what the measurements show.
2. The per-row path emits one over-allocated batch per required row
In OptionalOperator::next_batch, output_columns is allocated with
Vec::with_capacity(batch_size) for every column, and the loop breaks as soon as
rows_added > 0 && pending_output.is_empty(). On the per-row path pending_output holds one entry
at a time, so each required row produces its own output batch of one or a few rows, carrying
columns sized for 1,000 rows.
With size_of::<Binding>() == 88, that is 1000 x 88 x columns bytes per required row: 176 KB for
the two-column repro, which matches the 160 to 171 KB measured. The Vocabularies query carries six
columns over about 74,000 rows, i.e. about 39 GB for one query, more than the machine had. I have
not instrumented the allocator; this is the reading of the code that fits the numbers.
The batched path does not show it because it queues every row of the required batch first and then
fills complete batches.
Suggested fixes
- In
substitute_pattern, resolveBinding::EncodedSidin object position toTerm::Iri, the way
the subject arm does, and key it inpush_cache_key_componentaccordingly (today only the
subject slot is keyed bys_id). The doc comment ofobject_var_shared_with_requiredalready
notes that this slot is left free; the cost of leaving it free is what this report adds. - In
next_batch, keep accumulating across required rows untilbatch_sizeis reached or the
input is exhausted, or shrink the columns before building the batch, so that a per-row path never
returns 1,000-capacity columns for one row. - Longer term: a probe lane keyed on the object (OPST) for this shape, the mirror of
batched_subject_probe_binary.
Related observations
- The approximate memory budget (
BINDING_EST_BYTESaccounting incontext.rs) did not abort the
query before the process reached the machine limit. - Cooperative cancellation works on this path (
ctx.check_cancelled()in the per-row loop): with
solo's RSS watchdog enabled the query is cancelled cleanly. The resident memory is not returned
afterwards; that part is reported on the solo side.
Related issues and pull requests
None of them covers this shape; searched on 2026-09-28.
- perf: EXISTS semijoin cache probe declines EncodedSid rows to the generic per-row path #1320 (open): the EXISTS / OPTIONAL subject probe declines
EncodedSidrows to the per-row path.
Same family (late-materialised bindings missing a fast path), but on the subject side and
reported as a missed optimisation, without the memory growth. - fix(query): let OPTIONAL extend a row that left the shared variable unbound #1724 (merged): OPTIONAL over a row that left the shared variable unbound; it touches
substitute_patternbut not theEncodedSidobject arm, which dates from the v4 baseline
(5985d0f01), like theVec::with_capacity(batch_size)allocation innext_batch. - OPTIONAL's right operand is evaluated correlated with the left, where SPARQL §18.2 evaluates it independently (nested-opt-1) #1725 (open): correlated evaluation of the OPTIONAL right operand. A fix here only substitutes a
value that is already correlated, so it should not change that discussion. - perf(query): let LIMIT stop property joins and OPTIONAL early #1936 (merged, included in
ffeeec554): letsLIMITstop the coalesced OPTIONAL seed early; it
applies to the batched path, which this shape never reaches. - perf(query): accelerate joins, existence checks, and counts #1959 (open): join, EXISTS and count accelerations; does not touch
optional.rs. - fix(query): close the memory-budget blind spot on the non-aggregate scan path #1521 (merged): memory-budget accounting on the scan path;
optional.rshas norecord_alloc/
checkpointcall, so the OPTIONAL operator is outside that accounting.
Workaround on the client side
Ask for the children in a separate query with a plain join
({ ?c skos:inScheme <scheme> . ?child skos:broader ?c }, 0.02 s on the customer scheme) and merge
in the client, or pass the concept IRIs through VALUES.
Reproduction files
gen.py
#!/usr/bin/env python3
"""Synthetic SKOS vocabulary for the reverse OPTIONAL report.
N flat concepts in one scheme; the first P of them are the parent of K children each.
Writes repro.ttl (about 75,000 triples with the defaults) and the VALUES variant of the query.
"""
import json
N, P, K = 20000, 500, 10
with open("repro.ttl", "w") as out:
out.write("@prefix skos: <http://www.w3.org/2004/02/skos/core#> .\n")
out.write("@prefix ex: <http://example.org/> .\n\n")
out.write('ex:scheme a skos:ConceptScheme ; skos:prefLabel "Repro scheme"@en .\n')
for i in range(N):
out.write(f'ex:c{i} a skos:Concept ; skos:inScheme ex:scheme ; skos:prefLabel "Concept {i}"@en .\n')
for p in range(P):
for k in range(K):
out.write(f'ex:k{p}_{k} a skos:Concept ; skos:prefLabel "Child {p} {k}"@en ; skos:broader ex:c{p} .\n')
ctx = {"skos": "http://www.w3.org/2004/02/skos/core#", "ex": "http://example.org/"}
query = {
"@context": ctx,
"select": ["?c", "?child"],
"where": [
["values", ["?c", [{"@id": f"ex:c{i}"} for i in range(N)]]],
["optional", {"@id": "?child", "skos:broader": "?c"}],
],
}
with open("4-values-reverse-optional.json", "w") as out:
json.dump(query, out)Comparison queries
2-inner-join.json
{"@context":{"skos":"http://www.w3.org/2004/02/skos/core#","ex":"http://example.org/"},"select":["?c","?child"],"where":[{"@id":"?c","skos:inScheme":{"@id":"ex:scheme"}},{"@id":"?child","skos:broader":"?c"}]}3-forward-optional.json
{"@context":{"skos":"http://www.w3.org/2004/02/skos/core#","ex":"http://example.org/"},"select":["?c","?pref"],"where":[{"@id":"?c","skos:inScheme":{"@id":"ex:scheme"}},["optional",{"@id":"?c","skos:prefLabel":"?pref"}]]}4-values-reverse-optional.json is written by gen.py (20,000 IRIs in a values clause).
5-sparql-reverse-optional.rq
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
SELECT ?c ?child WHERE { ?c skos:inScheme <http://example.org/scheme> OPTIONAL { ?child skos:broader ?c } }
Activity
aaj3f commentedon Oct 1, 2026
Thanks for the really thorough write-up here, @arnaud-fluree. This ended up explaining a slowdown the solo validation hit on an update (a
DELETE … WHERE { … OPTIONAL { ?c schema:subjectOf ?s } }taking ~13 s on 4.2.2 vs ~0 s on the earlier build), so I had Claude dig into how the two relate. Pasting the findings mostly as-is, since I think they add one thing the issue doesn't have yet:#1967 widened this from fresh loads to the normal long-running-server state. Your repro restarts the server before each run, which is the state where every build is slow, the build before #1967 included. But on a server that has written and then adopted an index (the usual steady state), the build before #1967 was fast and main isn't:
schema:subjectOflinks)ffeeec554ba984c7f561b836e9aThe mechanism, as far as we can tell (from the diff plus debug traces of the scans, not a full bisect):
PatternOptionalBuilder::substitute_pattern(optional.rs) fills in?swhen it arrives as a decodedSid, but leaves it a variable when it arrives still encoded (EncodedSid) in the object position. So the OPTIONAL becomes a single scan of the whole predicate, cached under a key every row shares, and each row compares against all of it: rows × triples of the predicate, which matches the quadratic CPU you measured. Whether?sarrives encoded is decided inbinary_scan.rs. Before #1967 the rule was "overlay epoch == 0", so a server handle that had written and then adopted an index got decoded values and the fast lookup.00920483c(#1967) changed it to "no live novelty", which I think is the right rule; it just routes those handles into the gap you found.FLUREE_DISABLE_QUERY_FAST_PATHS=1doesn't change anything, so this is the generic OPTIONAL operator, not a fast path.One trap worth flagging on the fix: substituting the encoded
?salone isn't enough. The OPTIONAL's scan cache key has to include the substituted id too; otherwise the first row's results get handed to every row, which trades slow results for wrong ones. A batched object-keyed probe (mirroringbatched_subject_probe_binary) is probably the nicer shape. It also looks like #1320 is the same gap on theEXISTSside.I'm putting up a PR for this shortly and will link it here. Happy to fold in anything you've already tried on your side.
fix(query): OPTIONAL binds encoded values into every position of its …
perf(query): size OPTIONAL's per-row output batches to their rows