Skip to content

OPTIONAL with a left-bound variable in object position: quadratic CPU and ~170 KB of memory per required row (OOM) #1973

Closed

Description

@arnaud-fluree

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/db rev ffeeec554 (the revision pinned by solo 9fdbb65f1a);
    fluree-db-query/src/optional.rs is identical at ac1e8a61b.
  • fluree-ai standalone 0.10.0-dev.41+g9fdbb65f1, release-fast profile, 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.json

The 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_batch needs a subject column), so the operator takes the
    per-row path;
  • the substituted pattern is ?child skos:broader ?c with nothing bound, i.e. the whole predicate;
  • cache_key gives every row the same key (the u token), so the scan runs once, but each
    required row receives a deep clone of the whole result ((**cached).clone()) and unify_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

  1. In substitute_pattern, resolve Binding::EncodedSid in object position to Term::Iri, the way
    the subject arm does, and key it in push_cache_key_component accordingly (today only the
    subject slot is keyed by s_id). The doc comment of object_var_shared_with_required already
    notes that this slot is left free; the cost of leaving it free is what this report adds.
  2. In next_batch, keep accumulating across required rows until batch_size is 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.
  3. 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_BYTES accounting in context.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.

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

  1. added
    bug
    area:query
    performance
    on Sep 28, 2026
  2. aaj3f commented on Oct 1, 2026

    @aaj3f
    Contributor

    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:

    State (≈1M triples, 3.2k required rows, 23k schema:subjectOf links) main before #1967 ffeeec554 4.2.2 ba984c7f5 main 61b836e9a
    server, index adopted after a write: SELECT with OPTIONAL 0.018 s 1.160 s 1.185 s
    same state: UPDATE with that OPTIONAL in its WHERE 0.032 s 1.141 s 1.153 s
    server, indexed, no write since load (your repro's state) 1.18 s 1.19 s 1.16 s
    novelty pending 0.026 s 0.017 s 0.019 s

    The 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 ?s when it arrives as a decoded Sid, 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 ?s arrives encoded is decided in binary_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=1 doesn't change anything, so this is the generic OPTIONAL operator, not a fast path.

    One trap worth flagging on the fix: substituting the encoded ?s alone 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 (mirroring batched_subject_probe_binary) is probably the nicer shape. It also looks like #1320 is the same gap on the EXISTS side.

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:querybugperformance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions