Repository navigation
feat(sessions): one snapshot per session per pass, and Sessions::Checks for the quota scan's checks (task #211, step 1) - #667
aixle-com[bot] wants to merge 5 commits into
Conversation
…ks for the quota scan's checks (task #211, step 1) Signed-off-by: Aixle Flow <[email protected]>
…nd their kept state (task #211) Signed-off-by: Aixle Flow <[email protected]>
| assert_raises(ArgumentError) { read(%i[scrollback something_else]) } | ||
| end | ||
|
|
||
| test "parses the shell's own output" do |
There was a problem hiding this comment.
[Recommendation] No test runs the generated script through a real shell.
The snapshot's correctness depends on a shell contract:
echoputs 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_readreconstructs 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.
There was a problem hiding this comment.
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.
|
|
||
| # 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) |
There was a problem hiding this comment.
[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").
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| # 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 |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
[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 undersession.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").
There was a problem hiding this comment.
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").
| # 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 } |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
… 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]>
|
Reopened in Alex's name for the squash merge (task #211). |
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]>
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(replacesquota_error_scan_workflow, every minute, now withoverlap: skip) runsActivities::Workflow::MonitorSessionsActivity. For each live workflow step (running/ready, with a container) a pass:applies_to?; a session no check applies to is not read;Sessions::Snapshot.read→Snapshot::ExecSource, throughContainerRuntime.for_session, capped atscan_op_timeout);UPDATE(Checks::KeptState).Every pass logs
[Sessions::Monitor] pass read=<n> duration_ms=<ms> …and returnsreadandduration_mswith its counts.Monitor.snapshotgives the same read on demand (step 2 uses it).The parts registry:
Sessions::Snapshot::Parts::REGISTRY.scrollback(capture-pane -S -1000),log_mtime(statof/tmp/terminal_output.log) andclients(tmux list-clientswith the container clock).Snapshot::Commandbuilds 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 areSnapshot#screen(the last 40 nonblank lines throughScreenDigest),#screen_digest,#last_output_at(counted only from a read that also captured the pane),#quiet_for?andClients#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_keysand#call(snapshot), and#callreturns aChecks::Result(an outcome, plus whether processing stops). The checks run in today's order:Checks::QuotaErrorChecks::BlockingPromptChecks::AuthPause(its actions stay inSessions::AuthPause)Checks::TurnEnd(replacesSessions::TurnEndNudge)The
*Detectorclasses stay as the text parsers.Re-check before acting, and conditional state changes.
Base#fail_session→ newSessionService.fail_session_if(session:, expected_state:, error_message:) { |locked| … }. Under the row lock (for an admitted session, through the newSessionAdmissionService.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 ingive_up.Sessions::AuthPause#pause!,#unpause_quietlyand#expire!are compare-and-sets too. A change that did not apply returns:taken_overand stops processing.Removed reads:
capture-paneexec;statexec on a quota hit;AuthPause'sstatexec (LiveLogReader#tail(lines: 1));TurnEndNudge'stmux list-clientsexec;AuthPause#banner_in.Kept state (each check owns its keys, written once per session per pass)
auth_paused_at,auth_pause_reason,auth_renewed_at,auth_heal_attempts,auth_heal_attempted_at(delivery'sresume!andlogin_refused!also write them)turn_end_screen,turn_end_seen_atturn_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:
overlap: skip(decision 8).|| truecapture while thestatexec failed). No check acted on that case before.Related issues
Board task #211. Follows #666 (#208).
Type of change
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.rbturn_end_nudge_test→test/services/sessions/checks/turn_end_test.rb(the stale-copy cases now return:taken_overinstead ofnil)auth_pause_testNew 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 aBase, 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.finishingduring the read is not failed (quota and blocking prompt), the auth pause does not pause afinishingsession or fail an unpaused one, and every pass logs its duration and read count.Run on Coder (
aixle-prod-2c822a0f, checkoute7ba0d17): 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
git commit -s).docs/architecture/workflows.md→ "Session monitoring";docs/design/agent-credential-lifecycle.md).