fix(office): stop mark fixed from silently discarding a newer pause reason (#3734)

Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
Henry
2026-09-17 21:33:52 +08:00
committed by GitHub
parent e8e8bcff64
commit 3faf244b1d
11 changed files with 622 additions and 11 deletions
@@ -464,6 +464,32 @@ func (r *Repository) UpdateAgentStatusFieldsIfCurrent(
return rows > 0, nil
}
// UnpauseAgentIfCurrent moves a paused agent to newStatus and clears
// pause_reason, but only while the row still has status='paused' AND
// pause_reason=expectedReason. Gating on the pause reason as well as the
// status closes the window where a concurrent writer changes the reason
// (a second auto-pause landing on an already-paused agent) while status
// stays 'paused': a status-only guard would accept that write and
// silently clobber the newer reason instead of refusing it.
func (r *Repository) UnpauseAgentIfCurrent(
ctx context.Context, id, expectedReason, newStatus string,
) (bool, error) {
now := time.Now().UTC()
result, err := r.db.ExecContext(ctx, r.db.Rebind(`
UPDATE agent_profiles
SET status = ?, pause_reason = '', working_run_id = '', updated_at = ?
WHERE id = ? AND status = ? AND pause_reason = ? AND `+agentInstanceFilter+`
`), newStatus, now, id, string(models.AgentStatusPaused), expectedReason)
if err != nil {
return false, err
}
rows, err := result.RowsAffected()
if err != nil {
return false, err
}
return rows > 0, nil
}
// ClearAgentPauseReasonIfCurrent clears only pause_reason when the agent
// still has expectedStatus. This preserves a concurrent working or stopped
// status while avoiding a stale status write.
@@ -710,6 +710,61 @@ func TestUpdateAgentStatusFieldsIfCurrent_DoesNotOverwriteNewStatus(t *testing.T
}
}
// A status-only CAS can't tell a concurrent pause_reason change apart from
// the reason it originally observed: status stays 'paused' the whole time,
// so a status-only guard accepts the write either way. UnpauseAgentIfCurrent
// closes that by gating on pause_reason too.
func TestUnpauseAgentIfCurrent_RefusesWhenPauseReasonChanged(t *testing.T) {
repo := newTestRepo(t)
ctx := context.Background()
agent := fullAgentInstance("st-unpause-cas", "ws-1", "Unpause CAS")
if err := repo.CreateAgentInstance(ctx, agent); err != nil {
t.Fatalf("CreateAgentInstance: %v", err)
}
if err := repo.UpdateAgentStatusFields(ctx, agent.ID, "paused", "Auto-paused: reason1"); err != nil {
t.Fatalf("pause agent: %v", err)
}
// A second, unrelated auto-pause lands while status stays 'paused'.
if err := repo.UpdateAgentStatusFields(ctx, agent.ID, "paused", "Auto-paused: reason2"); err != nil {
t.Fatalf("re-pause agent: %v", err)
}
changed, err := repo.UnpauseAgentIfCurrent(ctx, agent.ID, "Auto-paused: reason1", "idle")
if err != nil {
t.Fatalf("compare-and-set unpause: %v", err)
}
if changed {
t.Fatal("compare-and-set unpause = true, want false (pause_reason changed underneath it)")
}
got, err := repo.GetAgentInstance(ctx, agent.ID)
if err != nil {
t.Fatalf("GetAgentInstance: %v", err)
}
if got.Status != settingsmodels.AgentStatus("paused") || got.PauseReason != "Auto-paused: reason2" {
t.Fatalf("status/reason = %q/%q, want paused/Auto-paused: reason2 (newer reason preserved)",
got.Status, got.PauseReason)
}
// The observed reason still matches: the CAS succeeds, moving the
// agent to idle and clearing pause_reason.
changed, err = repo.UnpauseAgentIfCurrent(ctx, agent.ID, "Auto-paused: reason2", "idle")
if err != nil {
t.Fatalf("compare-and-set unpause (matching reason): %v", err)
}
if !changed {
t.Fatal("compare-and-set unpause (matching reason) = false, want true")
}
got, err = repo.GetAgentInstance(ctx, agent.ID)
if err != nil {
t.Fatalf("GetAgentInstance: %v", err)
}
if got.Status != settingsmodels.AgentStatus("idle") {
t.Fatalf("status = %q, want idle", got.Status)
}
}
func TestClearAgentPauseReasonIfCurrent_PreservesStatus(t *testing.T) {
repo := newTestRepo(t)
ctx := context.Background()
@@ -165,11 +165,6 @@ func (s *Service) MarkAgentPausedFixed(
// Both the pause marker and its durable recovery work are gone.
return s.repo.DismissInboxItem(ctx, userID, InboxKindAgentPausedAfterFails, agentID)
}
if err := s.repo.DismissInboxItem(
ctx, userID, InboxKindAgentPausedAfterFails, agentID,
); err != nil {
return fmt.Errorf("dismiss: %w", err)
}
if autoPaused {
if err := s.clearAutoPause(ctx, agent); err != nil {
@@ -180,6 +175,15 @@ func (s *Service) MarkAgentPausedFixed(
zap.String("agent", agentID), zap.Error(err))
}
}
// Dismissed only once the auto-pause this call observed is actually
// cleared (or there was none to clear): a refused clearAutoPause
// returns above, leaving the inbox entry for a still-active pause
// visible and this call retryable instead of silently swallowed.
if err := s.repo.DismissInboxItem(
ctx, userID, InboxKindAgentPausedAfterFails, agentID,
); err != nil {
return fmt.Errorf("dismiss: %w", err)
}
return s.recoverPausedTasks(ctx, agentID, recoveries)
}
@@ -209,6 +213,7 @@ func (s *Service) loadPauseRecoveries(
func (s *Service) clearAutoPause(
ctx context.Context, agent *models.AgentInstance,
) error {
originalReason := agent.PauseReason
for attempt := 0; attempt < 2; attempt++ {
changed, err := s.clearAutoPauseAttempt(ctx, agent)
if err != nil {
@@ -225,6 +230,15 @@ func (s *Service) clearAutoPause(
if !strings.HasPrefix(current.PauseReason, autoPauseReasonPrefix) {
return nil
}
// Still paused but with a reason this call never observed means a
// newer auto-pause landed between our read and the CAS above.
// Retrying against it would clear that newer pause and let the
// caller reset the counter and recover tasks from this call's
// stale snapshot instead. Abort so the newer pause stays intact
// and reachable by a fresh "Mark fixed".
if current.Status == models.AgentStatusPaused && current.PauseReason != originalReason {
return fmt.Errorf("clear pause reason: a newer auto-pause is in progress")
}
agent = current
}
return fmt.Errorf("clear pause reason: agent status changed")
@@ -242,9 +256,8 @@ func (s *Service) clearAutoPauseAttempt(
func (s *Service) unpauseAgentIfCurrent(
ctx context.Context, agent *models.AgentInstance,
) (bool, error) {
changed, err := s.repo.UpdateAgentStatusFieldsIfCurrent(
ctx, agent.ID, string(models.AgentStatusPaused),
string(models.AgentStatusIdle), "",
changed, err := s.repo.UnpauseAgentIfCurrent(
ctx, agent.ID, agent.PauseReason, string(models.AgentStatusIdle),
)
if err != nil {
return false, fmt.Errorf("unpause agent: %w", err)
@@ -454,6 +454,87 @@ func TestMarkAgentPausedFixed_DiscardsRecoveryForReassignedTask(t *testing.T) {
}
}
// Regression for card b250dfad: recoverPausedTask's stale-failed-run guard
// (failure.go: discard when the latest run for the task is no longer the
// recovery's recorded FailedRunID) was covered by nothing — neutering the
// guard left `go test ./internal/office/...` green. If a newer run has
// already superseded the one the pause snapshot points at (for example a
// manual retry that landed and finished while the agent was still paused),
// MarkAgentPausedFixed must discard that stale recovery instead of
// re-queuing a duplicate run for a task that has already moved on.
func TestMarkAgentPausedFixed_DiscardsRecoveryForStaleFailedRun(t *testing.T) {
svc, _ := newTestServiceWithBus(t)
ctx := context.Background()
createTestAgent(t, svc, "ws-1", "agent-stale-run")
staleTaskID := "stale-task"
insertSyntheticTask(t, svc, staleTaskID, "ws-1", "agent-stale-run")
failedRun := queueAndReadRun(t, svc, "agent-stale-run", staleTaskID)
if _, err := svc.HandleAgentFailure(ctx, failedRun, "boom"); err != nil {
t.Fatalf("handle failure: %v", err)
}
// Two more failures (on other tasks) to cross the default threshold
// of 3 and auto-pause the agent, with the stale task's failed run
// captured in the pause snapshot.
autoPauseAgent(t, svc, "ws-1", "agent-stale-run", 2)
// Precondition: the pause snapshot must include the stale task,
// otherwise the negative assertions below would pass vacuously (there
// would be nothing to discard).
var preCount int
if err := svc.RepoForTest().ReaderDB().Get(&preCount,
`SELECT COUNT(*) FROM office_agent_pause_recoveries WHERE agent_id = ? AND task_id = ?`,
"agent-stale-run", staleTaskID,
); err != nil {
t.Fatalf("query pre-fix snapshot: %v", err)
}
if preCount != 1 {
t.Fatalf(
"test setup error: expected exactly one recovery row for stale task, found %d",
preCount,
)
}
// A newer run for the same task has already finished (e.g. a manual
// retry that landed while the agent was paused), superseding the
// failed run the recovery snapshot points at.
supersedingRunID := staleTaskID + "-superseding-run"
supersedingRequestedAt := time.Now().UTC().Add(time.Hour)
svc.ExecSQL(t,
`INSERT INTO runs (id, agent_profile_id, reason, payload, status, requested_at, finished_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
supersedingRunID, "agent-stale-run", service.RunReasonTaskAssigned,
mustMarshalJSON(map[string]string{"task_id": staleTaskID}),
service.RunStatusFinished, supersedingRequestedAt, supersedingRequestedAt,
)
if err := svc.MarkAgentPausedFixed(ctx, "user-1", "agent-stale-run"); err != nil {
t.Fatalf("mark fixed: %v", err)
}
runs, err := svc.ListRuns(ctx, "ws-1")
if err != nil {
t.Fatalf("list runs: %v", err)
}
for _, run := range runs {
if run.Reason == service.RunReasonManualResumeAfterFailure &&
taskIDFromPayload(t, run.Payload) == staleTaskID {
t.Fatalf("queued recovery run for stale task %s", staleTaskID)
}
}
var recoveryCount int
if err := svc.RepoForTest().ReaderDB().Get(&recoveryCount,
`SELECT COUNT(*) FROM office_agent_pause_recoveries WHERE agent_id = ? AND task_id = ?`,
"agent-stale-run", staleTaskID,
); err != nil {
t.Fatalf("query pause recoveries: %v", err)
}
if recoveryCount != 0 {
t.Fatalf("expected recovery row for stale task to be deleted, found %d", recoveryCount)
}
}
// Threshold-agnostic: the fix must not assume the default threshold
// of 3. A per-agent override to a different value must still recover.
func TestMarkAgentPausedFixed_ThresholdAgnostic(t *testing.T) {
@@ -0,0 +1,59 @@
package service_test
import (
"context"
"testing"
"github.com/kandev/kandev/internal/office/models"
"github.com/kandev/kandev/internal/office/service"
)
// TestMarkAgentPausedFixed_LeavesInboxUndismissedWhenClearFails pins the
// AC-OFFICE-RUNTIME-001.10 ordering: MarkAgentPausedFixed must not dismiss
// the inbox entry until clearAutoPause actually succeeds. A trigger blocks
// the exact UPDATE UnpauseAgentIfCurrent issues, forcing clearAutoPause to
// return an error deterministically (no goroutine or real race needed) so
// MarkAgentPausedFixed returns before reaching dismiss, counter reset, or
// task recovery.
func TestMarkAgentPausedFixed_LeavesInboxUndismissedWhenClearFails(t *testing.T) {
svc, _ := newTestServiceWithBus(t)
ctx := context.Background()
createTestAgent(t, svc, "ws-1", "agent-clear-fails")
autoPauseAgent(t, svc, "ws-1", "agent-clear-fails", 3)
svc.ExecSQL(t, `
CREATE TRIGGER block_unpause
BEFORE UPDATE ON agent_profiles
WHEN NEW.status = 'idle' AND OLD.status = 'paused'
BEGIN
SELECT RAISE(ABORT, 'injected: unpause write blocked');
END
`)
if err := svc.MarkAgentPausedFixed(ctx, "user-1", "agent-clear-fails"); err == nil {
t.Fatal("MarkAgentPausedFixed = nil, want an error from the blocked unpause write")
}
dismissed, err := svc.IsInboxItemDismissed(
ctx, "user-1", service.InboxKindAgentPausedAfterFails, "agent-clear-fails",
)
if err != nil {
t.Fatalf("check dismissed: %v", err)
}
if dismissed {
t.Fatal("inbox entry was dismissed despite the clear failing; " +
"dismiss must happen only after a successful clearAutoPause")
}
agent, err := svc.GetAgentInstance(ctx, "agent-clear-fails")
if err != nil {
t.Fatalf("get agent: %v", err)
}
if agent.Status != models.AgentStatusPaused {
t.Fatalf("agent status = %q, want still paused (unpause write was blocked)", agent.Status)
}
if agent.ConsecutiveFailures == 0 {
t.Fatal("consecutive-failure counter was reset despite the clear failing")
}
}
@@ -0,0 +1,132 @@
package service
import (
"context"
"testing"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
settingsstore "github.com/kandev/kandev/internal/agent/settings/store"
"github.com/kandev/kandev/internal/office/models"
"github.com/kandev/kandev/internal/office/repository/sqlite"
)
// newClearAutoPauseTestRepo opens a minimal in-memory repo: clearAutoPause
// only reaches agent_instances, so this skips the tasks/workflow schema
// newTestService (base_test.go, service_test package) sets up.
func newClearAutoPauseTestRepo(t *testing.T) *sqlite.Repository {
t.Helper()
db, err := sqlx.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
db.SetMaxOpenConns(1)
t.Cleanup(func() { _ = db.Close() })
if _, _, err := settingsstore.Provide(db, db, nil); err != nil {
t.Fatalf("settings store init: %v", err)
}
repo, err := sqlite.NewWithDB(db, db, nil)
if err != nil {
t.Fatalf("new repo: %v", err)
}
return repo
}
// TestClearAutoPause_AbortsWhenNewerAutoPauseLands pins the retry-abort
// guard added alongside the CAS unpause write (AC-OFFICE-RUNTIME-001.9):
// a clearAutoPause call holding a stale pause_reason snapshot must not
// retry against a newer, unobserved auto-pause reason it finds on reload.
//
// This drives clearAutoPause directly with a hand-built stale snapshot
// instead of racing goroutines against the exported MarkAgentPausedFixed
// entry point, which always re-reads the agent fresh and so cannot
// reproduce the read-then-CAS window from the outside.
func TestClearAutoPause_AbortsWhenNewerAutoPauseLands(t *testing.T) {
ctx := context.Background()
repo := newClearAutoPauseTestRepo(t)
svc := &Service{repo: repo}
agent := &models.AgentInstance{
ID: "agent-cas-abort",
WorkspaceID: "ws-1",
Name: "cas-abort",
Role: models.AgentRoleWorker,
Status: models.AgentStatusIdle,
}
if err := repo.CreateAgentInstance(ctx, agent); err != nil {
t.Fatalf("create agent: %v", err)
}
if err := repo.UpdateAgentStatusFields(ctx, agent.ID, "paused", "Auto-paused: reason1"); err != nil {
t.Fatalf("pause agent: %v", err)
}
// The snapshot a caller (MarkAgentPausedFixed) would have read before a
// second, unrelated auto-pause lands underneath it.
stale := &models.AgentInstance{
ID: agent.ID,
WorkspaceID: agent.WorkspaceID,
Status: models.AgentStatusPaused,
PauseReason: "Auto-paused: reason1",
}
if err := repo.UpdateAgentStatusFields(ctx, agent.ID, "paused", "Auto-paused: reason2"); err != nil {
t.Fatalf("re-pause agent: %v", err)
}
if err := svc.clearAutoPause(ctx, stale); err == nil {
t.Fatal("clearAutoPause = nil, want an error aborting the stale clear")
}
got, err := repo.GetAgentInstance(ctx, agent.ID)
if err != nil {
t.Fatalf("GetAgentInstance: %v", err)
}
if got.Status != models.AgentStatusPaused || got.PauseReason != "Auto-paused: reason2" {
t.Fatalf("status/reason = %q/%q, want paused/%q (newer pause left intact by the abort)",
got.Status, got.PauseReason, "Auto-paused: reason2")
}
}
// TestClearAutoPause_SucceedsWhenPauseReasonStillMatches is the control:
// the same stale-snapshot shape but with the observed reason still current
// must clear normally, so the abort branch above is proven to be reason-
// specific rather than a general clearAutoPause regression.
func TestClearAutoPause_SucceedsWhenPauseReasonStillMatches(t *testing.T) {
ctx := context.Background()
repo := newClearAutoPauseTestRepo(t)
svc := &Service{repo: repo}
agent := &models.AgentInstance{
ID: "agent-cas-match",
WorkspaceID: "ws-1",
Name: "cas-match",
Role: models.AgentRoleWorker,
Status: models.AgentStatusIdle,
}
if err := repo.CreateAgentInstance(ctx, agent); err != nil {
t.Fatalf("create agent: %v", err)
}
if err := repo.UpdateAgentStatusFields(ctx, agent.ID, "paused", "Auto-paused: reason1"); err != nil {
t.Fatalf("pause agent: %v", err)
}
snapshot := &models.AgentInstance{
ID: agent.ID,
WorkspaceID: agent.WorkspaceID,
Status: models.AgentStatusPaused,
PauseReason: "Auto-paused: reason1",
}
if err := svc.clearAutoPause(ctx, snapshot); err != nil {
t.Fatalf("clearAutoPause: %v", err)
}
got, err := repo.GetAgentInstance(ctx, agent.ID)
if err != nil {
t.Fatalf("GetAgentInstance: %v", err)
}
if got.Status != models.AgentStatusIdle || got.PauseReason != "" {
t.Fatalf("status/reason = %q/%q, want idle/\"\" (matching reason clears)",
got.Status, got.PauseReason)
}
}
@@ -0,0 +1,113 @@
---
created: 2026-09-17
status: done
requirements:
- REQ-OFFICE-RUNTIME-001
system_design:
- ../../specs/office/system-design/runtime-01.md
- ../../specs/office/system-design/runtime-02.md
legacy_specs: []
---
# Implementation Plan: Office Mark fixed atomicity
## Overview
**Mark fixed** on an `agent_paused_after_failures` inbox entry clears the
agent's `pause_reason`, resets `consecutive_failures`, and re-queues the
affected tasks. When a second, unrelated auto-pause lands on the same agent
between the moment Mark fixed reads the agent and the moment it writes the
clear, the write used to succeed unconditionally: it clobbered the newer
pause's `pause_reason`, then went on to reset the counter and recover tasks
from the *first* pause's stale snapshot, silently discarding the second
pause's cause.
This plan closes that window with a compare-and-set write plus a
retry-abort guard, and dismisses the inbox entry only once the clear it
guards has actually succeeded. It does not touch the rest of the recovery
flow (dismissal semantics for `agent_run_failed`, reassignment, or the
counter-reset UX) and does not redesign it.
## Scope
### In scope
- A compare-and-set write for the unpause transition (`paused` -> `idle`)
gated on both `status` and the `pause_reason` the caller observed, closing
the read-then-write window.
- A retry-abort guard in the service-layer clear loop: when the CAS write is
refused and a reload shows the agent still paused with a *different*
reason than the caller started with, the call aborts instead of retrying
against the newer reason.
- Reordering `MarkAgentPausedFixed` so the inbox entry is dismissed only
after its clear succeeds, leaving an aborted call's entry retryable.
- Regression coverage for the compare-and-set write and the abort guard.
### Out of scope
- Any change to `agent_run_failed`'s dismiss-then-retry flow, reassignment,
or the counter-reset semantics AC-OFFICE-RUNTIME-001.5 already covers.
- An event or activity entry for a refused Mark fixed call.
- The unrelated `office_agent_recovery` status-transition control (a
different action on a different endpoint; see
[`office-agent-recovery`](../office-agent-recovery/plan.md)).
## Technical approach
### Compare-and-set unpause write
`UnpauseAgentIfCurrent` (`internal/office/repository/sqlite/agents.go`)
updates `agent_instances` with `WHERE status = 'paused' AND pause_reason = ?`
instead of `WHERE status = 'paused'` alone, so a write built from a stale
`pause_reason` affects zero rows instead of clobbering a newer one.
### Retry-abort on a newer, unobserved reason
`clearAutoPause` (`internal/office/service/failure.go`) captures
`originalReason` before its CAS attempt. When the attempt reports no row
changed, it reloads the agent: if the reload is no longer auto-paused, the
clear is treated as already done; if it is still paused with the *same*
reason, the loop retries (handles a same-reason status flip between
`paused` and `stopped`); if it is still paused with a *different* reason,
the call aborts with an error rather than adopting it. The newer pause stays
untouched and reachable by its own Mark fixed.
### Dismiss-after-clear ordering
`MarkAgentPausedFixed` previously inserted the `inbox_dismissals` row before
clearing the pause. It now clears first and dismisses only on success, so an
aborted clear leaves the entry visible and the call retryable instead of
being silently swallowed by an already-recorded dismissal.
## Tests
| Acceptance criterion | Evidence |
| --- | --- |
| `AC-OFFICE-RUNTIME-001.9` | `TestUnpauseAgentIfCurrent_RefusesWhenPauseReasonChanged` (repository CAS refusal) and `TestClearAutoPause_AbortsWhenNewerAutoPauseLands` (service-layer abort, `consecutive_failures` untouched) |
| `AC-OFFICE-RUNTIME-001.10` | `TestClearAutoPause_AbortsWhenNewerAutoPauseLands` asserts the newer `pause_reason` survives the aborted call; `TestClearAutoPause_SucceedsWhenPauseReasonStillMatches` is the matching-reason control proving the abort is reason-specific, not a general regression |
## Verification results
Delivered on PR [#3734](https://github.com/kdlbs/kandev/pull/3734), commits
`9d1f1975e` (CAS unpause write) and `4bcdbef71` (retry-abort guard and
dismiss-after-clear ordering). `go test -tags fts5 ./internal/office/service/...
./internal/office/repository/sqlite/...` passes except for the pre-existing,
unrelated `TestMigrate_PriorityIdempotent` FTS backfill failure (reproduces
identically on the branch base commit, before this plan's changes).
## Risks
- `clearAutoPause`'s loop caps at two attempts. A third auto-pause landing
between the second attempt's read and write is not retried further; the
call fails closed (an error), which is the same outcome as the guarded
abort case, not a silent clobber.
- The compare-and-set predicate is `status = 'paused' AND pause_reason = ?`.
A caller that races the *stopped* clear path
(`ClearAgentPauseReasonIfCurrent`, gated on `status` alone) is unaffected
by this plan - that path never held the unpause clobber this plan closes,
because a `stopped` agent's pause_reason is not the multi-writer contended
field the auto-pause scheduler mutates.
## Work orders
- [x] [Task 01: CAS unpause write and retry-abort guard](task-01-cas-unpause-retry-abort.md)
@@ -0,0 +1,126 @@
---
id: "01-cas-unpause-retry-abort"
title: "CAS unpause write and retry-abort guard"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-OFFICE-RUNTIME-001
acceptance_criteria:
- AC-OFFICE-RUNTIME-001.9
- AC-OFFICE-RUNTIME-001.10
system_design:
- ../../specs/office/system-design/runtime-01.md
- ../../specs/office/system-design/runtime-02.md
---
# Task 01: CAS unpause write and retry-abort guard
## Summary
Close the TOCTOU window in **Mark fixed** on `agent_paused_after_failures`:
a second, unrelated auto-pause landing between the read and the write could
previously be silently clobbered, letting the caller reset the counter and
recover tasks against the wrong pause. Gate the unpause write on the
observed `pause_reason`, abort the service-layer retry instead of adopting
a newer reason it never observed, and dismiss the inbox entry only after a
successful clear.
## In scope
- `UnpauseAgentIfCurrent`'s compare-and-set predicate on `pause_reason` in
addition to `status`.
- `clearAutoPause`'s retry-abort branch: still-paused-with-a-different-reason
on reload aborts rather than retrying.
- Reordering `MarkAgentPausedFixed` to dismiss the inbox entry after the
clear succeeds, not before.
- Regression tests for the CAS refusal (repository layer) and the abort
branch (service layer, both the abort case and a matching-reason control).
## Out of scope
- `agent_run_failed`'s dismiss-then-retry ordering (unaffected - it clears a
session, not a shared `pause_reason` field).
- Reassignment, the counter-reset UX, or any change to the transition table
the unrelated `office-agent-recovery` control uses.
- A third retry attempt beyond `clearAutoPause`'s existing two-attempt cap.
## Acceptance
- `UnpauseAgentIfCurrent` returns `changed = false` and leaves the row
untouched when `pause_reason` no longer matches the caller's value, even
though `status` is still `paused`.
- `clearAutoPause` returns an error, leaves `pause_reason` at the newer
value, and does not proceed to reset `consecutive_failures` or dismiss the
inbox entry when a reload shows the agent still paused with a reason the
call never observed.
- `clearAutoPause` still succeeds and clears the pause when the reload's
reason matches what the call started with.
## Verification
```bash
(cd apps/backend && go test -tags fts5 -count=1 -run TestUnpauseAgentIfCurrent_RefusesWhenPauseReasonChanged ./internal/office/repository/sqlite/)
(cd apps/backend && go test -tags fts5 -count=1 -run TestClearAutoPause ./internal/office/service/)
(cd apps/backend && go test -tags fts5 -count=1 -run 'TestMarkAgentPausedFixed|TestMarkAgentRunFailedFixed' ./internal/office/service/)
make -C apps/backend lint
```
## Files likely touched
- `apps/backend/internal/office/repository/sqlite/agents.go`
- `apps/backend/internal/office/repository/sqlite/agents_test.go`
- `apps/backend/internal/office/service/failure.go`
- `apps/backend/internal/office/service/pause_reason_cas_internal_test.go`
## Dependencies
None.
## Risks
- The abort branch is only reachable when the agent is still `paused` with
a changed reason; a concurrent transition to `stopped` or `idle` takes the
"no longer auto-paused, treat as done" branch instead, which this task
does not change.
- `clearAutoPauseAttempt`'s two code paths (`unpauseAgentIfCurrent` for a
`paused` agent, `clearPauseReasonIfCurrent` for anything else) only the
first is exercised by the abort scenario, since a currently-`paused` agent
is the precondition for `MarkAgentPausedFixed`'s auto-pause branch.
## Parallelism
`parallel-safe`
Touches only `internal/office/repository/sqlite/agents.go` and
`internal/office/service/failure.go`; disjoint from any other in-flight
Office work order.
## Inputs
- `docs/specs/office/requirements/runtime.md`, `REQ-OFFICE-RUNTIME-001`
(`AC-OFFICE-RUNTIME-001.9`, `.10`).
- `docs/specs/office/system-design/runtime-01.md`, "Recovery hooks > Mark
fixed = dismiss + retry" and "Failure modes".
- `docs/specs/office/system-design/runtime-02.md`, "Migrated source detail >
Scenarios".
- `apps/backend/internal/office/service/failure.go`,
`MarkAgentPausedFixed` / `clearAutoPause` / `clearAutoPauseAttempt`.
- `apps/backend/internal/office/repository/sqlite/agents.go`,
`UnpauseAgentIfCurrent`.
## Results
Implemented in commits `9d1f1975e` (CAS unpause write on `pause_reason`,
plus `TestUnpauseAgentIfCurrent_RefusesWhenPauseReasonChanged`) and
`4bcdbef71` (retry-abort guard and dismiss-after-clear reorder) on PR
[#3734](https://github.com/kdlbs/kandev/pull/3734). The retry-abort branch
shipped in `4bcdbef71` without a dedicated regression test; this task adds
`TestClearAutoPause_AbortsWhenNewerAutoPauseLands` (verified to fail against
the pre-guard code) and its matching-reason control
`TestClearAutoPause_SucceedsWhenPauseReasonStillMatches`, both driving the
unexported `clearAutoPause` directly from an internal-package test against a
minimal in-memory repo, since the exported `MarkAgentPausedFixed` always
re-reads the agent fresh and cannot reproduce the read-then-CAS window from
the outside.
@@ -27,6 +27,8 @@ When an agent run fails mid-turn (invalid model, auth failure, malformed respons
- **AC-OFFICE-RUNTIME-001.6:** Changing `assignee_agent_instance_id` on a task fires the existing reactivity pipeline, which queues a fresh `task_assigned` wakeup for the new agent.
- **AC-OFFICE-RUNTIME-001.7:** The existing staleness check (`recovery-reliability` spec) cancels the prior wakeup for the (task, **old** agent) since the assignee has changed.
- **AC-OFFICE-RUNTIME-001.8:** Any per-task `agent_run_failed` inbox entry tied to the old (task, agent) auto-dismisses - the failure is no longer actionable on this task.
- **AC-OFFICE-RUNTIME-001.9:** If a second auto-pause replaces the agent's `pause_reason` after **Mark fixed** on `agent_paused_after_failures` has read it but before its clear commits, the clear is refused and the call aborts instead of adopting the newer reason: `consecutive_failures` is not reset and no wakeup is re-queued.
- **AC-OFFICE-RUNTIME-001.10:** A **Mark fixed** call aborted under AC-OFFICE-RUNTIME-001.9 does not dismiss the inbox entry - it stays actionable for the still-paused agent, and is dismissed only once a clear against the then-current `pause_reason` succeeds.
## System design
@@ -91,10 +91,12 @@ For `agent_run_failed`:
3. Re-queue a wakeup for that (task, agent) with reason `manual_resume_after_failure`.
For `agent_paused_after_failures`:
1. Insert into `inbox_dismissals`.
2. Clear the agent's `pause_reason`, reset `consecutive_failures` to zero. (Counter reset is the user saying "I fixed the cause; start over".)
1. Compare-and-set clear of the agent's `pause_reason`, reset `consecutive_failures` to zero. (Counter reset is the user saying "I fixed the cause; start over".) The service reads the expected reason at the start of the request. If a second auto-pause replaces it before the conditional write, the clear is refused and the call aborts rather than adopting the newer reason (`AC-OFFICE-RUNTIME-001.9`).
2. Insert into `inbox_dismissals`, only after step 1 succeeds. An aborted clear leaves the entry actionable for the still-paused agent (`AC-OFFICE-RUNTIME-001.10`).
3. Re-queue wakeups for every (task, agent) listed on the entry with reason `manual_resume_after_failure`.
See [part 2](runtime-02.md#migrated-source-detail) for the compare-and-set scenario detail.
There is no separate "Dismiss without retry" affordance. If the user wants to silence the inbox without re-running the task, they reassign the task to a different agent - that's the explicit recovery path described below.
#### Reassignment as the multi-provider failover path
@@ -275,6 +277,7 @@ Recovery and runtime-action authorization splits across three actors: human user
- **Transient network failure**: treated as terminal in v1. User clicks Resume / Mark fixed to retry. Future classifier may auto-retry.
- **Auto-paused agent's wakeup fires**: scheduler refuses to claim it; behaviour identical to a manually-paused agent.
- **Reassignment during failure**: cancels the (task, old agent) wakeup via the existing staleness check; auto-dismisses `agent_run_failed` for (task, old agent). Does not unpause the old agent.
- **Second auto-pause lands during Mark fixed**: the compare-and-set clear on `pause_reason` is refused; the call aborts instead of retrying against the newer reason. `consecutive_failures` is unchanged, no wakeup is queued, and the inbox entry is not dismissed - the newer pause remains actionable.
## Persistence guarantees
@@ -30,7 +30,8 @@ This design preserves the technical source detail for `REQ-OFFICE-RUNTIME-001` d
- **GIVEN** an agent below its failure threshold with `cooldown_sec > 0`, **WHEN** a run fails and `HandleAgentFailure` marks it terminal, **THEN** `office_agent_runtime.last_run_finished_at` is stamped the same as after a successful run, and the heartbeat gate blocks the agent's next fire (for any task) until `cooldown_sec` has elapsed.
- **GIVEN** an auto-paused agent, **WHEN** the scheduler tick attempts to claim one of its wakeups, **THEN** the wakeup is not claimed; behaviour is identical to a manually-paused agent.
- **GIVEN** an `agent_run_failed` inbox entry, **WHEN** the user clicks Mark fixed, **THEN** an `inbox_dismissals` row is inserted, the (task, agent) session is cleared from `FAILED` to `IDLE`, and a new wakeup is queued with reason `manual_resume_after_failure`.
- **GIVEN** an `agent_paused_after_failures` inbox entry, **WHEN** the user clicks Mark fixed, **THEN** the agent's `pause_reason` clears, `consecutive_failures` resets to zero, and a wakeup with reason `manual_resume_after_failure` is queued for every (task, agent) listed on the entry.
- **GIVEN** an `agent_paused_after_failures` inbox entry, **WHEN** the user clicks Mark fixed and the agent's `pause_reason` still matches the value that the service read at the start of the request, **THEN** the compare-and-set clear succeeds, `consecutive_failures` resets to zero, the entry is dismissed, and a wakeup with reason `manual_resume_after_failure` is queued for every (task, agent) listed on the entry (`AC-OFFICE-RUNTIME-001.9`, `AC-OFFICE-RUNTIME-001.10`).
- **GIVEN** an `agent_paused_after_failures` inbox entry, **WHEN** a second auto-pause overwrites the agent's `pause_reason` after the service read and before the conditional write, **THEN** the compare-and-set clear is refused, the call aborts instead of adopting the newer reason, `consecutive_failures` is not reset, no wakeup is queued, and the inbox entry is not dismissed so it stays actionable for the still-paused agent (`AC-OFFICE-RUNTIME-001.9`, `AC-OFFICE-RUNTIME-001.10`).
- **GIVEN** a failed task assigned to an agent, **WHEN** the user reassigns the task to a different agent, **THEN** the prior (task, old agent) wakeup is cancelled by the staleness check, the (task, old agent) `agent_run_failed` inbox entry auto-dismisses, the old agent's `consecutive_failures` counter is NOT reset, and a fresh `task_assigned` wakeup queues for the new agent.
- **GIVEN** an agent runtime call without a valid `Bearer` token, **WHEN** the request hits any `/runtime/*` endpoint, **THEN** the response is `401 Unauthorized` with `{"error": "missing runtime token"}` or `{"error": "invalid runtime token"}`.
- **GIVEN** an agent run with `Capabilities.CanCreateSubtasks = false`, **WHEN** the agent calls `POST /runtime/tasks/:id/subtasks`, **THEN** the response is `403 Forbidden` (`ErrCapabilityDenied`) and a `runtime.denied` event is appended to `office_run_events` with `action=create_subtask`.