Skip to content

ui-server: a provider-restricted turn rebuilds its private index on every turn (28–36 s) #2833

Closed

Description

@schlessera

Context

Under a provider rule that hides folders from the turn's recipient, every hosted turn builds its own private search index from scratch before the provider sees a byte. A warm follow-up pays the same price as the first turn.

Measured on the native hosted fixture (UID 1000, Btrfs loop store, 2,000 notes of 16 KiB, offline fake providers), 10 sessions × first and warm turn per cell. Policy: me/** hidden by path and type private (vault/) hidden by type, from the proven anthropic recipient. Median / p95, ms:

Claude first Claude warm pi first pi warm
private index build 35,488 / 37,505 35,318 / 36,797 27,826 / 34,614 30,427 / 34,810
taxonomy CLI + stray-type scan 409 / 495 396 / 472 353 / 406 357 / 395
hardlink scan 0 0 0 0
whole admission 36,334 / 38,425 36,262 / 37,750 28,540 / 35,654 31,234 / 35,676
pre-provider total 37.1 s / 39.1 s 36.9 s / 38.5 s 30.0 s / 37.3 s 32.4 s / 37.2 s

The same turn without the policy adds 0.75 s (Claude) and 1.45 s (pi) before the provider. The private index is therefore ~95 % of a restricted turn's overhead. Host load average was 6–8 on 32 cores during these cells; the build is CPU- and I/O-bound, so a quieter host would be faster but would not change its share.

Where it happens, verified on af6300478:

  • Admission builds it for every masked turn (buildPrivateIndex({, packages/ui-server/src/brain/governed-turn.ts:219), into a fresh directory (createPrivateIndexDirectory();, line 218), discarded when the turn ends (discardPrivateIndex(); } finally { hold.release, line 256).
  • The build (export async function buildPrivateIndex, packages/ui-server/src/brain/private-index.ts:105) runs the brain CLI's index over the masked startup view in a strict worker (export async function runMaskedBrainCli, line 63), bounded by PRIVATE_INDEX_BUILD_MS = 120_000 (line 25). It indexes the whole visible brain each time.
  • The taxonomy read and stray-type scan before it (export async function readProviderTaxonomy, packages/ui-server/src/brain/provider-types.ts:35; const strays = strayTypedDocuments(, line 121).

The worker launch inside the build is synchronous on the event loop (#2790), so the build also blocks health and WebSocket traffic for part of each turn (#2416).

Scope

Reuse the private index across turns, or update it incrementally, so that a warm restricted turn does not re-index the brain. Target: a warm provider-restricted turn adds under 1 s over the same turn without the policy, on the native fixture. Implement the approved checkpoint-bound option C below; the existing prompt supplies design inputs subject to that ruling.

Out of scope

Acceptance criteria

  • Reuse is bound to exact source/final startup-view identities and canonical brain/policy/effective-mask/recipient identity; incomplete change evidence rebuilds safely rather than serving stale state.
  • Worker writes cannot modify the reusable base or another turn index; eviction, restart, missing checkpoint and interrupted update safely rebuild without authoritative data loss.
  • Tests cover newly masked prior text remaining in free pages, FTS structures or WAL, not just query results; unsafe transitions use a clean masked build unless physical byte non-disclosure is proved.
  • Cache/checkpoint retention is bounded and cleaned under existing native storage guarantees; first/invalidated build costs and fresh-build equivalence are recorded, without weakening the warm-turn target.
  • On the native hosted fixture with the policy above, a warm provider-restricted turn's pre-provider overhead is within 1 s of the same cell without the policy (median of 10 warm turns), for both Claude and pi.
  • A document added, changed or removed between two turns, inside or outside a masked folder, is reflected in the next turn's private index exactly as a fresh build would reflect it, proven by a test that compares the reused or updated index with a fresh build.
  • A masked document never appears in the reused index, including after it moves into or out of a masked folder between turns and after a policy change, proven by tests that fail if the reused index is served stale.
  • A policy or recipient change invalidates any reused index.

Verification

Reproduction: run the native hosted proof (bun scripts/prove-native-host.ts --backend=claude --app-uid=1000, and the pi cell, under the exclusive native fixture lock) with a test that writes the policy above, a brain.config.ts taxonomy defining private: { dir: "vault" }, me/ and vault/ documents, and runs first and warm turns in fresh sessions. Time admission from the hosted governedTurns.begin boundary and the private-index build around buildPrivateIndex. Raw per-phase timelines from the measurement run are retained locally by the maintainer.

Then bun run test packages/ui-server packages/ui-sdk.

Contract impact

None expected; a design that changes what the CLI's index writes would need a check against docs/integration-contract/cli.md.

Part of #1668. Event-loop impact: #2416, #2790.

Maintainer decision (2026-10-24)

Option C selected: use a host-owned private-index cache bound to an exact source checkpoint, then reconcile against the exact next admission startup-view diff. Cache identity includes the canonical brain, exact policy, effective masks and proven recipient; timestamps alone or an incomplete journal change list do not prove freshness.

Before exposing an index, establish a complete reconciliation to the final startup view used for that admission. Policy, recipient, effective taxonomy/masks or indexing semantics changes invalidate reuse. If a complete safe transition cannot be proven, rebuild cleanly from the masked view rather than serving a stale index; refusal remains available when no safe index can be supplied under admission policy. No relaxed consistency or latency-bound increase is approved.

Keep the reusable cache host-owned and outside worker write authority. A turn must not poison future reuse; preserve existing turn-local indexing behavior through isolation from the reusable base. Retain exact checkpoint identity for as long as a diff needs it, and integrate cache/checkpoint ownership, bounded storage and cleanup with existing native managed-storage guarantees. Lost state only costs a rebuild; brain.db remains disposable.

A move into a masked folder or any transition that might retain newly forbidden text requires a clean build unless physical byte non-disclosure is proved. Deleting SQLite rows alone is not sufficient: free pages, FTS structures, WAL and other index artifacts must not expose restricted text. Compare updated indexes against a fresh-build oracle and separately prove physical non-disclosure.

Update the G2 decision record and applicable package contract documentation during implementation. No new extension seam, background daemon or source-of-truth store is introduced. First/startup/invalidated-build cost must be reported; the existing warm-turn target remains binding.

2026-10-24 maintainer ruling: selected C with exact-checkpoint freshness, policy/mask/recipient isolation and safe clean-rebuild fallback. This is architecture approval, not an implemented cache or runtime performance receipt.

Activity

  1. added this to the 0.44.0 milestone on Oct 24, 2026
  2. added
    type: fix
    area: ui-server
    priority: p1
    needs: design
    on Oct 24, 2026
  3. schlessera commented on Oct 24, 2026

    @schlessera
    OwnerAuthor

    Design needed: how a restricted turn's private index survives across turns.

    Decided: a masked turn searches an index built only from what its recipient may see (#1668, #2692, #2725), and today that index is rebuilt from scratch on every turn (28–36 s on the native fixture). Still open: which cache or update shape keeps the "never stale, never leaky" guarantee while a warm turn pays under 1 s. The code cannot decide that; it depends on what the masking model may trust between turns.

    You are designing a change for brain-kit (Bun/TypeScript monorepo). Do not write code; produce a design.
    
    Read first
    - The issue this prompt is attached to (measurements, citations, acceptance criteria).
    - Epic #1668 and its closed children #2690–#2700, #2718, #2726, #2797 for the masking model.
    - packages/ui-server/src/brain/governed-turn.ts:219 (buildPrivateIndex call), :218 (fresh directory), :256 (discard at turn end).
    - packages/ui-server/src/brain/private-index.ts:63 (runMaskedBrainCli) and :105 (buildPrivateIndex).
    - packages/ui-server/src/brain/provider-types.ts:35 and :121 (taxonomy read, stray-type scan).
    - packages/ui-server/src/brain/turn-journal.ts:202 (the journal observation that already knows which paths changed in each turn).
    - docs/decisions/ records on provider masks and generated-text caches (search for #2692 and #2725).
    - AGENTS.md "Markdown is the source of truth; brain.db is disposable".
    
    The problem
    Under `providers: [{ paths: [me/**], allow: [google] }, { types: [private], allow: [google] }]` with recipient anthropic, every hosted turn re-indexes the whole visible brain (2,000 notes) into a new directory, then deletes it. Warm turns cost the same as first turns.
    
    Design: answer each
    1. Which of these, or what better shape:
       A. Cache the private index per (policy hash, masked folder set, recipient) on host storage the worker cannot write, and update it incrementally before each turn from the paths changed since the last build (journal changes, a checkpoint diff, or index mtimes).
       B. Keep one masked index per active mask set up to date in the existing post-turn automatic index refresh, off the turn path, so admission only verifies freshness.
       C. Build once per server start and policy change, then patch per turn from the startup checkpoint's diff against the cached build's checkpoint.
    2. How freshness is proven at admission: what identity (checkpoint id, content hash, generation) ties the cached index to the startup view the turn runs on, and what happens when it cannot be proven (rebuild, or refuse).
    3. How invalidation works on policy change, recipient change, taxonomy change (a type moving folders), and a document moving into or out of a masked folder.
    4. Where the cache lives, who may write it, and how it is cleaned up; its size bound.
    5. What the first restricted turn after start costs, and whether it may build in the background before any restricted turn arrives.
    
    Requirements to hold
    - A masked document, or generated text derived from one (#2692, #2725), never appears in any index the denied worker can read, including transiently during an update.
    - brain.db stays disposable: losing the cache costs only a rebuild.
    - The worker gets the index read-only; it cannot poison the next turn's cache.
    - No new extension seam (docs/extending/README.md).
    - Target: a warm restricted turn adds under 1 s over the unrestricted turn.
    
    Deliverable
    A short design note: the chosen option and why the others lose, the freshness proof, the invalidation table, the expected first and warm turn cost, and the tests that would fail if the cache were stale or leaky. A documented "rebuild per turn is required, and here is why" is an acceptable outcome if no option keeps the guarantee.
    
  4. added
    needs: decision
    and removed
    needs: design
    on Oct 24, 2026
  5. schlessera commented on Oct 24, 2026

    @schlessera
    OwnerAuthor

    2026-10-24 triage at main 77f35ef1ba34e4fab7092ada5362ae799852ea24: Classified the remaining private-index lifecycle question as needs: decision. Folded exact options, consequences, recommendations and ruling evidence into the body while preserving the existing technical prompt and measured targets. No option, consistency relaxation, threshold change or new runtime result is approved.

  6. schlessera commented on Oct 24, 2026

    @schlessera
    OwnerAuthor

    Decision (maintainer, 2026-10-24): Option C. Use a host-owned cache bound to an exact source checkpoint, reconciled through a complete diff to the next admission startup view, with exact policy/masks/recipient identity. Rebuild cleanly whenever safe reconciliation cannot be proved; never serve stale or masked text. Row deletion alone is insufficient because restricted bytes can remain in SQLite free pages, search structures and WAL. Keep the reusable base outside worker write authority, integrate bounded checkpoint/cache retention and cleanup, and preserve the existing warm-turn target and disposable-index rule. The body now records the chosen architecture, safety fallback and proof criteria; implementation and performance evidence remain outstanding.

  7. added
    agent-ready
    and removed
    needs: decision
    on Oct 24, 2026
  8. self-assigned this
    on Oct 24, 2026
  9. schlessera commented on Oct 24, 2026

    @schlessera
    OwnerAuthor

    Claim c2833-a7f1: implementing option C on branch fix/2833-private-index-cache-044.

  10. schlessera commented on Oct 24, 2026

    @schlessera
    OwnerAuthor

    Progress and a question that needs a maintainer ruling (claim c2833-a7f1, draft PR #2847).

    Implemented (option C): a host-owned base per exact brain / policy hash / masked folders / proven recipient / mask paths / build command, bound to the native checkpoint it was built from and reconciled to each turn's final startup view through the complete --no-data send delta. Unchanged view → copy of the base. Only new .md/asset files outside the masks → the CLI's incremental brain index on the turn's copy (must report nothing updated or deleted), which becomes the next base. Anything else (a change, removal, move into a masked folder, second name, permission/ACL change, unreadable delta, tampered base) → a clean masked build. Physical non-disclosure is tested byte by byte (free pages, FTS segments, WAL); 22 mutations recorded in the PR.

    Measured on the native fixture (issue's policy and harness, UID 1000, 2,000 × 16 KiB, warm pre-provider median, Δ over the same cell without the policy):

    before after, harness as-is after, turns that add no note
    Claude +34.6 s +1.41 s +0.55 s
    pi +36.3 s +1.90 s +0.69 s

    The harness's fake turn writes a new note every turn, so every warm turn takes the incremental path: the brain's own brain index re-hashes the corpus (≈0.35 s) and recomputes the graph (≈0.55 s) on the turn path, ≈1.1–1.5 s in total. Over an unchanged brain the 1 s target holds for both backends; after a turn that added notes it does not. First/invalidated builds are unchanged (≈37 s, plus a ≤0.35 s copy into the base).

    Question: which applies to the acceptance criterion "a warm provider-restricted turn's pre-provider overhead is within 1 s"?

    • A. Accept it for warm turns over an unchanged brain, and record the incremental cost after new notes (≈1.1–1.5 s on this fixture). PR fix(ui-server): reuse a restricted turn's private index across turns #2847 can then close the issue as is.
    • B. Approve advancing a base off the turn path, right after the existing post-turn index refresh (bind it to a fresh checkpoint and apply the additions there), so the next admission usually finds it unchanged. This moves work toward option B's placement, which the ruling did not select.
    • C. A core change so the private index's incremental pass can skip or defer the graph precompute and full re-hash (a CLI contract addition), then re-measure.

    Recommendation: A now, with B or C as a follow-up if captures-between-turns latency matters in practice. Approval is the maintainer's; until then the PR stays a draft with Refs #2833.

  11. added
    needs: decision
    and removed
    agent-ready
    on Oct 24, 2026
  12. removed their assignment
    on Oct 24, 2026
  13. schlessera commented on Oct 24, 2026

    @schlessera
    OwnerAuthor

    Maintainer ruling (2026-10-24): option B. Advance the cached base after the post-turn refresh, off the turn path, so that the next warm turn starts from an up-to-date base, including after a turn that added notes. #2847 (merged) is the first step. Option C's safety rules still apply: an advanced base must be bound to the exact checkpoint it reflects, with policy, mask and recipient identity; it falls back to a clean rebuild whenever reconciliation can't be proved; and it never serves stale or masked text. The target remains under 1 s for a warm turn.

  14. added
    agent-ready
    and removed
    needs: decision
    on Oct 24, 2026
  15. self-assigned this
    on Oct 24, 2026
  16. schlessera commented on Oct 24, 2026

    @schlessera
    OwnerAuthor

    Claim c2833-b2e4: implementing the option B ruling on branch fix/2833-advance-private-index-044 (draft #2856).

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

Metadata

Metadata

Assignees

Labels

agent-readyarea: ui-serverpriority: p1type: fix

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions