Skip to content

fix(computers): take thread locks in one order to avoid deadlocks - #562

Merged
nixuuu merged 5 commits into
devfrom
fix/thread-move-deadlock
Nov 12, 2026
Merged

nixuuu merged 5 commits into
devfrom
fix/thread-move-deadlock

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

SendMessage can deadlock with a source transaction and deferred range journaling during a linked-computer move. The advisory key in #545 decodes to 1102188573303919923, exactly hashtextextended('canopy.thread_mirror_journal', 0).

The original PostgreSQL wait graph is 105 → 106 (transaction holding the threads row), 106 → 104 (global journal advisory lock), 104 → 105 (KEY SHARE tuple lock queued behind SendMessage). The original log omits the SQL statements for 104 and 106. The regression pins these roles to real commandDone, ingestThread, and SendMessage paths.

The inversion came from #539: thread_replication_enqueue updates the same clock twice for a turn and its thread projection. PostgreSQL rechecks an unchanged FK when the previous row version belongs to the current transaction. That takes a fresh threads KEY SHARE while already holding the global journal lock. SendMessage, ingest and move admission acquire the thread row before their deferred journal.

Migration 0124 inserts an immutable thread_replication_sources row between the clock and threads. Repeated clock updates now check that anchor without locking the execution row. Bootstrap creates it while already holding the thread row. Existing epochs, cursors and journal payloads survive; FK integrity and deletion cascades remain. No retries or weaker execution locks.

Lock rule: source rows precede journal barriers/clocks; deferred journaling takes global journal → per-thread range barrier → clock and must not acquire threads locks there. This is documented in the helper and in Polish in docs/linked-computers.md.

Validation:

  • Deterministic database barriers arrange command completion → ingest → queued SendMessage. The fixed test checks message delivery, the persisted ingest cursor, and publication of the committed notice. A second barrier case overlaps actual range publication, move freezing and SendMessage.
  • The existing move/history/files/old-home redirect/third-computer scenario runs twenty times in CI.
  • The migration upgrade test checks retained journal state and cascading deletion.
  • RED confirmed on the original schema in CI 43189075639, Tests 4/4: the new regression fails with 40P01. PostgreSQL's context shows SELECT 1 FROM ONLY public.threads ... FOR KEY SHARE from the second thread_replication_enqueue(...,'thread',...) clock update, under computer_thread_changed. That run also exposed an old-home mirror cleanup timeout in repetition 3/20 and an unrelated native-interaction fixture timeout; neither is counted as proof of the deadlock. GREEN pending on the fixed head.
  • Full CI covers frozen bun install, gen:check, typecheck, lint, formatting, every check:tmp shard and the web build. Local tests/install/builds were not run because this host is under a performance measurement; only changed-file oxfmt/oxlint ran at nice 19.

Lock audit: thread-row locks in admission/queue/steers, ingest/settle/interactions, lifecycle/moves, bus/worktree/checkout/import and GitHub paths precede their deferred journal triggers. Range publication and client windows share prepareRangeClock. Publication-failure persistence runs after the read transaction ends; cursor/ACK storage locks mirror state rather than source threads. Bot-view, bot-name, GitHub-cache, proxy-migration and index-build advisory locks have different keys and do not match the incident.

Copy audit: no user-facing text changes.

Fixes: #539
Related: #545

@nixuuu
nixuuu force-pushed the fix/thread-move-deadlock branch from cf5757f to a72d1ac Compare November 12, 2026 09:19
@nixuuu
nixuuu marked this pull request as ready for review November 12, 2026 09:31
@nixuuu
nixuuu merged commit 7ef97c1 into dev Nov 12, 2026
23 of 27 checks passed
@nixuuu
nixuuu deleted the fix/thread-move-deadlock branch November 12, 2026 09:51
nixuuu added a commit that referenced this pull request Nov 12, 2026
After cutover, the generic moved-item guard could reject an old home's
final range ACK and every resumed mirror subscription containing that
thread's durable cursor. The third computer then retained the old-home
mirror indefinitely. Keep ThreadMirrorService controls on the original
journal home; normal thread actions still redirect.

Both failed attempts of run 43190996415 failed at the stale-mirror
assertion in `computer-moves.test.ts`: `Expected: 0`, `Received: 1`
(attempt 1: repetition 2/20; attempt 2: 1/20). Both logs show
`AckThreadRange` failing with code 9 followed by repeated
`WatchThreadMirror` failures with code 9. Neither contains `40P01`.
History, file transfer, redirects and the visible new owner had already
passed.

#539 introduced per-thread mirror cursors and durable ACKs into a path
whose generic redirect guard scans request IDs. #562 exposed this
separate race through repetition; it did not introduce it.

Add real linked-gateway regression coverage with an ACK barrier after
durable apply and before source cutover. Cover final ACK/removal,
resumed old cursors, and old-epoch range repair. Keep the existing 20
repetitions unchanged and document journal routing in Polish.

Validation: changed-file oxfmt/oxlint and `git diff --check` passed. No
local tests or builds were run while the host measurement is active.
Remote required checks and two consecutive complete CI passes on the
final head are pending.

Fixes: #539
Related: #562
nixuuu added a commit that referenced this pull request Nov 12, 2026
Bots currently choose permissions when starting threads, and Full access
is downgraded for subagents. New subagents now inherit the parent's
effective permissions, including Full access where the computer allows
it. Bots use the owner's default thread permissions or a per-bot
override; models no longer choose a creation mode.

## Changes

- Add Settings → Threads → Subagents: **Same as parent** by default, or
a fixed mode capped by the parent. Resolve and record the mode in the
gateway creation transaction. Existing children keep their mode;
lowering the parent's default limits new children immediately, and a
running turn's narrower permissions remain a ceiling.
- Default bot thread permissions to **Inherit default**, with all five
explicit overrides. Apply the configured choice to direct starts, forks,
schedules, and linked-computer starts. Remove model-facing creation
parameters; legacy `spawn_thread.permission_mode` can only narrow
access.
- Enforce owner scoping before execution and replay. Persist the
worker's authenticated Full access capability and clamp automated
creation to Full auto where bypass is unavailable. Scheduled new threads
retain their sandbox ceiling. Show clamp explanations and recorded
permissions in web/mobile thread details.
- Add gateway integration coverage for inheritance, parent changes,
fixed settings, escalation, owner scoping, worker ceilings, bot
defaults/overrides, and mode propagation into Codex, Claude, and Grok
native adapters. Add migration coverage and update Polish docs.

## Contracts and migration

Additive protobuf fields only:
`ThreadDefaults.subagent_permission_mode`,
`Thread.permission_mode_note`, and
`NewThreadSchedule.permission_mode_note`; generated code is included.
Worker link protocol is unchanged.

Migration **0125_inherited_access_mode** converts missing/legacy
inherited bot settings to `user_default`, preserving explicit choices,
including Ask first retained by migration 0090. It also includes clamp
explanations in the lightweight thread-settings projection used by lists
and details. Registration and schema expectations are updated.

Rebased onto `origin/dev` at `f7ad51ccc`, including #562 (migration
**0124_thread_range_lock_order**) and #566. This PR adds
**0125_inherited_access_mode**; registration and schema expectations
list 0124 followed by 0125.

Related: #562

Mobile changes are TypeScript/JavaScript only. No dependencies, Expo/EAS
configuration, or native files change.

## Verification

The initial implementation passed local `bun install --frozen-lockfile`,
`bun run gen:check`, `bun run typecheck`, `bun run lint`, `bun run
format:check`, and `git diff --check`. Subsequent fixes use CI logs for
runtime evidence; only `nice -n 19` formatting/lint on changed files and
`git diff --check` run locally while measurement continues. Current-head
CI results are shown by the PR checks.

After the maintainer opened the local verification window, `bun install`
and `bun run gen:check` passed on head
`ef33469656f17e4255f35e519cb1d37e4c9c3ee4`. Focused tests passed: **20
tests, 0 failures, 135 assertions** across `full-access-mode.test.ts`,
`bot-approval-rules.test.ts`, `bot-approval-review.test.ts`, and
`inherited-access-upgrade.test.ts`. The full local `check:tmp` was
intentionally omitted at the maintainer's request because CI runs the
full suite. Web/Linux builds and static checks passed in current-head
CI; other CI results are shown by the PR checks. Adapter coverage feeds
the child mode received over the worker link into native permission
adapters; it does not claim a live provider run.

Real-browser review passed in light and dark at desktop (1280/1440 px)
and phone (390 px) widths: Settings → Threads → Subagents, saved mode
after reload, bot Inherit default and fixed override after
saving/reopening, Full access confirmation, and the child clamp
explanation beside its effective mode. Long project, bot, parent, and
child names wrap or truncate cleanly; no horizontal page overflow. The
dark phone dropdown was checked after transitions settled: its
background is opaque and its copy remains legible. The isolated gateway
used a scripted worker; no live model or external account was contacted.
Review servers and their test database were stopped, and the browser tab
was closed.

Expo/EAS runtime fingerprints generated with `expo-updates
fingerprint:generate` are unchanged against `origin/dev`, using the same
checkout path and dependencies for both snapshots: iOS
`74705db3a68907bc28379bb9b1080a227bc0755b`, Android
`7d38be8f5c9bf842d62060c75820a206f99c87e3`. No native/config/dependency
changes are included.

## Copy audit — docs/copy.md §8

| Before → after | Reason |
| --- | --- |
| “Same as the bot’s approvals” → “Inherit default”; “Uses your default
permissions from Settings → Threads.” | Match the owner's new-thread
default and identify where to change it. |
| No subagent permission control → “Subagents”, “Permissions”, “Same as
parent”; “New subagents keep their mode when the parent’s permissions
change.” / “A fixed mode can limit access, up to the parent’s current
permissions.” | Describe inheritance, persistence, and the fixed-mode
ceiling beside the control. |
| No bot Full access override → “Full access”; “Thread tools run without
asking or a sandbox, where the computer allows it.” | Use the existing
mode name and confirmation; name the computer restriction. |
| No clamp explanation → “This computer limits Full access to Full auto.
Choose another mode or enable Full access on this computer.” / “The
parent’s mode limits subagent permissions. Change permissions in the
parent thread to allow more access.” / “Scheduled threads limit Full
access to Full auto. Keep this mode or choose one that asks.” | State
the effective limit and a next action; show it with the saved mode in
thread details. |
| Schedule standing-rule labels mentioning Ask first/Read only →
“creating schedules” / “updating schedules” | Permissions now come from
owner configuration, so the old qualifier was misleading. |

Static audit: sentence case, existing glossary terms, short
descriptions, and active wording; controls use the shared kit, and
actions retain existing verb labels. Clamp explanations include a next
action, avoid internal protocol names, and convey meaning in text rather
than color alone. Existing Full access confirmations remain. No new
empty states or humorous copy. The permission descriptions and clamp
explanation serve separate purposes. **Visual audit passed in light/dark
on desktop and phone widths, including long names, narrow picker
overlays, and the clamp hint; labels and descriptions stay readable
without horizontal page overflow.**
nixuuu added a commit that referenced this pull request Nov 12, 2026
The same thread now exposes its home connector access and scheduled
tasks from either linked computer. A dedicated display DTO omits
credentials, headers, endpoints and account errors. Connector grants,
schedule creation, edits and cancellation run at home with owner and
revision checks. Worker grants affect every thread on that worker;
inherited All workers and account administration show a compact
home-management hint.

Verified panel responses survive a restart and remain visible as stale
when the home or panel read is unavailable. The archived sidebar now
pages local rows together with committed linked metadata: the previous 7
vs 31 counts came from intentionally local-only archive reads.

The three-gateway move regression now reconnects with a saved thread
cursor and requires a removal from the old home. The runtime exemption
for mirror subscriptions and range acknowledgments is already present in
the rebased dev branch; individual thread operations still follow their
redirects, and ACKs retain peer/subscription/cursor validation.

Gateway-to-gateway regression coverage exercises safe metadata, schedule
create/list/edit/cancel, home enforcement after grant changes, owner
isolation, cached stale reads, restart/unlink and archive
totals/pagination. Mobile changes are JavaScript/TypeScript only; native
configuration and dependencies are unchanged.

Validation:
- `bun install`, `bun run gen:check`, package-db typecheck and
changed-file oxfmt/oxlint passed. No full local `check:tmp` was run, as
requested; CI runs the full checks and test shards.
- Focused gateway-to-gateway panel tests, schema and upgrade tests
passed. The three-gateway move regression passed 20 consecutive runs.
After rebasing onto migration 0126, the panel/schema/inherited-access
tests passed; the staged sync upgrade exposed an ordering assumption,
was repaired and passed its focused rerun (17 assertions).
- Real-browser review used two linked gateways in light/dark at desktop
and phone widths. Both views show Connectors and Scheduled tasks. Remote
grant revoke/restore was reflected at home; remote schedule
create/edit/cancel worked. Disconnecting home retained connectors and
schedules with explicit stale/unreachable text and disabled actions.
Both archive counts were 38 (7 + 31), including offline. Short, typical
and long labels remained readable without horizontal overflow; removed a
duplicate offline hint that compressed schedule rows on phones.
- Native fingerprints match the tested dev base (`a79d316c`) for both
platforms: iOS `6ddec9ef559ee0095ac33e94ff9418a942053b17`; Android
`5f6eae3ab278f1cd543e9ed763f923a319b65ec9`. Mobile changes remain JS/TS
only. Subsequent rebases include JS/TS-only mobile changes from dev;
fresh CI runs on the final head.

Copy audit (§8): hidden sections → visible Connectors and Scheduled
tasks; Manage → scoped connector-access dialog with “Changes apply to
every thread on this worker.” This states the grant's actual scope.
Stale metadata → explicit last-known-details status; account-wide
changes → “Manage accounts on <computer>”. New actions use verbs,
sentence case and text status cues; no humorous copy. Existing controls
provide keyboard/focus behavior and name truncation. Browser review
covered short, typical and long names in light/dark at desktop and phone
widths, including offline states and dialog scrolling.

Related: #543, #539

Migration coordination: rebased onto `580a4815`, including #562 = 0124,
#547 = 0125, #560 = 0126 and #557 = 0127. This PR registers
`0128_thread_panel_cache`; the loader and schema expectations list 0124
through 0128 in order. The staged thread-sync upgrade test reads the
migration tail dynamically after the explicit 0126 stage, including 0127
and 0128, checks that durable sync state survives, and verifies that
repeating the full migration is a no-op. It does not assume 0128 is the
latest migration. Focused schema and staged/inherited-access upgrade
tests passed again after this rebase (25 tests, 107 assertions); all 6
remote-panel integration tests also passed (63 assertions). `bun
install` and `gen:check` passed. An initial panel test launch resolved a
workspace package to another checkout; refreshing installation corrected
the local alias before the successful rerun.
nixuuu added a commit that referenced this pull request Nov 12, 2026
An update or restart can surface an authentication failure as “Pair
again” even when the saved computer identity has not changed. Reconnect
now treats RPC authentication failures as retryable and requires
repeated, locally verified TLS pin mismatches before requesting new
trust. A successful handshake with the saved identity clears stale
pairing state.

## Investigation

- The dial catch classified **every**
`ConnectError(Code.Unauthenticated)` as a pin mismatch. That includes
invalid certificate validity, a peer rejecting the client pin, and hello
validation; on a manual route it persisted `pairing_required`, and on
LAN it deleted the route. This behavior exists in the original linking
implementation (#13), before the reported release range.
- Reviewed `v0.2.0-nightly.120..v0.2.0-nightly.137` and the `.133` →
`.137` diff, including #547, #548, #559, #562, #565, #566 and #546. The
full desktop hello grew from 32 capabilities to 33 in #559; both
releases reject more than 32 as `Unauthenticated: Invalid computer
identity` after pinned TLS succeeds. Merged #574 fixes this capability
overflow, including compatibility with the older validator. This branch
is rebased onto that fix in `dev`. Full source evidence:
#573 (comment).
- Identity and the 20-year certificate are persisted in
`computer_identity`; the private key uses the existing encrypted secrets
key. Desktop keeps the same Canopy data directory, database,
app/keychain name and `secrets.enc` across versions and channel changes.
Keychain/decryption failure stops startup rather than replacing the
identity. Reinstalling while preserving that data preserves trust;
deleting it creates a new identity.
- Production starts computer links, including loading identity and
peers, before opening Network access. There is no demonstrated
listener-before-store race in that path. The new readiness guard also
makes an early or stopping link service explicitly return `Unavailable`.
- `manual` means entered by the user, including a LAN/Tailscale address;
it is separate from the network's address type. A bad manual path must
not override another route or an incoming connection proving the saved
pin. The capability-count rejection is source-proven for the reported
version pair's full desktop configuration; incident logs would still be
needed to attribute every earlier report or explain successful
re-pairing.

## Changes

- Use a local `CertificatePinMismatch` signal emitted only after TLS
proof of possession and validation of a different self-signed
certificate. Override ConnectError's inherited structural
`Symbol.hasInstance` check so ordinary RPC errors cannot impersonate
this local class. Without this override the new LAN test correctly
caught a real route-deletion bug, not test timing. Invalid/expired
certificates remain rejected without declaring an identity change.
- Exhaust routes first. Require the same different certificate at the
same manual route in two consecutive failed rounds. A matching pinned
TLS connection or ready incoming link outweighs stale addresses. Only a
verified pin mismatch removes a discovered LAN route. Saved pins are
never replaced automatically.
- Clear confirmation evidence after pinned TLS verification, a
successful handshake, explicit pairing, route edits and unlink. Existing
successful handshake recovery also clears a persisted `pairing_required`
after restart.
- Use the shared reason “{name}'s identity changed. Pair again to trust
it.” for linked computer availability and app updates, including the
relay's name when its identity changed. Remove the contradictory
automatic-retry explanation for that state. Add stable auth-failure
classifications to diagnostics without logging certificates, keys,
addresses or RPC payloads.
- Document persistence and recovery. No proto changes, protocol bump or
migration.

## Regression coverage

Added gateway↔gateway integration scenarios using independent databases
and real TLS listeners:

1. Repeated startup `Unauthenticated` on manual and LAN routes preserves
trust and resumes; verify the LAN route remains after each attempt. RPC
error text cannot impersonate a local pin mismatch, and failed TLS
connections cannot confirm a manual route's identity change.
2. An early listener returns `Unavailable` for both `Pair` and `Connect`
until ready.
3. Both gateway/core restarts reuse persisted identities/certificates
and reconnect; a protocol-1 `.133` hello without new capabilities links
with a `.137` hello and resumes after upgrading.
4. A real new key requires confirmed pairing, receives no RPC, never
replaces the pin, and has consistent availability/update explanations.
5. A persisted stale pairing state heals after restart; a valid
alternate route outweighs a stale manual address with another key.

The older-version scenario exercises the compatible wire
hello/capability set, not archived app binaries. Installer and OS
keychain behavior was inspected in source, not exercised on
macOS/Windows.

## Validation

- After maintainer clearance, ran only the two authorized test files,
sequentially, at `nice -n 19`, using `TMPDIR=/var/tmp` and `bun run
check:tmp`: `linked-pairing-recovery.test.ts` **10 pass**,
`linked-capability-compatibility.test.ts` **3 pass**. Both
temp-directory checks passed. The original LAN failure reproduced before
the fix (8 pass / 1 fail); the strengthened assertion confirmed deletion
immediately after the first auth failure.
- Changed-file formatting and lint passed; `git diff --check` is clean.
Earlier dependency install and repository formatting/lint checks passed
before the original push.
- CI validates generation, full typechecking, all test shards and builds
for the rebased head. Browser verification remains pending; the UI
change reuses existing components and only changes status explanations.

## Copy audit (§8)

“{name} must be paired again” / “Link it again…” / “unavailable, trying
again automatically” → “{name}'s identity changed. Pair again to trust
it.” The text states the verified problem and the explicit trust action,
uses two short sentences and avoids TLS jargon. The compact action badge
remains “Pair again”. Names are interpolated as whole values and
existing wrapping/layout remains in place; short/long-name checks at
desktop/phone widths have not been run yet.

Related: #13
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