Skip to content

feat(sessions): one snapshot per session per pass, and Sessions::Checks for the quota scan's checks (task #211, step 1) - #667

Closed
aixle-com[bot] wants to merge 5 commits into
developfrom
feature/session-checks
Closed

aixle-com[bot] wants to merge 5 commits into
developfrom
feature/session-checks

Conversation

@aixle-com

@aixle-com aixle-com Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Summary

Step 1 of task #211 (decision 11.1): the mechanism, the interface, and the four checks that ran on the quota scan's read. Step 2 (the no-output watchdog and the token-refresh sweep) is a separate PR stacked on this one.

The mechanism: Sessions::Monitor. session_monitor_workflow (replaces quota_error_scan_workflow, every minute, now with overlap: skip) runs Activities::Workflow::MonitorSessionsActivity. For each live workflow step (running/ready, with a container) a pass:

  1. asks each check applies_to?; a session no check applies to is not read;
  2. collects the parts the applicable checks need;
  3. reads them with one exec (Sessions::Snapshot.read → Snapshot::ExecSource, through ContainerRuntime.for_session, capped at scan_op_timeout);
  4. hands the snapshot to the checks in order until one stops;
  5. writes the checks' kept state in one UPDATE (Checks::KeptState).

Every pass logs [Sessions::Monitor] pass read=<n> duration_ms=<ms> … and returns read and duration_ms with its counts. Monitor.snapshot gives the same read on demand (step 2 uses it).

The parts registry: Sessions::Snapshot::Parts::REGISTRY. scrollback (capture-pane -S -1000), log_mtime (stat of /tmp/terminal_output.log) and clients (tmux list-clients with the container clock). Snapshot::Command builds one script from the requested parts. Each part sits between a header and a footer that carries its exit status and a random marker for each read, so one failing part leaves the others readable and pane text cannot forge a delimiter. The shared helpers are Snapshot#screen (the last 40 nonblank lines through ScreenDigest), #screen_digest, #last_output_at (counted only from a read that also captured the pane), #quiet_for? and Clients#input_within?. The source can be swapped per runtime (Snapshot.source_for, for task 8c).

The interface: Sessions::Checks::Base. Each check implements .applies_to?, .parts, .kept_keys and #call(snapshot), and #call returns a Checks::Result (an outcome, plus whether processing stops). The checks run in today's order:

  • Checks::QuotaError
  • Checks::BlockingPrompt
  • Checks::AuthPause (its actions stay in Sessions::AuthPause)
  • Checks::TurnEnd (replaces Sessions::TurnEndNudge)

The *Detector classes stay as the text parsers.

Re-check before acting, and conditional state changes. Base#fail_session → new SessionService.fail_session_if(session:, expected_state:, error_message:) { |locked| … }. Under the row lock (for an admitted session, through the new SessionAdmissionService.fail_if! under the writer lock), it checks that the session is still in the state the pass read, that the check still applies, and that the check's own condition still holds. The state change happens in the same transaction, the method reports whether it applied, and only the Temporal signal goes after the commit. This closes the gap #666 accepted in give_up. Sessions::AuthPause#pause!, #unpause_quietly and #expire! are compare-and-sets too. A change that did not apply returns :taken_over and stops processing.

Removed reads:

  • the scan's own capture-pane exec;
  • the second stat exec on a quota hit;
  • AuthPause's stat exec (LiveLogReader#tail(lines: 1));
  • TurnEndNudge's tmux list-clients exec;
  • the separate screen normalization in AuthPause#banner_in.

Kept state (each check owns its keys, written once per session per pass)

Check Kept between passes Written by its action, under the row lock
QuotaError — —
BlockingPrompt — —
AuthPause — auth_paused_at, auth_pause_reason, auth_renewed_at, auth_heal_attempts, auth_heal_attempted_at (delivery's resume! and login_refused! also write them)
TurnEnd turn_end_screen, turn_end_seen_at turn_end_nudges (counted before typing)

Inventory

Checked against the code. The quota scan (4 checks), the no-output watchdog and RefreshExpiringTokensActivity#parked? are the only pieces that read a live terminal to decide something. Outside the mechanism:

  • ScanDeadContainersActivity (runtime API, no exec);
  • CleanupStaleActivity (DB timestamps);
  • Sessions::LogTail / LiveLogReader (the UI tail, get_session_log, session_log): reads for people;
  • AgentBaseStrategy's launch-time wait for the shell prompt: part of starting the CLI.

Behaviour

Thresholds, messages, skips and order are unchanged. Differences:

  • The schedule now has overlap: skip (decision 8).
  • When tmux is gone, the pane is now empty for every check (the old scan still got a pane from its || true capture while the stat exec failed). No check acted on that case before.
  • A check whose compare-and-set does not apply now leaves the session alone; before, it failed or paused the session anyway.

Related issues

Board task #211. Follows #666 (#208).

Type of change

  • Refactor / chore

How was this tested?

The existing tests were ported, with the same assertions:

  • scan_quota_errors_activity_test → test/temporal/activities/workflow/monitor_sessions_activity_test.rb
  • the auth-pause and turn-end activity tests
  • turn_end_nudge_test → test/services/sessions/checks/turn_end_test.rb (the stale-copy cases now return :taken_over instead of nil)
  • auth_pause_test

New tests:

  • test/services/sessions/snapshot_test.rb: one exec, only the requested parts, per-part failure, mtime only with a captured pane, marker-looking pane text, unreachable container.
  • test/services/sessions/checks/interface_test.rb: every check is a Base, the order, no shared kept keys, one-UPDATE kept-state write, key ownership.
  • test/services/session_service_fail_session_if_test.rb: a session finished after the read stays finished; a guard that no longer holds; the admitted path.
  • The pass: one exec per session, sessions no check applies to are not read, a session that moved to finishing during the read is not failed (quota and blocking prompt), the auth pause does not pause a finishing session or fail an unpaused one, and every pass logs its duration and read count.

Run on Coder (aixle-prod-2c822a0f, checkout e7ba0d17): rubocop on the 36 changed Ruby files passed, and 654 targeted Rails tests passed with 0 failures. The suites covered sessions, the workflow activities, session/admission services, credential delivery and sync, the Temporal registry and service, hosted-runtime-unchanged, runner session launch, the runner contract, the detectors, complete-step, agent credentials, docs, config and resources.

Checklist

  • All my commits are signed off for the DCO (git commit -s).
  • I added/updated tests where it makes sense.
  • I updated documentation where it makes sense (docs/architecture/workflows.md → "Session monitoring"; docs/design/agent-credential-lifecycle.md).
  • My commits use clear, descriptive messages.

Aixle Flow added 2 commits November 8, 2026 17:08
…ks for the quota scan's checks (task #211, step 1)

Signed-off-by: Aixle Flow <[email protected]>
assert_raises(ArgumentError) { read(%i[scrollback something_else]) }
end

test "parses the shell's own output" do

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Recommendation] No test runs the generated script through a real shell.

The snapshot's correctness depends on a shell contract:

  • echo puts the footer on its own line, and the parser takes exactly one newline back off;
  • s=$? carries each fragment's own status;
  • date +%s && tmux list-clients … fails as one unit;
  • the \#{client_readonly} escaping reaches tmux as a literal.

Two things cover it today, and neither runs Command#argv:

  • this test parses a hand-written stdout;
  • FakeRuntime#snapshot_read reconstructs the sections from the script with a regex.

A quoting or newline slip in Command#argv or in a Parts::REGISTRY script would pass CI and only show up in production, as every check reading nil. All checks treat nil as "unknown", so the monitor would go quiet without any error.

Suggestion: add one test that runs Command.new(%i[scrollback log_mtime clients]).argv with Open3.capture2 against a temp PATH. The PATH holds stub tmux and stat scripts that print known output, and one of them exits non-zero. Then assert parse returns the expected parts. This pins the real contract without a container.

Source: general engineering best practice (test the integration seam, not only its fake); docs/testing.md prefers the blessed fake for runtimes, but the fake here re-implements the very parsing under test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in cb83b51f. New test in snapshot_test.rb runs Command.new(%i[scrollback log_mtime clients]).argv through /bin/sh with Open3.capture2. Stub tmux and stat scripts sit on a temp PATH, and stat exits 1. The stub tmux checks that the -F format arrives as a literal, and its capture-pane output has no final newline. The test asserts that parse returns the scrollback and clients and leaves out log_mtime.

Comment thread app/services/sessions/auth_pause.rb Outdated

# Under the session's row lock, as #pause!: a session another path unpaused meanwhile
# (a delivery's #resume!, a pass's #unpause_quietly) is not unpaused twice.
def unpause!(renewed: false, &still)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Note] resume! ignores the new compare-and-set result of unpause!.

unpause! now returns false when another path unpaused the session first. #resume! (lines 76 and 82, a delivery's path) ignores that result: it logs "resumed" / "login renewed" and returns true either way. On the workflow-step branch, it has also already typed the resume prompt through nudge, before the compare-and-set.

Nothing breaks: the second unpause is a no-op now, which is the point of the change. But the log line and the return value no longer say what happened, and CredentialDelivery counts on that return value.

Suggestion: use the boolean, for example return false unless unpause! and the same for the interactive branch, so the log and the result match what was done. Moving the paused? re-check under the lock before nudge is optional, since it is outside this task's scope.

Source: task decision 5 ("it reports whether it applied. If it did not apply … the check stops").

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Correction: Agents::CredentialDelivery#deliver does not use resume!'s return value (credential_delivery.rb:41). Only the log line and the method's documented return value (@return [Boolean] whether the session was paused and has been resumed) are misleading. The suggestion stays the same.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in cb83b51f. resume! returns false when unpause! did not apply (both branches) and logs "already unpaused by another path" instead of "resumed" / "login renewed". Covered by the "a duplicate delivery returns false" test.

Comment thread app/services/sessions/auth_pause.rb Outdated
# Under the session's row lock, as #pause!: a session another path unpaused meanwhile
# (a delivery's #resume!, a pass's #unpause_quietly) is not unpaused twice.
def unpause!(renewed: false, &still)
unpaused = session.with_lock do

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Must] (second review) Task decision 5 and the project documentation in docs/architecture/workflows.md require every check action to be a compare-and-set and safe under Temporal retries. resume! types the resume prompt before this lock, then ignores unpause!'s Boolean result. Two concurrent deliveries can therefore both observe the pause and both type into the agent; the CAS loser still logs/returns success. There is a symmetric race in pause!: it commits auth_paused_at, releases the session lock, and only then calls run.pause!, so a delivery can clear the marker and observe a running run before pause! subsequently pauses it, leaving a paused workflow run with no auth-paused session to release it.

Please make pause/resume a durable claimed transition. For example, use a claim token or lock the session and workflow run in one consistent order for the metadata and run-state transition, and allow only the claim winner to send the prompt. Preserve the paused claim if typing fails, return the actual CAS result, and add concurrency tests for simultaneous pause/delivery and duplicate deliveries.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in cb83b51f (Alex's decision, Fix CR round 1). pause! and unpause! are each one transaction that locks the workflow run, then the session (#transition), and changes the marker and the run's state together. A delivery can no longer land between the marker and run.pause!, and two sessions of one run that unpause at once are serialized on the run's lock, so the second sees the first's marker gone and resumes the run. resume! now returns unpause!'s result. The resume prompt is still typed before the compare-and-set: typing is an exec and must not run inside a transaction, and typing after the unpause would leave the agent with no prompt if typing fails. A double prompt from two concurrent deliveries is accepted. No claim token. Tests in auth_pause_test.rb: a delivery between the pause marker and the run's pause, two sessions of one run unpaused concurrently, a duplicate delivery returning false.

…nd the session's locks, heal counters under the lock, a real-shell snapshot test (task #211, CR round 1)

- Sessions::AuthPause#pause! and #unpause! lock the workflow run, then the
  session, and change the marker and the run's state in one transaction.
  A delivery can no longer land between the marker and the run's pause,
  and two sessions of one run unpaused at once resume it.
- #resume! returns the unpause's result and logs only what happened. The
  resume prompt is still typed before the compare-and-set.
- #heal! counts its attempt under the session's row lock, re-reading the
  counter and, from the pass, heal_due? there.
- A test runs Snapshot::Command#argv through /bin/sh with stub tmux and stat.

Signed-off-by: Aixle Flow <[email protected]>
# The two unpauses are serialized on the run's row lock. Here the second one runs while the
# first holds its locks (`still` is called inside the first's transaction): it sees the
# first session still paused and leaves the run alone, and the first then resumes it.
test "two sessions of one run unpaused concurrently resume the run" do

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Recommendation] This test passes without the run lock, so the serialization this round added is not pinned.

The second unpause runs inside the first one's still block, on the same DB connection and in the same transaction. The second run.lock! and session.lock! are re-entrant there, and the second unpause sees the first session's marker because still runs before the marker is removed. So the test stays green in two cases:

  • if run&.lock! is removed from #transition. Then two real concurrent transactions can each see the other's marker as still set and leave the run paused, which is the race Alex's decision 1 was meant to close;
  • on the pre-fix code (e7ba0d17), which ran the same nested sequence under session.with_lock.

The delivery test above does fail on the old code, so that one is fine.

Suggestion: move this case into a test/services/sessions/auth_pause_concurrency_test.rb with self.use_transactional_tests = false. Use two threads, each with its own connection (ActiveRecord::Base.connection_pool.with_connection), and hold the first one inside still with a Queue until the second is waiting on the run's lock. Then assert the run ends running. Delete the records in teardown, as the existing concurrency tests do.

Source: existing implementation patterns in the repository (test/services/session_admission_concurrency_test.rb, test/services/runners/*_concurrency_test.rb), and Alex's Fix CR round 1 decision 1 ("two sessions of one run unpaused concurrently resume the run").

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 38c29da0 / 15f98e2b. The nested case is gone from auth_pause_test.rb. test/services/sessions/auth_pause_concurrency_test.rb (use_transactional_tests = false) runs the two unpauses on two threads, each with its own connection. The first is held inside its transaction, after it has looked for another paused step, until the second is seen waiting on a lock in pg_stat_activity. The test then asserts the run ends running. It follows runners/revocation_concurrency_test.rb, and its teardown deletes the rows. Checked on Coder: with run&.lock! commented out of #transition, the test fails (Expected: "running").

Comment thread app/services/sessions/auth_pause.rb Resolved
# Fails the session after its last reminder, if it still takes reminders and has used
# them all (Base#fail_session).
def give_up
result = fail_session(self.class.message_after_limit) { |locked| locked.metadata&.dig(COUNT_KEY).to_i >= LIMIT }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Must] (second review) The final-reminder failure does not CAS the confirmation that caused it. claim correctly requires the locked row to still hold the confirmed digest, but give_up re-checks only applicability and turn_end_nudges >= LIMIT. If a timed-out pass overlaps its Temporal retry, a newer observer can see the agent working and remove or replace turn_end_screen; the stale attempt can then acquire the lock and fail that working session from its obsolete snapshot.

Please pass the observed confirmation into give_up and require both turn_end_screen and turn_end_seen_at to match under the lock, as claim already does for reminders. Add a stale-copy regression where another observer clears or replaces the confirmation before failure and assert the session remains ready.

Source: task decision 5's Temporal-retry requirement and docs/architecture/workflows.md lines 808–832, which require the check's own condition to still hold inside the conditional state change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 38c29da0. give_up(digest) takes the confirmation the pass acted on. Under the lock it requires turn_end_screen to equal that digest and turn_end_seen_at to equal the observed time, as well as turn_end_nudges >= LIMIT. Tests in checks/turn_end_test.rb: another observer either clears the confirmation, or replaces it with the same screen at a later time, between the pass's read and the failure. In both cases the session stays ready with outcome :taken_over. Both tests fail when the new guard is removed.

Aixle Flow added 2 commits November 9, 2026 08:00
… and turn-end confirmation, a threaded unpause test (task #211, CR round 2)

- Sessions::AuthPause#pause! redacts the banner before storing auth_pause_reason.
- #expire! and #unpause_quietly take the auth_paused_at the pass observed and act only
  if the locked row still holds it; #expire! computes the expiry from the locked row.
- Checks::TurnEnd#give_up requires turn_end_screen and turn_end_seen_at to match the
  confirmation it acts on, under the lock.
- The two-sessions-of-one-run unpause test moves to auth_pause_concurrency_test.rb,
  on two threads with their own connections.

Signed-off-by: Aixle Flow <[email protected]>
…he concurrency test's sessions have a prompt (task #211, CR round 2)

Signed-off-by: Aixle Flow <[email protected]>
@aixle-com

aixle-com Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Reopened in Alex's name for the squash merge (task #211).

@aixle-com aixle-com Bot closed this Nov 9, 2026
@NOX73
NOX73 deleted the feature/session-checks branch November 9, 2026 11:22
aixle-com Bot pushed a commit that referenced this pull request Nov 10, 2026
Conflicts resolved:
- Files touched on staging only by the pre-squash branches of task #209 (PR #669)
  and task #211 (PRs #667/#668) take develop's version, which carries the
  reviewed, merged form of the same work (#670, #671, #672).
- test/integration/web/company/billing_test.rb: keeps the billing redesign's
  (#646) test body with develop's 14-day trial values (#678).
- CHANGELOG.md: develop's 1.11.0 entry for the 14-day trial; the billing
  redesign entry already present above is kept once.

Signed-off-by: Alex <[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.

0 participants