← Back to Pull requests

perf(core): index exact named graph lookups #7376

Closed
unknown closed this pull request without merging on Nov 13, 2026 13:45 UTC
View on GitHub
unknown unknown commented on Nov 13, 2026 11:59 UTC
Author

<!-- claude-projects-attribution: {"github_login":"jeswr"} -->
_Requested by Jesse · project thread_

Addresses #7188.
Addresses #7370.

Change and design

Resolving a graph by its exact name used to scan the named-graph Vec. That happened in core, in constant GRAPH evaluation, in scoped forks and in durable effect application. This PR adds a shared in-memory exact-name index. Those paths, dataset-clause selection and the capability callers that do the same lookup now go through it.

  • The Vec stays private and keeps its dataset iteration order. A separate hash table stores positions and compares the name terms the Vec already holds, so no extra owned name keys are stored. Declared durable slot IDs stay separate from positions.

  • Exact access returns the first of any duplicates. Scoped forks include every selected duplicate in the original dataset order, and requested positions are sorted and deduplicated before the fork is built.

  • Appends update the index incrementally. A single removal deletes or promotes the matching entry and shifts later positions in place, so surviving entries are neither reallocated nor rehashed.

  • - Removal still does linear work to shift Vec members and index positions. This PR doesn't claim deletion is independent of graph count.
    - Single removals keep the table's capacity. Bulk membership rebuilds and drop-all can release it, and heap_bytes counts retained capacity.
  • Forks and opens build their own matching indexes, and compression and default replacement carry the index across. Replay uses the same membership helpers. Every membership change updates the exact index before any later step that can fail. The separate prefix index is unchanged.

  • Internal test fixtures use private helpers to attach and detach children. External callers already can't change the Vec, so updating the index eagerly needs no lazy validation and no change to field visibility.

  • heap_bytes counts the hash table and any duplicate-position allocations. The index lives only in memory, so the storage format, declared-slot behaviour and persistence ordering are unchanged.

  • named_graph_index(&name) is now public for positional writes, and the data-format and query skills explain when a position goes stale. Graph and GraphSnapshot don't implement Clone, so clone coverage uses shared snapshot ownership and independent forks.
  • Tests

  • named_index_matches_vec_operations: runs random operations from a fixed seed and compares each step against an independent Vec model. It checks indexed positions, first-match references, full ordered contents and prefix results.

  • - Operations: add, ensure, replace, remove/drop, retain, take/extend, clear, compression, default replacement and rebuild, vacuum, forks, scoped forks and shared snapshot clones.
    - Inputs include duplicate names and different term kinds.
  • named_index_survives_save_replay_and_rewrites: runs durable operations from a fixed seed and checks the ordered state at each stage.

  • - Stages: save/open, journal replay of committed but unmaterialized creates and drops in read-only and writable opens, per-slot WAL replay, clear, compaction, vacuum, and snapshot and scoped forks.
    - It also checks that surviving members keep their declared slots across ordinary creates and drops.
  • removal_preserves_duplicate_order_and_term_identity: checks specific removal cases: duplicate promotion, deleting a non-first duplicate, shifted positions, deleting the tail, removing down to empty, and appending again.

  • - An IRI, a blank node and a literal share the same lexical text, and each must still resolve to its own entry.
    - After each step, scoped selection checks every remaining duplicate and its contents.
  • exact_lookup_work_is_bounded: a test-only comparison probe checks that hits, misses, existing ensure and scoped selection stay bounded as the population grows. Hit paths must record index work, so a fallback that skips the probe fails too. The test also checks that heap_bytes includes the index.

  • pop_named is compiled only with mmap, the feature its fixture callers need. This avoids an unused-helper warning in test builds without mmap.
  • Mutation evidence

    Each mutation below compiled, failed the named assertion and was restored. The index tests passed again after each restore.

  • Shift a surviving first position too far in NamedIndex::remove by adding an extra decrement after the normal shift:
  •   + positions.first = positions.first.saturating_sub(usize::from(true));
      

    removal_preserves_duplicate_order_and_term_identity fails indexed-position equality for a survivor.

  • Leave a deleted non-first duplicate in its positions list:
  •   - positions.duplicates.retain(|p| *p != i);
      + positions.duplicates.retain(|_| true);
      

    The removal test fails ordered membership and contents equality in scoped selection.

  • After promoting a duplicate, add:
  •   + positions.first = positions.first.saturating_sub(usize::from(true));
      

    The removal test fails indexed-position equality.

  • Build a fork with an empty index:
  •   - named_index: named_index::NamedIndex::from_named(&named),
      + named_index: named_index::NamedIndex::default(),
      

    named_index_matches_vec_operations fails indexed-position equality.

  • Skip index maintenance during read-only replay:
  •   - self.push_named(name, sub);
      + self.named.push((name, sub));
      

    named_index_survives_save_replay_and_rewrites fails indexed-position equality.

  • Restore the original linear lookup:
  •   - self.named_index.positions(&self.named, name).map(|p| p.first)
      + self.named.iter().position(|(n, _)| n == name)
      

    exact_lookup_work_is_bounded fails exact lookup must not scan named graphs. An instrumented linear scan fails the same assertion.

  • Replace indexed scoped selection with the original Vec scan, dropping the indexed selection code above it:
  •   - self.fork_with_named(selected.into_iter().map(|i| &self.named[i]))
      + self.fork_with_named(self.named.iter().filter(|(name, _)| names.contains(name)))
      

    The bounded-work test fails scoped selection must not scan named graphs.

  • Remove the named_index.heap_bytes() contribution. The bounded-work test fails account for the exact index allocation equality.
  • Base gate (always required)

    Rerun after the review fixes:

  • cargo test -p sparq-core, --no-default-features, and --features mmap,dict-spill: PASS. These include the crash, fault, journal, corruption and byte-identity suites.

  • cargo test -p sparq-engine and default cargo test -p sparq-lws-core: PASS.

  • cargo clippy --workspace --exclude sparq-py --all-targets -- -D warnings: PASS.

  • Strict all-feature rustdoc for core and engine: PASS.

  • python3 scripts/preflight.py, changed-markdown lint, and git diff --check: PASS.

  • cargo build --workspace was not run. Crate-scoped builds and workspace clippy were run instead.
  • Targeted re-evaluation (check the rows that apply to your change)

  • Pinned W3C SPARQL conformance runner and committed ratchet: PASS.

  • Feature-executor check and explicit durable-property test listing: PASS.

  • Wasm dependency guard, shipping release-wasm build, and deterministic byte ratchets: PASS.

  • Rebuilt shipping release CLI and bench, and operator coverage in count, materialize and JSON modes: PASS with no query error rows.

  • From the first pass, before the review: conformance, Solid and MCP default suites; Solid with odrl-bridge,trust-graph; MCP with solid; LWS with no default features and with http-sparq; strict rustdoc for the other changed crates. All PASS.

  • Plain cargo test -p sparq-zk is blocked locally at the live external-compiler cross-check, because the compiler's dependency cache can't be locked on a read-only home filesystem. The Rust suite passed with the existing missing-toolchain declaration and the named skip shown. That skip doesn't count as a pass for the live check. No gate source was changed.

  • Fresh-process microbench and the sequential HTTP create harness: completed. The HTTP run passed its restart and recovered-content checks. Results are kept out of the repository.
  • Ratchets and conventions

  • No floors changed.

  • Follow-ups (no bead tool in this environment):

  • - The separate decoded update Dataset still does its own name lookup.
    - The existing parent-state and checkpoint work under the linked durable-create issue is separate from Graph exact-name resolution.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01JLKBH5gHei9rJAmvhNgZyi

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: jeswr Review duration: 106m
    All Vouch review confidence checks passed
    Residual risk 0.23 = Change Risk (0.57) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.57 · 650 lines diff across 8 files
    0.57
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #7376"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 57% (MEDIUM) · Higher = larger blast radius
    57%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%