Skip to content

Make implicit state machines explicit #2890

Open

Description

@sentry-junior

Several lifecycles in Junior keep state in two to four places that are synced by hand: Redis records, SQL copies, index membership, keys that expire, and combinations of optional fields or booleans. Each lifecycle also has many writers and no single owner of its transitions. These drifts account for about 15 fix commits and one production incident (JUNIOR-9M, aaf51a505).

Audit at 5187ebf. Code refs are verified. Races marked inferred were found by reading the code and were not reproduced. Paths are under packages/junior/src/.

The work goes one PR at a time, in this order. Conversation status is reworked in #2888; status-specific concerns are in this comment.

Prevention

  • Add a rule to policies/: each lifecycle is one tagged type with one function that owns its legal changes. Copies (SQL mirrors, indexes, counts) are written in the same step as the source. No state is derived from a combination of optional fields, a timestamp, or a key expiring.

Quick fixes

  • chat/mcp/tool-manager.ts:851: forgetProvider drops MCP clients without closing them, so close() can no longer reach them. It also leaves clientPromisesByProvider alone, so an in-flight connect can re-add a client after the provider moved to auth-pending.
  • upsertTurnRecordLocked (chat/task-execution/turn-cursor.ts:825) has no terminal or version check, so saveRunning (checkpoint.ts:245-257) can move a failed or abandoned Turn back to running (late-worker race inferred; workers do come back after losing their lease, see c587ed558).
  • markAgentInvocationMailboxAppended (chat/agent-invocations/store.ts:312-321) has no status check in its WHERE clause. A read-side recheck in result.ts:313-322 protects it today.
  • Remove dead state writers: recordConversationExecution (chat/task-execution/state.ts:1585, no non-test caller, sets any status), injectedAtMs (read at state.ts:486, never written), and the duplicate turnWakeError branch (chat/providers/slack/turn.ts:1458-1461).
  • Scheduled Automation edits can set blocked with no statusReason (chat/scheduled-automations/edit-schema.ts:39, editScheduledAutomation).

Turn and execution core (with #2888)

  • Turn state lives in the Turn record (terminal TTL 1h), a TurnSummary index (24h), the SQL execution copy, and lifecycle events. Readers reconcile them (mailbox-turn.ts:136-180, turn-cursor.ts:1029-1050). Cost: aaf51a505 (JUNIOR-9M).
  • ExecutionStatus (state.ts:79) has about 14 writers with their own rules. Reads repair illegal combinations: idle with a lease becomes running, idle with pending input becomes pending (state.ts:502-508, 636-650). failed with pending messages still counts as runnable (state.ts:623-634).
  • SQL picks the winning execution status by updatedAtMs plus an olderRunFinished metrics lookup (chat/conversations/sql/store.ts:524-547, 873). Cost: 30f8b2cab.
  • conversation:active membership is written apart from the record (state.ts:1029-1088), and heartbeat removes it outside the mutation lock (heartbeat.ts:89-94) (drift inferred).
  • Stop lives in a Redis stop key, a stop-only runId, and SQL stoppedAt (state.ts:1966-2058). Cost: 63bc0657c, 72edb9c11.
  • Turn record as one tagged type with terminal states that absorb later writes; summary written in the same transition.
  • Execution as one tagged type with one transition function; SQL as a copy keyed by run and version; index membership written in the same step.

Child agent invocations

  • Child status is pieced together from invocation.status, parentMailboxStatus, and stoppedAtMs (chat/agent-invocations/list.ts:44-112). completeAgentInvocation has 9 call sites in work.ts, and the bulk stop (stop.ts:345-362) skips it. steered is stored as completed with an empty result (store.ts:425-427). Cost: 62866985, 05108d93, 5187ebf4.
  • One owner for invocation transitions; explicit steered and mailbox delivery states.

Pending auth (related: #843)

  • A sign-in wait lives in McpAuthSessionState (24h, chat/mcp/auth-store.ts:25-43), processing.pendingAuth (7d, chat/state/conversation.ts:76-97), the web-authorization key (24h), and the Turn record (paused + resumeReason: auth). deleteMcpAuthSession has 7 callers. MCP provider state is membership across 7 maps and sets (chat/mcp/tool-manager.ts:358-370). Cost: d0a9a4816, d1d7e6836, 6c6b90e98, 9a2e00856, a2ac98b5f.
  • One sign-in attempt record with an explicit status; one state per MCP provider.

Automations (related: #2051)

  • Paused-while-blocked is coded separately in 5 places (event-automations/store.ts:493-544, automations/edit.ts:358-366, scheduled-automations/runs.ts:572-585, scheduled-automations/edit.ts:77-81). Finishing a run and advancing the Automation are separate transactions (heartbeat.ts:140-152; repair path in runs.ts:354-370, Link an Automation run to its Conversation with a foreign key #2176). Event runs copy dispatch state from Redis and treat a missing record as failed (event-automations/runs.ts:40-43). Cost: d6b2ea19.
  • One Automation status type and transition function for both kinds; one transaction finishes a run and advances the Automation.

Slack reply lifecycle

  • About 9 booleans in chat/providers/slack/turn.ts:762-799, with the terminal state worked out in a finally. "Posted but not confirmed" is not a state, which leaves a duplicate-reply risk (794dc4bc4).
  • One explicit reply phase with one function that advances it.

Lower priority

  • Sandbox binding: "" means no sandbox (chat/runtime/thread-state.ts:33-38), the thread-state blob is merged with get-then-set (:48-64), and switchWorkspace persists the new ref before stopping the old sandbox (chat/sandbox/session.ts:894-955, leak inferred).
  • Archive: undoing a child archive matches by exact timestamp (api/conversations/archive.ts:168-180). Fold into the single-archive work in Add Threads: child conversations people can talk to #2792.
  • Snapshot build phase is inferred from sandboxName? + commandId? inside building (chat/sandbox/snapshot/workspace.ts:141-146, 580-620).
  • Watches: expired and timer-vs-resource kind are derived (chat/events/store.ts:279-281, 470); three index removals follow the status write.
  • Review items: how an item closed is keyed on the string "Replied in thread" (chat/review-items/actions.ts:71-81, store.ts:273, slack/review-item-card.ts:133).

Already explicit, no change: snapshot status (check constraints and guarded writes), transitionDispatch, review-item first-close-wins, the plugin credential result type, background compaction.

via @dcramer.

--

View Session [Sentry]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions