Skip to content

fix(remote): stop unlabelled inventories and replayed rows authorising destruction - #17981

Merged
nwparker merged 2 commits into
mainfrom
fix/ssh-sweep-leftovers
Sep 2, 2026
Merged

nwparker merged 2 commits into
mainfrom
fix/ssh-sweep-leftovers

Conversation

@nwparker

@nwparker nwparker commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​266 $\color{#cf222e}{\Huge{\mathbf{−}}}$​100 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​166
Prod 20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​253 $\color{#cf222e}{\Huge{\mathbf{−}}}$​73 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​180

Two fixes from the SSH sweep's leftover list. #17915 is closed with evidence and needed no code.

1. #15317 — a correctness bug, not a tuning question. TTL untouched.

The 30-minute staleness window was never reached, which is why this read as "pick a better number."

receivedAt was doing two jobs:

  • delivery/ordering — clearStatusEntriesForConnection raises a per-connection watermark, and four consumers drop anything at or below it (agent-status-event-applicator.ts:123,139, agent-status-live-entry-builder.ts:72, agent-status-cleanup-actions.ts:24);
  • evidence age — the freshness scheduler compares updatedAt + AGENT_STATUS_STALE_AFTER_MS.

On reconnect the relay replays every cached row, main restamps receivedAt, and every reconnect pushes the deadline out another 30 minutes. A pane stuck at working was unbounded.

Restamping the replay with its original time is not available — it would land at or below the watermark and be dropped outright, leaving the pane with no row at all, which is worse than a stale one. (I proposed exactly that first; it was wrong.)

So: two clocks. receivedAt untouched, all four guards and the watermark keep working. A new optional evidenceObservedAt is read only by the staleness comparison, so all ~12 existing call sites inherit it without edits. Main holds it per pane, bounded at 1024, deliberately surviving the transport clear — that clear deletes the row on purpose, but the age of evidence a later replay restates is not a claim about the pane. Dropped in clearPaneState, so a reused pane key cannot inherit one.

Wire: no relay-side addition needed. buildRelayHookEnvelope carries no timestamp and isReplay: true is already on the wire. The new field crosses only main→renderer IPC (versioned together). Absent means "no separate observation" and every consumer falls back — old rows and hosts behave exactly as today.

Behaviour: a live pane keeps stamping from its real events and stays working across reconnect. A pane whose relay restarted replays nothing and falls through to title evidence at confidence: 'fallback'. A genuinely stalled pane now decays after one window instead of never. The field can only move the deadline earlier, so it cannot fabricate liveness.

Still a product decision: AGENT_STATUS_STALE_AFTER_MS = 30 * 60 * 1000, unchanged. Shorter — a long quiet turn (a long build, a compaction, a model stall) emits no hooks and decays to "not fresh" while genuinely working; the sidebar dot drops working→active and smart-attention deprioritises it. Longer — a stalled pane spins for longer, but that is now bounded by the window; before it was unbounded, which is why the number looked like the problem. Prerequisite if you move it: the constant drives two deadlines in agent-status-freshness-scheduler.ts (hook freshness and completion freshness, plus smart-attention.ts:150), so tuning one tunes both.

2. #11495 Step C — the weaker action was gated on host authority; the stronger one was not

mirror-settle.ts already refuses to settle an empty inventory that is not authoritative. But buildMissingWebSessionTabsRemovals, which destroys an entire worktree mirror, never read event.authoritative at all. settleSessionTabsInventory sets that flag only when isCompleteSessionTabsPtyCensus passes — so an unlabelled inventory is the host saying my census is incomplete. That is unverifiable, and it was authorising destruction.

Now: authoritative → one omission is attestation, removal immediate (unchanged for capable hosts). Unlabelled → must repeat, reusing the two-observation shape of confirmSurfaceInventoryAbsence.

A genuinely gone worktree still goes: authoritative hosts remove on the first inventory as today; a legacy or degraded host removes on the second, one extra visibility resume. It cannot fail to recover, and ghosts cannot outlive the fence.

The 14 blocking tests — provenance settled, none encodes a defect

git log -S on each title: 14 of 15 come from one commit, PR #13621 "park hidden remote session mirrors" (2026-08-11). They assert that a full inventory omitting a tracked worktree retires its mirror, and that the ordering/fencing around that retirement is right.

The decisive fact is the date. SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY landed 2026-08-26 in PR #16546 — fifteen days later. These fixtures could not have expressed a distinction whose vocabulary did not yet exist. They encode a contract written before the words for it existed, not a bug. All 15 were retargeted to say authoritative: true explicitly via a named authoritativeInventory() helper — not weakened.

Negative control in the other direction: making the authoritative path also require two observations reproduces exactly those 15 failures, so the immediate-removal contract is still pinned.

max-lines forced two extractions rather than a disable — omission/tombstone logic to session-tabs-inventory-absence.ts, and the test file's duplicated park/reveal blocks into one parkAndReveal(multiplier) helper (net −18 lines before the new tests).

Step A deliberately not implemented

Three reasons, and the third is the real one:

  1. The signal does not exist at that layer — authoritative is a host-wide census verdict; per-worktree snapshot/updated frames never carry one, so "not authoritative" would be true almost always.
  2. It would break correct pruning — apply-terminal-records.ts deletes those keys only for tabs a frame did not re-publish. Append-only leaves dead handles in ptyIdsByTabId, the live-PTY index feeding doomed-PTY computation and wake/respawn (terminal-tab-retirement.ts:64-80, worktree-purge-doomed-ids.ts:29-38).
  3. Wrong layer — the evidence lives in web-session-terminal-orphan-recovery-inventory.ts, which already reasons about truncated / hostScopeUnverifiable. The specific bad disposition Step A compensated for is already fixed in fix(remote): stop a colliding path key, a dead conflict state, and a live-PTY removal from losing tabs #17948.

3. #17915 — premise stale, no code change

The issue says #17914 fixes the app and daemon "but not the SSH relay," leaving a platform split. That split does not exist, because the fix does not exist anywhere: #17914 is open and unmerged, and grep -rn "FD_CLOEXEC\|O_CLOEXEC\|cloexec" config/ src/ scripts/ returns no matches — including inside the src/unix/pty.cc hunks of config/patches/[email protected], which carry only the GCC-9 floor, the winpty/conpty target removal, and console-list-agent work.

The leak is uniform across app, daemon and relay. #17915 is blocked on #17914, not independently fixable. Ground truth for whoever picks it up is in the commit message; note relay-native-dependency-coverage.test.ts:93-103 pins version parity and would break under the version-bump option.

User-facing regressions

None expected. Verbatim before/after in both commits; negative controls in both directions. tc:node/tc:web/tc:cli clean, check:code-quality:changed 0 findings. Sweeps: src/renderer/src/runtime 1243 passed; agent-hooks + slices + ipc-events + lib 8516 passed; components + runtime + shared + ssh 32178 passed.

Follow-up identified, not done

runtime-mobile-agent-status-projection.ts:151 (updatedAt: live.receivedAt) is the same clock bug on the paired-runtime mirror path reaching mobile/web. Propagating the field there changes HookLiveAgentRow and the runtime wire shape — a real mixed-version surface needing full compat treatment, and it inherits the cross-authority clock skew documented in agent-status-observation.ts. Scoped follow-up rather than forced in.

…e mirror

#11495 Step C. `buildMissingWebSessionTabsRemovals` synthesised a `removed: true`
tombstone -- emptying a worktree's entire mirror -- for any tracked worktree
absent from a single inventory frame, without ever consulting the host's own
authority label. `mirror-settle` already refuses to settle an *empty* inventory
that is not `authoritative` (#16414, #16546); the strictly more destructive
action was ungated.

An inventory the host labels `authoritative` carries a complete PTY census, so
one omission is host attestation and removal stays immediate. An unlabelled
inventory is a degraded or version-skewed census: `unverifiable`, not `exited`.
It must now repeat before it can destroy anything, reusing the two-observation
shape of `confirmSurfaceInventoryAbsence`. A legacy host that never negotiates
the capability still converges after two rounds, so ghost rows cannot outlive
the fence.

The 14 tests from #13621 that blocked this were all written before the
`authoritative` label existed (#13621 landed 2026-08-11; the capability landed
2026-08-26 in #16546). #13621's own summary says "Reconcile each resumed host
from an authoritative inventory, including removals", so their fixtures are
retargeted to say so explicitly rather than weakened.

Refs #11495
…lock

#15317 correctness half. `receivedAt` was doing two jobs: delivery order and
evidence age. A relay reconnect replays every cached row, and `receivedAt` must
restamp to clear the connection watermark that `clearStatusEntriesForConnection`
raises -- so a pane stuck at `working` had its 30-minute deadline pushed out by
another 30 minutes on every reconnect. The TTL was never reached, which is why
this read as a tuning question.

Two clocks, not one rewritten clock:

- `receivedAt` is untouched. The transient-clear watermark and the four `<`
  ordering drops (`agent-status-event-applicator`, `agent-status-live-entry-builder`,
  `agent-status-cleanup-actions`) keep working unchanged. Restamping a replay with
  its original time would have made it `<= watermark` and dropped it outright,
  leaving the pane with no row at all.
- `evidenceObservedAt` is new, optional, and read only by the staleness
  comparison (`isFreshNonDoneAgentStatus`, `isExplicitAgentStatusFresh`, the
  freshness scheduler). Main holds it per pane across the transport clear -- the
  clear deletes the row on purpose, but the *age* of evidence a later replay
  restates is not a claim about the pane. Absent means "no separate observation",
  and every consumer falls back to `receivedAt`/`updatedAt`, so old hosts and old
  rows behave exactly as today.

Behaviour: a genuinely active pane keeps stamping the observation clock from its
real events, so it stays `working` across a reconnect. A pane whose relay
restarted replays nothing and still falls through to title evidence. A torn-down
pane drops its remembered clock in `clearPaneState`, so a reused pane key cannot
inherit one.

`AGENT_STATUS_STALE_AFTER_MS` is deliberately unchanged -- the window length
remains a product decision.

Refs #15317
@coderabbitai

coderabbitai Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Caution

Review failed

An error occurred during the review process. Please try again later.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

evidenceObservedAt is written to the last-status file but never read back at hydrate, so it does not survive a main restart as the type comment and PR body claim — the restart variant of #15317 is still open. See the inline comment on server-types.ts:18 for the exact path and fix.

Reviewed changes

  • Staleness clock split (evidenceObservedAt) — a new optional observation timestamp, read only by the freshness comparison, so a relay reconnect replay stops restamping the staleness deadline. receivedAt keeps its delivery/ordering role so the connection-clear watermark and the renderer's four < drops are untouched.
  • Authoritative-gated mirror destruction — buildMissingWebSessionTabsRemovals now reads hostAuthoritative: a capable host removes on the first omission, an unlabelled/degraded census must repeat via a two-observation fence (mirroring confirmSurfaceInventoryAbsence) before it can tombstone a worktree mirror.
  • Test retargeting + extraction — 14 fixtures retargeted to authoritative: true via an authoritativeInventory() helper, plus new replay-clock (server-replay-evidence-clock.test.ts, agent-status-evidence-clock.test.ts) and absence (web-session-tabs-sync-window-visibility.test.tsx) tests.

ℹ️ Nitpicks

  • dropStatusEntriesByTabPrefix in server-tab-cleanup.ts clears every per-pane cache that clearPaneState does but was not given the same evidenceObservedAtByPaneKey.delete. It is bounded dead weight in practice (a closed pane's key is suppressed before it could replay), so nothing user-visible — but the asymmetry is easy to miss next time this map gains a reader.
  • omissionKey in session-tabs-inventory-absence.ts re-implements sessionTabsFreshnessKey (${environmentId}:${worktreeId}) verbatim, and the cleanup paths in tracking-lifecycle.ts rely on that same format matching. Use sessionTabsFreshnessKey directly so the two key spaces can't silently diverge.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

* replays cached rows and `receivedAt` must restamp to clear the connection watermark, so
* only this clock can answer how old the evidence itself is. Persisted so it survives a
* main restart; absent means "never separately observed" and consumers use `receivedAt`. */
evidenceObservedAt?: number

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JSDoc says evidenceObservedAt is "Persisted so it survives a main restart", but it is not actually round-tripped: serializeStatusFile writes it through the ...persistedPayload rest spread, yet sanitizeHydratedEntry reconstructs the enriched row from an explicit field list that omits it. After a restart the in-memory evidenceObservedAtByPaneKey map is empty and the hydrated row also lacks the field, so the first reconnect replay sets evidenceObservedAt = now and clears restoredUnconfirmed in applyNormalizedStatus — re-arming the 30-minute window for a genuinely stuck working pane. The reconnect fix works; the restart variant of #15317 does not.

Technical details
# evidenceObservedAt does not survive hydration

## Affected sites
- src/main/agent-hooks/server/server-persistence.ts:41 — `...persistedPayload` rest spread persists `evidenceObservedAt` into the last-status file.
- src/main/agent-hooks/server/server-persistence-validation.ts:104-125 — `sanitizeHydratedEntry` rebuilds the row from an explicit field list and never reconstructs `evidenceObservedAt`, so the persisted copy is discarded.
- src/main/agent-hooks/server/server-hydration.ts:103 — hydrated rows land in `lastStatusByPaneKey` without the field.
- src/main/agent-hooks/server/server-status-update.ts:181-200 / server-status-application.ts:59-77 — a later `isReplay` event runs `resolveEvidenceObservedAt` with an empty map and undefined `previous.evidenceObservedAt`, producing `now`, and the new enriched row drops `restoredUnconfirmed`.

## Required outcome
- Either reconstruct `evidenceObservedAt` in `sanitizeHydratedEntry` (validate `typeof === 'number' && Number.isFinite`) so the "survives a main restart" claim is true, or strip it from persistence like `isReplay` and correct the JSDoc + PR body to state it is runtime-only. The type and the code must agree.

## Suggested approach (optional)
- Mirror the existing `receivedAt`/`stateStartedAt` validation in `sanitizeHydratedEntry` and add `evidenceObservedAt` to the returned object; add a hydrate round-trip assertion to `server-replay-evidence-clock.test.ts`.

## Open questions for the human (optional)
- Is the restart scenario actually in scope for #15317, or is the reconnect-only fix sufficient and only the comment is wrong?

@nwparker
nwparker merged commit 4e35e05 into main Sep 2, 2026
33 checks passed
@nwparker
nwparker deleted the fix/ssh-sweep-leftovers branch September 2, 2026 05:43
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Sep 3, 2026
…g destruction (stablyai#17981)

* fix(remote): stop one unlabelled inventory tombstoning a live worktree mirror

stablyai#11495 Step C. `buildMissingWebSessionTabsRemovals` synthesised a `removed: true`
tombstone -- emptying a worktree's entire mirror -- for any tracked worktree
absent from a single inventory frame, without ever consulting the host's own
authority label. `mirror-settle` already refuses to settle an *empty* inventory
that is not `authoritative` (stablyai#16414, stablyai#16546); the strictly more destructive
action was ungated.

An inventory the host labels `authoritative` carries a complete PTY census, so
one omission is host attestation and removal stays immediate. An unlabelled
inventory is a degraded or version-skewed census: `unverifiable`, not `exited`.
It must now repeat before it can destroy anything, reusing the two-observation
shape of `confirmSurfaceInventoryAbsence`. A legacy host that never negotiates
the capability still converges after two rounds, so ghost rows cannot outlive
the fence.

The 14 tests from stablyai#13621 that blocked this were all written before the
`authoritative` label existed (stablyai#13621 landed 2026-08-11; the capability landed
2026-08-26 in stablyai#16546). stablyai#13621's own summary says "Reconcile each resumed host
from an authoritative inventory, including removals", so their fixtures are
retargeted to say so explicitly rather than weakened.

Refs stablyai#11495

* fix(agent-status): stop a reconnect replay restamping the staleness clock

stablyai#15317 correctness half. `receivedAt` was doing two jobs: delivery order and
evidence age. A relay reconnect replays every cached row, and `receivedAt` must
restamp to clear the connection watermark that `clearStatusEntriesForConnection`
raises -- so a pane stuck at `working` had its 30-minute deadline pushed out by
another 30 minutes on every reconnect. The TTL was never reached, which is why
this read as a tuning question.

Two clocks, not one rewritten clock:

- `receivedAt` is untouched. The transient-clear watermark and the four `<`
  ordering drops (`agent-status-event-applicator`, `agent-status-live-entry-builder`,
  `agent-status-cleanup-actions`) keep working unchanged. Restamping a replay with
  its original time would have made it `<= watermark` and dropped it outright,
  leaving the pane with no row at all.
- `evidenceObservedAt` is new, optional, and read only by the staleness
  comparison (`isFreshNonDoneAgentStatus`, `isExplicitAgentStatusFresh`, the
  freshness scheduler). Main holds it per pane across the transport clear -- the
  clear deletes the row on purpose, but the *age* of evidence a later replay
  restates is not a claim about the pane. Absent means "no separate observation",
  and every consumer falls back to `receivedAt`/`updatedAt`, so old hosts and old
  rows behave exactly as today.

Behaviour: a genuinely active pane keeps stamping the observation clock from its
real events, so it stays `working` across a reconnect. A pane whose relay
restarted replays nothing and still falls through to title evidence. A torn-down
pane drops its remembered clock in `clearPaneState`, so a reused pane key cannot
inherit one.

`AGENT_STATUS_STALE_AFTER_MS` is deliberately unchanged -- the window length
remains a product decision.

Refs stablyai#15317

Mirror-Of: 4e35e05
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…g destruction (stablyai#17981)

* fix(remote): stop one unlabelled inventory tombstoning a live worktree mirror

stablyai#11495 Step C. `buildMissingWebSessionTabsRemovals` synthesised a `removed: true`
tombstone -- emptying a worktree's entire mirror -- for any tracked worktree
absent from a single inventory frame, without ever consulting the host's own
authority label. `mirror-settle` already refuses to settle an *empty* inventory
that is not `authoritative` (stablyai#16414, stablyai#16546); the strictly more destructive
action was ungated.

An inventory the host labels `authoritative` carries a complete PTY census, so
one omission is host attestation and removal stays immediate. An unlabelled
inventory is a degraded or version-skewed census: `unverifiable`, not `exited`.
It must now repeat before it can destroy anything, reusing the two-observation
shape of `confirmSurfaceInventoryAbsence`. A legacy host that never negotiates
the capability still converges after two rounds, so ghost rows cannot outlive
the fence.

The 14 tests from stablyai#13621 that blocked this were all written before the
`authoritative` label existed (stablyai#13621 landed 2026-08-11; the capability landed
2026-08-26 in stablyai#16546). stablyai#13621's own summary says "Reconcile each resumed host
from an authoritative inventory, including removals", so their fixtures are
retargeted to say so explicitly rather than weakened.

Refs stablyai#11495

* fix(agent-status): stop a reconnect replay restamping the staleness clock

stablyai#15317 correctness half. `receivedAt` was doing two jobs: delivery order and
evidence age. A relay reconnect replays every cached row, and `receivedAt` must
restamp to clear the connection watermark that `clearStatusEntriesForConnection`
raises -- so a pane stuck at `working` had its 30-minute deadline pushed out by
another 30 minutes on every reconnect. The TTL was never reached, which is why
this read as a tuning question.

Two clocks, not one rewritten clock:

- `receivedAt` is untouched. The transient-clear watermark and the four `<`
  ordering drops (`agent-status-event-applicator`, `agent-status-live-entry-builder`,
  `agent-status-cleanup-actions`) keep working unchanged. Restamping a replay with
  its original time would have made it `<= watermark` and dropped it outright,
  leaving the pane with no row at all.
- `evidenceObservedAt` is new, optional, and read only by the staleness
  comparison (`isFreshNonDoneAgentStatus`, `isExplicitAgentStatusFresh`, the
  freshness scheduler). Main holds it per pane across the transport clear -- the
  clear deletes the row on purpose, but the *age* of evidence a later replay
  restates is not a claim about the pane. Absent means "no separate observation",
  and every consumer falls back to `receivedAt`/`updatedAt`, so old hosts and old
  rows behave exactly as today.

Behaviour: a genuinely active pane keeps stamping the observation clock from its
real events, so it stays `working` across a reconnect. A pane whose relay
restarted replays nothing and still falls through to title evidence. A torn-down
pane drops its remembered clock in `clearPaneState`, so a reused pane key cannot
inherit one.

`AGENT_STATUS_STALE_AFTER_MS` is deliberately unchanged -- the window length
remains a product decision.

Refs stablyai#15317
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