Skip to content

Run core thread pin and unpin on the shared tagged-query predictions - #5994

Closed
ymichael wants to merge 2 commits into
mainfrom
bb/prove-5658-core-mutation-keyed-read-on-the-share-thr_xig942tj2w
Closed

ymichael wants to merge 2 commits into
mainfrom
bb/prove-5658-core-mutation-keyed-read-on-the-share-thr_xig942tj2w

Conversation

@ymichael

@ymichael ymichael commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Core didn't use the live-data mechanism behind the plugin hooks from #5658 for its own thread data. That data has dozens of direct cache writers: live status patches, sends, archive and section moves. #5658's predictions (optimistic updates) assumed nothing else writes to the cache. If a status patch landed while a pin was still saving and the save then failed, the rollback left the thread shown as pinned. Core Pin also had two paths with separate optimistic code: the batched plugin-bound SDK, used by the menu, drag-and-drop and Move-to-section, and the usePinThread hooks.

This is a draft for evaluation and is not meant to merge as is. It tests whether core's thread data can run on the shared mechanism.

What changed

  • @bb/query-tags, all general, with nothing core-specific:
    • writes that aren't read receipts are folded into the confirmed data under a prediction;
    • functional setQueryData updaters run on the confirmed data (TaggedQueryClient, used by createAppQueryClient);
    • select observers no longer replace the confirmed data. This fixes a latent Let plugins read and write live data through core's tagged queries #5658 bug that crashed menu Pin once the sidebar was a tagged read;
    • infinite-query receipts, so the archived list is a tagged read and keeps its optimistic pin;
    • caches that no read owns get predictions through a client-level listener;
    • prefix descriptors attach predictions to lists that load while a write is pending;
    • an accepted prediction is refined with the server's value (pinnedAt shows at acknowledgement).
  • One pin implementation: apps/app/src/hooks/mutations/thread-mutation-batcher.ts keeps main's per-thread ordering and whole-batch rollback on runTaggedMutation. The menu, drag-and-drop, Move-to-section and usePinThread/useUnpinThread all go through it. The hooks pass core's toast meta. Deleted: beginPin/UnpinThreadTransaction, applyThreadPinStateResult and the batch transaction's pinnedAt handling.
  • Tagged thread reads: sidebar navigation, thread detail and thread lists. The pin and unpin routes invalidate thread:<id> and thread-lists.
  • Plugin-facing API: unchanged. No query keys or QueryClient are exposed to plugins.

One timing difference from main at ~400 ms latency. On rapid pin/unpin ×5, main replays the sequence after you stop, with two to four extra Pinned/Threads jumps. This branch stays on the last toggle. An earlier version of this description claimed a second difference (Move-to-section where the unpin succeeds and the update fails). It came from a harness that delayed HTTP but not WebSocket frames. With symmetric latency, both builds behave the same.

Acknowledged predictions yield to later writes (ee698dbb75). When a write lands after acknowledgement, such as the pin-order result after a drag-and-drop pin, the acknowledged value is folded into the confirmed data first, so the write takes effect when it arrives. The prediction stays only as a guard over reads that started before the acknowledgement. This fixes a drag-to-Pinned delay at 400 ms (about 450 ms slower than main) that independent verification found.

Network-only side effects:

  • pin-only batches no longer cancel in-flight reads;
  • the pin tags broadcast adds a refetch next to pin-state-changed.

How you verified

  • Existing tests:

    • All pin tests pass unedited, including plugin-bound-sdk.test.ts "moves a pinned thread immediately and reconciles success/failure".
    • One case was removed because its function was deleted: the pin case of "preserves concurrent state on a delayed response". The new test "shows the server's pinnedAt as soon as the pin is acknowledged" replaces it.
    • Mechanical edits only: thread-queries.test.ts (client argument) and query-tags mutation.test.ts (options-object signature).
  • New tests:

    • 47 in @bb/query-tags (cache-writers.test.ts, prediction-lifecycle.test.ts). They cover rollback under status patches, same-field writes, row adds and removes, snapshot restores, select observers, infinite pages, unowned caches and late-loading lists. The rollback and select cases fail without the fix.
    • 6 app-level pin tests on real hooks and writers (thread-pin-mutations.test.tsx).
  • pnpm exec turbo run typecheck lint test --filter='...[origin/main]': 196/196 before a final docs-only edit.

  • Independent verification (a separate thread with its own harness): matches main frame for frame at 0 and 400 ms for menu pin and unpin, failures, every Move-to-section case, a status update mid-save, archived flows, and push-notifications' optimistic level toggle. The drag-to-Pinned delay it found is fixed. After the fix, drop-to-slot takes 822–837 ms vs main's 814–839 ms over 4 runs each.

  • Tests added after verification: "lets a write after acknowledgement replace the acknowledged value" (query-tags), "shows the pinned order written after the pin is acknowledged", and "keeps concurrent thread state when a pin succeeds". The first two fail on the previous head.

  • Side-by-side QA: main and this branch as dev builds, at 0 and ~400 ms added latency, with a per-frame log of every sidebar row's position and status. Identical frame for frame for:

    • menu pin, and a forced failure (rollback plus the "Failed to pin thread" toast);
    • drag-and-drop pin, success and forced failure;
    • Move-to-section success, and failure at 0 ms;
    • a real turn's status update landing mid-save (the row stays pinned);
    • a status update plus a failed unpin (back to Pinned, and keeps "working").

    The only differences are the two timing cases above.

🤖 Generated with Claude Code

AGENT GENERATED

ymichael and others added 2 commits October 20, 2026 23:10
Evidence branch for #5658: every core pin and unpin path now uses the
@bb/query-tags prediction layer that the plugin live-data hooks use.

- Predictions survive core's own cache writers: a setQueryData value is
  rebased onto the confirmed data, and the app's TaggedQueryClient runs
  functional updaters on the confirmed data, so rollback removes only the
  prediction.
- structuralSharing calls for an observer's select output no longer
  overwrite the confirmed data.
- Prefix descriptors predict on matching queries that load while a write
  is pending; acknowledged results refine the prediction; infinite queries
  are confirmed by a full reread; caches without a tagged read keep their
  writes and settle to the acknowledged value.
- One thread mutation batcher owns pin, unpin and metadata updates for the
  thread action menu, drag and drop, Move to section and the pin hooks,
  keeping main's per-thread ordering and whole-batch rollback. The
  held-patch pin transactions and the server-result pin write are removed.
- Thread detail, thread lists (including the archived infinite list) and
  sidebar navigation are tagged reads; pin and unpin invalidate their tags.

> AGENT GENERATED

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An acknowledged prediction kept overriding later cache writes until a read
started after the acknowledgement landed, so a dragged thread held the top
of Pinned until the refetch instead of moving to its slot when the pin
order result arrived. A write now folds the acknowledged prediction into
the confirmed data first; the prediction is kept only as a guard reapplied
over reads that started before the acknowledgement.

Add tests for a pin followed by a pin-order write and for concurrent
thread state surviving a successful pin. The pin hooks no longer pass a
no-op invalidate, and writes without predictions no longer subscribe to the
query cache.

> AGENT GENERATED

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael marked this pull request as ready for review October 21, 2026 13:06
ymichael added a commit that referenced this pull request Oct 22, 2026
…#6002)

## Human comments

## What was wrong

Core kept a separate copy of each thread in every cache that shows it:
the thread detail, every list variant, the sidebar, search and the
machine preview. Every write had to find and patch each copy by hand
(pending-thread-patches, the list and sidebar mappers, snapshot
restores, the engine's array rebase). Copies the code missed showed
stale state. On main:
- a list loaded during a failed pin stays pinned;
- a sidebar refetch during a pending archive brings the thread back.

Core's thread predictions also didn't share plugins' keyed-row path.

Includes #5994 (core pin and unpin on the shared tagged-query
predictions). Merge this PR alone and close #5994.

## What changed

- **One keyed store in `@bb/query-tags`** (`src/keyed-store.ts):
  - per-client collections of stored rows;
  - ordered prediction layers;
  - the read-start rule;
  - accepted predictions becoming stored values;
  - incremental rebuilds of query views.

`beginOptimisticMutation` takes `optimisticKeyedUpdate(collection, key,
update)` next to `optimisticQueryUpdate`. **Core thread predictions and
plugin `cache.updateKey` both go through it**, and
`createTaggedKeyedQueryOwner` keeps its rows in the same store.
- **Each thread is stored once.** Every list, the sidebar, search and
detail keep their exact shapes, now built from those entries, so
components don't change. `thread-entity-store.ts` holds only the thread
view configuration: facets, membership, `updatedAt` merging and sidebar
insertion.
- **Every thread writer predicts on the entry:**
  - pin, archive, unarchive and delete;
  - rename and metadata, read state;
  - section and parent moves;
  - send status, stop;
  - environment rename, project and section deletion;
  - realtime status.
- **Deleted:**
  - `pending-thread-patches` and `thread-archive-cache`;
- the list and sidebar mappers, snapshot and restore,
`updateCachedThread`;
- `optimisticQueriesUpdate`, the array rebase, the per-path keyed
receipts, infinite receipts and `TaggedQueryClient`.
- **Bundle:** the thread panel query hooks now load with the thread page
instead of at boot.
- **Two plugin keyed-row behaviour changes,** documented in
`docs/api_to_audit.md` and the query-tags README:
- a row that loads while a write is pending now shows the prediction,
the same rule as plain reads and core threads;
- an unsubscribed row whose refresh failed is dropped and read fresh on
resubscribe, instead of keeping its accepted prediction.

  The plugin SDK surface is unchanged.

**Visible changes from main** (frame QA at 0 and 400 ms):
1. **Fixed:** a list that loads after a failed pin no longer shows the
thread pinned.
2. **Fixed:** a sidebar refetch during a pending archive no longer
brings the thread back.
3. Undo after archive: the thread reappears when Undo is clicked,
instead of after the refetch (about 0.8 s sooner at 400 ms).
4. Failed unarchive: the thread reappears, then hides again with the
error toast (about 0.4 s at 400 ms). Main never shows it.
5. Failed send: the row shows the working state until the failure toast
(about 60 ms at 0 ms, about 430 ms at 400 ms). Main shows nothing.
6. Failed environment rename at 0 ms: the predicted name can paint for
one frame (about 17 ms).

## Speed and requests

**Requests per action match main.** Same headless-Chrome script against
`start:worktree` builds of main (`2dc5e37d9e`) and this PR on one data
dir, 3 pin/unpin cycles each:

| Action | main | this PR |
|---|---|---|
| Pin | POST + 2 sidebar GETs | POST + 2 sidebar GETs |
| Unpin | POST + 2 sidebar GETs | POST + 2 sidebar GETs |

#5994 had declared tag invalidations on pin and unpin. The server
broadcast them and the client re-applied them, which added 2 sidebar
reloads per pin. They are removed, together with the thread route tags
that only they used. The server and server contract are now identical to
main, and there is no schema change.

Script time measured earlier on a VACUUM INTO snapshot of a real bb.db
(3,869 threads), at 5 runs, medians, main / this PR at 1×: archive 17.5
/ 16.4 ms, move section 18.9 / 21.8 ms, delete 20.3 / 25.0 ms, undo 11.6
/ 13.0 ms. Click to paint is unchanged (~46 ms), and cold load and
thread switching are at parity.

## How you verified

- `pnpm exec turbo run typecheck lint test
--filter='...@bb/query-tags'`: green (app 6,246, plugin SDK 395).
- Bundle budget: the boot payload is 393.7 KB brotli against the
unchanged 394.4 KB budget.
- `@bb/query-tags/testing` `keyedStoreContract`: one six-case table run
against core thread lists and against the real plugin hooks
(`experimental_useRpcKeyedQuery` plus `experimental_useRpcMutation` with
`updateKey`). Breaking the read-start rule fails both.
- **Frame-by-frame QA against main (b143a22):** 25 scenarios at 0 and
400 ms, including failures: pin, archive, drag-to-Pinned, status
mid-save, every writer above. Everything matches main except the changes
listed above.
- **Real plugin caller:** push-notifications at 400 ms. Muted shows
about 100 ms after the click and holds through acknowledgement, and a
forced failure reverts, the same as main.

Net vs #5994: code +2,302 / −2,341; tests and docs +936 / −291.

- Thread hooks: 358 tests across `src/hooks/mutations`, `cache-owners`,
`queries` and realtime effects pass. The stale-read pin test's fake
writes now return the server's row, as the real pin route does.
- After merging current main: `pnpm exec turbo run typecheck lint
--filter='...[origin/main]'` passes (122 tasks), and the
`@bb/query-tags`, plugin SDK and server-contract tests pass. The plugin
SDK version check reports the surface unchanged. CI runs the full suite.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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