Skip to content

Managed refresh releases its lock before draining the stale-link backlog, and reports phase times (GST-3107) - #9746

Merged
capy-ai[bot] merged 1055 commits into
masterfrom
fix/refresh-link-backlog-after-lock
Nov 19, 2026
Merged

capy-ai[bot] merged 1055 commits into
masterfrom
fix/refresh-link-backlog-after-lock

Conversation

@garrytan

@garrytan garrytan commented Nov 18, 2026 •

Copy link
Copy Markdown
Owner

A managed gbrain sources refresh that brings in a few files now holds the checkout's refresh lock for about a second instead of minutes, and --json reports where the run's time went.
The time was going to the sync's link derivation: after the import, it derived up to 1,000 pages of the source's stale-link backlog while the refresh still held the lock, so other refreshes of the checkout failed with refresh_in_progress.
Nothing to do: an uncontended run still drains as much backlog as before; the drain just happens after the lock is released. This is not yet shown to be what slows the deployment that prompted it; the new phase_ms output is how we'll find out.

What changed
  • The import's own links under the lock, the backlog after it. Inside a refresh, each member sync's tail derives links only for the pages that sync imported (runSyncTail with deferBacklog, extractManagedStaleLinks with backlog: false). Once every refresh lock is released, the same run spends the rest of the tail's page cap and time budget (1,000 pages and 5 minutes, less what the imports used) on the stale-link backlog (drainSyncTailBacklog). When several member sources drain after the lock, they share one deadline, so a refresh never spends more after-lock time than the tail budget allows. Callers outside a refresh (gbrain sync, the owner's recovery scan) are unchanged.
  • One backlog drain per source. The drain takes a per-source native try-lock (locks/link-backlog-<hash>.lock). A refresh that finds it held skips its own drain and says so in link_backlog (skipped). A drain that throws is reported as failed with its message, and the refresh stays completed.
  • Phase timings. The --json result adds phase_ms (whole milliseconds for fetch, precheck including fetch, drain, merge, sync, tail, backlog; only phases the run reached), lock_held_ms and link_backlog. GBRAIN_DEBUG=1 prints the phase line on stderr. The refresh is a trusted-CLI command (not an MCP operation), so no MCP result changes.
  • Safety of running the drain unlocked. Link derivation never relied on the refresh lock: each page derives in its own transaction, under its page-key locks and with a revision check, and plain gbrain sync already runs the same tail with no refresh lock. Commit-push and concurrent syncs of the source touch git and pages under their own locks. Dirty-file handling is unchanged: the same refresh_dirty refusal and the same preserved_uncommitted list, and nothing dirty is touched.
Measurements (synthetic managed checkout, 4-CPU machine)

Before the change, on Postgres at 3,000 pages, a 3-file refresh took about 4.5 s whether none or thousands of tracked files were dirty, with or without 8,000 ignored files. The dirty set only adds git status time (18 ms to 130 ms). The sync's link step took 2.7 to 3.2 s because it derived 1,000 backlog pages, against 30 to 50 ms with no backlog; PGLite took 7 to 8.5 s. After the change, on the same setup, the lock is held 760 to 830 ms, the in-lock link step takes 40 to 60 ms for the 3 imported pages, and the after-lock drain derives 997 pages, so the backlog shrinks by the same 1,000 per run.

Tests
  • New: test/refresh-link-backlog-gst3107.test.ts, on PGLite and on Postgres through test/e2e/worktree-refresh-postgres.test.ts. With a stale backlog, a 3-file refresh leaves the backlog minus 3 stale under the lock (master: 0 left, since the whole backlog was derived under the lock) and none after it. A refresh started during another's drain completes its import and reports skipped. A failing drain leaves the refresh completed and reports failed. All three fail on master.
  • The existing refresh, tail and link-extraction unit files pass on PGLite (37 files), as do the refresh E2E files on Postgres. One case in worktree-refresh-recovery-postgres (GST-1674, reflog gone) fails here the same way on master.
  • GBRAIN_VERIFY_SKIP_TYPECHECK=1 bun run verify, bun run typecheck, bash scripts/ci-census-tests.sh --run, bun run regen:all and bun run check:public-surface all pass.
Agent notes

GST-3107. worktree-refresh.ts's module-size ceiling rises by 2 lines (1550 to 1552): the refresh-run.ts import, the refreshWorktree entry wrapper that creates the run record, and the drain-phase note must sit in the state machine itself; the record, timedLock, the backlog drain and the report live in refresh-run.ts.

Master (including #9744's precheck retry) is merged in at 4955dd3; the only conflict was the precheck line, where both changes are kept. Our own added and removed lines are unchanged by the merge apart from that line's base context (patch-id cafbe188 at 3c22e0d, 28842985 at 4955dd3, which differs only because #9744 changed that line).

/ship review on 3c22e0d: full pass with no blockers and one docs-wording fix; the second-model review found one blocker (after-lock drains could each take the full budget), fixed by a shared deadline; the range re-read had two informational notes, left open: no dedicated test for the shared deadline, and sequential member drains can starve later members within one run. Adversarial pass: four low notes, left open.

Open in Capy

garrytan and others added 30 commits November 18, 2026 10:28
…ct call

The owner's wider reads (Facts rows as stored on get_page and fetch_page, a
segmented page's markdown view, every take holder for a credential with no
holders list, and graph-hop text) were on wherever a context resolved to the
owner, with each exception switched off by hand; delegated agent jobs were
one nobody had switched off. They are now off by default, and dispatch
switches them on for exactly one case: a direct remote call from an
owner-bound credential speaking for itself with no room declared. Agent jobs,
group chats, stdio, on-behalf-of audiences and attested actors read as before
this change. A census test fails if a second site sets the flag.

An agent job also reads its client's stored takes holders list, read fresh
with the grant, else world takes as before.

Review-Finding: p5/fix-check#1 reader=fix-check
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
…o a brain without the pages refuse

A page rename now moves the places the secret redactor recorded on the page, so purging a page that later
takes the old name no longer deletes the renamed page's originals, and purging the renamed page removes them.
The purge also keeps any place whose page id names a live page outside the purge (rows renamed before this fix).

A backup restore now reports originals whose page is not in this brain as skipped_no_page ("skipped because
their page is not in this brain"), with the next step to sync the pages and run the same restore again. When
every entry is skipped that way it refuses with invalid_params and writes nothing.

Also: the next backup is due for entries sealed while a backup ran (database high-water mark, not the host
clock); a spooled duplicate records its commit places on the existing original so a purge keeps it; a restore
groups occurrences by entry once.

Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/specialist-batched#1 reader=state-machines
Review-Finding: p1/specialist-batched#2 reader=data-migration
Review-Finding: p1/specialist-batched#4 reader=performance
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
A host that restores the thin-client tree without its node_modules got a launcher that passed its runtime check and then failed in Bun's module resolver ("Cannot find package 'js-yaml'"). When the CLI runs from a tree with its own bun.lock and node_modules, the launcher now checks that directory and prints the lockfile restore command (bun install --frozen-lockfile --ignore-scripts in that tree).

Reported by @Kkkkkuro; first fixed by @Masashi-Ono0611 in #9666.

Co-Authored-By: Masashi-Ono0611 <98894508+Masashi-Ono0611@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
A rebuilt brain numbers its pages in another order, so a restored occurrence could name an unrelated page; the purge cascade then kept the original when its real page was purged. Restore now looks the page up by source and slug.

Review-Finding: p2/outside-voice#1 reader=outside-voice
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
…ript changes (#9648)

A oneshot child that decides correctly to write nothing but answers in prose instead of the skip JSON dead-letters under require_writes and releases its key, so every cycle paid for the same transcript again and doctor reported dream_paid_loop. A dead synthesize child that finished cleanly with no page write now counts as settled for that content key; a changed transcript has a new key and is synthesized again.

Reported by @andreineacsu; first fixed by @Masashi-Ono0611 in #9651.

Co-Authored-By: Masashi-Ono0611 <98894508+Masashi-Ono0611@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Known limits from #9707's final review: the room mark is judged with the caller's own fact grant (GST-3066), and owner tokens minted with gbrain auth create store ['world'].

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
A timestamp like 2026-02-30 or 25:61 used to be accepted by the Rust store and stored as written. The store now checks the calendar: the day must exist in its month, hours, minutes and seconds must be in range, and 24:00:00 and a :60 leap second roll over the same way Postgres does. Page dates (effective_date) use the same check.

Review-Finding: specialist-batched#1 reader=specialist-batched
…d) pages

Three writes could leave a segmented page's search text wrong on the Rust store:
- sealChunks accepted a segmented page and replaced the chunks built from its segments. It now refuses (invalid_state), and a page in an archived source is not found, as on Postgres.
- deleteChunks removed the chunks but kept the page's seal, so a later unsealed write was read as current. It now clears the seal.
- createVersion of a segmented page wrote a version with no body and no reference to one. It now refuses with a typed capability_missing instead of writing an empty version. This changes the store's contract on purpose: the old test that pinned a version of a shell page is rewritten to expect the refusal.

Also adds a test that an impossible effective date is refused and writes nothing.

Review-Finding: adversarial-native#2 reader=adversarial-native
Review-Finding: adversarial-native#3 reader=adversarial-native
Review-Finding: adversarial-native#1 reader=adversarial-native
… holds

Creating a segmented page, or moving or reviving one with a new body, skipped the check that two live pages never share one source file. Both paths now run the same check as an ordinary page write and refuse with origin_claimed, as Postgres refuses with its unique index.

Review-Finding: red-team#1 reader=red-team
…EXCLUDE names

The Rust store hid only its built-in prefixes (test/, attachments/, .raw/). Pages under prefixes the operator lists in GBRAIN_SEARCH_EXCLUDE showed up in results. The adapter now passes the same resolved list Postgres uses, and include_slug_prefixes still brings a prefix back.

Review-Finding: outside-voice#1 reader=outside-voice
…it locked

If close() ran while an open() waited in the worker queue, the open finished afterwards and held the brain's lock with no handle to release it. The open now sees the close and refuses with store_closed, so the brain can be opened again.

Review-Finding: outside-voice#3 reader=outside-voice
…d) page

The export read the body of every page as one string, which a segmented page refuses, so it stopped with no manifest. It now skips each segmented page and counts it in the manifest (skipped_pages_segmented).

Review-Finding: outside-voice#4 reader=outside-voice
…s, search excludes, close during open, corpus export)
…er-reads-protected-sections-3058

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

# Conflicts:
#	src/mcp/http-transport.ts
The census shells out to git grep, which made the structural-suite classifier list the whole database suite as structural; on its own file only the census is.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
…d the pages.ts size

verify on the master merge: the test's Postgres arm runs in the Postgres lane, bodyStripsFor (inline pages only) and protectedTakesFilter (body flags on a segmented page) are reviewed body readers, and pages.ts grows 8 lines for the owner option and the room body check.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
… login-shaped word

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
The export holds the full text of a private brain, so it refuses an output
directory inside a git working tree unless --allow-in-repo is passed. The check
read every git error as "outside a repository": an inherited invalid GIT_DIR,
a missing git or unsafe ownership let the export write into a working tree.

Now inherited GIT_* settings are dropped for the probe, only git's own
"not a git repository" answer counts as outside, and any other failure refuses
with the git error and the --allow-in-repo way out.

Red before: with GIT_DIR pointing nowhere, the unfixed exporter passed the
guard and created its output directory inside a git repository.

Review-Finding: targeted#1
…re when only its occurrences change

The page purge cascade (removing a purged page's sealed originals), the rename move of occurrence slugs, the
restore rule that skipped originals whose page is missing, and doctor's count of unreferenced originals move to
their own change (GST-3074). This change now never deletes a secret store row: a restore only adds rows, ties each
restored place to the page that holds its slug now, and never overwrites an existing entry.

The backup is now due when only occurrences changed, for example a new page that uses an existing secret.

Review-Finding: p4/outside-voice#3 reader=outside-voice
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
…, and honour embedding_disabled on every embedding route (#9653, #9715)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
The serve deferred-embed drain now treats a brain whose database row disables embedding as keyless instead of retrying a refused embed forever.

Review-Finding: p1/red-team#1 reader=red-team
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
… to, and never make a key

A backup reads every entry and occurrence in one statement, so a row sealed mid-backup is in
neither list. The backup status records the backend's identity (kind, bucket, host or path,
never credentials); a different backend, or a drifted entry or occurrence count, makes the
backup due, and doctor no longer reports a backend it never wrote to as backed up. Backups seal
only under an existing key: a keyless host refuses with secret_store_key_missing, maintenance
skips, and doctor says why.

Review-Fix: p5/outside-voice#1
Review-Fix: p5/outside-voice#2
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
…t wins on reconcile; refuse a symlinked decision path

- One check decides whether a decision may be written into the default source's repository: no member in an
  owner-only source (archived ones included) or in a source that no longer exists, and no member page outside the
  default source that not every reader of it may read (readable_by, a folder rule or a private label). Record,
  reconcile, doctor's drift count and the bulk confirm list all use it, so an archived owner-only source no longer
  lets reconcile push its slugs, and one such group no longer wedges confirm --clean.
- confirm --join refuses (dedupe_group_not_confirmable, reason rejected_pair) when the joined identity would hold two
  pages recorded as different people.
- Decision files are written with O_NOFOLLOW after checking that .gbrain, .gbrain/identity and the file are a real
  folder and file; a symlink there is refused with commit_paths_invalid and nothing is written through it.
- reconcile never rewrites a committed decision file from the database: git wins, the projection gives the row the
  file's verdict, and git_kept names the decisions whose row disagreed.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
… engine method

The fix round's restricted-page query ran raw SQL from src/core/entities/identity-decisions.ts, which the
engine raw-SQL ratchet refuses. listRestrictedIdentityMembers now holds it in engine-sql/identity-decisions.ts,
with both engines delegating. It binds the member arrays through sqlFragment and splices the vetted
privatePagesFilterFragment('p'), which is the same text as readPolicyFragment('p', [], true), so behaviour
is unchanged. Module-size ceilings, the Rust members map, the coverage lists and the SQL-text classification
golden are updated, and the engine parity test pins the new method.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
garrytan and others added 23 commits November 19, 2026 06:23
… slug go with the page, a restore adds an existing entry's missing occurrences, and the cascade locks entries before deleting them

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
…tore-cascade

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

# Conflicts:
#	test/publish-redact-unpushed-gst2988.test.ts
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/specialist-batched#1 reader=security
Review-Finding: p1/red-team#2 reader=red-team
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
…send-keyed-hash

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

# Conflicts:
#	scripts/postgres-arm-weights.json
…bench-baseline-postgres-import

# Conflicts:
#	rust/bench/baseline/baseline.test.ts
…eps every recorded occurrence

Review round 1 on the purge cascade: a sync rename that falls back to a new row now moves the stale row's
occurrences to the new row, so expiring the stale row keeps the original its marker names. A restore compares every
recorded field before skipping an occurrence, reports a value held under another id as held rather than as a missing
page, and a rename makes the next backup due.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
…lug, and how to check

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
… page renamed earlier restores

A place recorded before occurrences moved with their page can carry a slug the page had before an older rename. The
backup now writes the slug of the page its page_id names, so a restore into a rebuilt brain finds that page instead of
skipping the original.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
An occurrence another page holds under an older slug (left by a rename before occurrences moved with their page) now
stays with that page when a different page that took the slug is renamed, so the new slug's readers do not pass the
reveal check for it.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

# Conflicts:
#	src/core/persistence/worktree-refresh.ts
…bench-baseline-postgres-import

# Conflicts:
#	rust/bench/baseline/baseline.test.ts
… the shared-source tables

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
@capy-ai
capy-ai Bot marked this pull request as ready for review November 19, 2026 08:25
@capy-ai capy-ai Bot added the full-ci Maintainer-only: run the full Test and E2E suite on this PR head label Nov 19, 2026
@github-actions github-actions Bot removed the full-ci Maintainer-only: run the full Test and E2E suite on this PR head label Nov 19, 2026
@capy-ai
capy-ai Bot merged commit 698a35c into master Nov 19, 2026
234 checks passed
@garrytan garrytan mentioned this pull request Nov 19, 2026
capy-ai Bot added a commit that referenced this pull request Nov 19, 2026
Releases v0.60.744.0 with eight changes since v0.60.743.0, including a security fix: archived sources are now hidden from every API token (#9795).
- Archiving a source now hides its pages from every API token, not just from search (#9795)
- `gbrain sources refresh` no longer stops and asks for the user when a local commit lands while it publishes the checkout's earlier local commits (#9744)
- A managed `gbrain sources refresh` that brings in a few files now holds the checkout's refresh lock for about a second instead of minutes, and reports where its time went (#9746)
- The Mac helper's send log no longer keeps a recipient hash that can be reversed by trying every phone number (#9756)
- The experimental Rust engine's store now serves vector search, embeddings, link and graph reads, takes, salience, stats and the ingest log the way PGLite does, but nothing selects it yet; PGLite and Postgres brains are unchanged (#9759)
- A publish that redacts secrets no longer reports a failure that did not happen, and the secret audit logs are private to their owner (#9790)
- Purging a page now removes the secret store originals only that page held (#9796)
- The bake-off baseline benchmark can run against Postgres on a clean install again (#9758)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Co-authored-by: garrytan <garrytan@gmail.com>
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