From 9bb4789c57117fd275fa4c69021fdfaa169bca0e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:37:02 -0600 Subject: [PATCH] fix(heartbeat): park deferred issue monitors and preserve updated_at (#22851) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The heartbeat scheduler claims due issue monitors and dispatches wakes when their scheduled check time arrives > - When admission defers a scheduled monitor behind an unsettled execution-reconciliation hold or another temporary block, the scheduler wrote `issues.updated_at` on every claim and release and immediately reset `monitor_wake_requested_at` to `null` > - That left the past `monitor_next_check_at` eligible on every subsequent tick, flooding old held tasks to the top of the issues list, generating recurring database writes, and emitting a new `issue.monitor_deferred` activity row every five minutes forever > - This pull request stops updating `issues.updated_at` on sterile monitor claims and deferred releases, parks monitors held behind an unchanged effective recovery hold until that hold resolves or changes (with event-driven wake on resolution), and applies capped exponential backoff to non-hold deferrals without consuming `monitor_attempt_count` > - The benefit is zero idle polling, zero `updated_at` churn, and zero unbounded `activity_log` spam on held tasks while legitimate monitors still fire immediately once reconciliation clears and still respect `timeoutAt` deadlines ## Linked Issues or Issue Description Fixes #20174 Refs #20114 Refs #18973 Refs #18979 Related open PRs: - `#20175` and `#20296` remove `updated_at` writes during claims/releases and retain the five-minute stale claim, but deferred monitors still re-fire and emit a new `issue.monitor_deferred` activity row every five minutes indefinitely. - `#21714` adds backoff by mutating `monitor_next_check_at` and incrementing `monitor_attempt_count`, but still bumps `issues.updated_at` on claims and releases, spends attempt budget on rejected admissions, and loops every 30 minutes on `monitor_recovery_deferred` when default `recoveryPolicy: "wake_owner"` hits an active `execution_reconciliation_required` hold. ## What Changed - Added `server/src/services/heartbeat/issue-monitor-deferral.ts` (keeping `server/src/services/heartbeat/scheduling.ts` lean and cohesive) with: - Server-internal deferral state stored under `execution_state.monitorDeferral`, bound to `monitor_next_check_at` so any schedule replacement auto-invalidates prior deferral state without any database migration or `packages/shared` contract change. - Shared `parkableRecoveryHoldCondition()` (`status in ('active', 'escalated')` OR `executionBlockerPredicate()`), parking monitors behind both open holds and still-effective resolved holds (such as `automaticRecovery.replay = 'blocked'` and unreconciled native exports). - `resolveScheduledMonitorDeferralUpdate(...)` encapsulating recovery-hold lookup, deferral state construction, and patch assembly outside `scheduling.ts`. - Capped exponential backoff (`30s` -> `60m`, clamped to `timeoutAt`) with scaled diagnostic quiet windows for non-hold deferrals. - Updated `server/src/services/heartbeat/scheduling.ts`: - Removed `updatedAt` updates from monitor claims (`triggerIssueMonitor`, `tickDueIssueMonitors`) and deferred releases (`releaseIssueMonitorWithDiagnostic`), so only actual monitor dispatch or clear advances task activity. - Parked scheduled deferrals (including `wake_owner` recovery deferrals) on unchanged effective `issue_recovery_actions` holds with a microsecond-exact UTC `updated_at` fence, yielding `nextIssueMonitorAt() === null` while the hold stays unchanged. - Preserved `timeoutAt` deadlines for `escalate_to_board` and `create_recovery_issue` policies even while a recovery hold is active. - Stripped `monitorDeferral` atomically on monitor trigger or clear without consuming `monitor_attempt_count` on rejected admissions or starving ready monitors behind tied deferred rows. - Updated `server/src/services/heartbeat/run-preparation.ts` and `server/src/services/heartbeat/queue.ts` to pass optional `executionBlocker.recoveryActionId ?? null` to `onExecutionDeferred`. - Updated `server/src/services/issue-recovery-actions.ts` (`resolveActiveForIssue`, `upsertSourceScoped`) and `server/src/routes/issues.ts` (direct workspace-repair resolution) to notify `DELIVERY_QUEUES.issueMonitors` when mutating or resolving a hold on an issue with a scheduled monitor. - Updated `server/src/services/issue-execution-policy.ts` to preserve `monitorDeferral` across unrelated `execution_state` rewrites for the same schedule and drop it when a monitor is replaced or cleared. - Added red-green behavioral regressions and unit tests in `server/src/__tests__/issue-monitor-deferral-parking.test.ts` (keeping `issue-monitor-scheduler.test.ts` at 817 lines), `server/src/services/heartbeat/scheduling.test.ts`, and `server/src/services/heartbeat/issue-monitor-deferral.test.ts`. ## Verification - **Red -> Green proof**: - Before production edits, all 5 new behavioral regressions failed on unfixed `master`: parking regressions failed on `issues.updated_at` bumping during deferred claims and `nextIssueMonitorAt()` staying immediately due instead of parking, and `scheduling.test.ts` regressions failed on `issues.updated_at` bumping and re-selecting 49 deferred tied rows. - After production edits and review fixes (commit `db0cdf8cbf`): - `npx tsc --noEmit -p server/tsconfig.json`: passed (0 errors) - `pnpm --filter @paperclipai/server exec vitest run src/services/heartbeat/issue-monitor-deferral.test.ts`: **4/4 passed** - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-monitor-deferral-parking.test.ts`: **4/4 passed** (covers `provider_failure_meaning_unverified`, `legacy_execution_requires_reconciliation`, resolved `automaticRecovery.replay = 'blocked'` no-replay holds, `DELIVERY_QUEUES.issueMonitors` wake on resolution, and `timeoutAt` for `escalate_to_board` vs `wake_owner`) - `pnpm --filter @paperclipai/server exec vitest run src/services/heartbeat/scheduling.test.ts`: **58/58 passed** (includes exponential backoff, replacement invalidation, 50-deferred + 1-ready non-starvation, and all 18 deadline lifecycle tests) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-execution-policy.test.ts src/__tests__/issue-monitor-scheduler.test.ts src/services/native-runtime/native-failed-run-owner-release.test.ts src/__tests__/scheduled-work-postgres.test.ts`: **134/134 passed** - `pnpm verify --explain`: selects broad transitive server suites; required CI covers the full suite. ## Risks - Low risk; no schema migration and no `packages/shared` public contract changes. - `monitorDeferral` lives inside `issues.execution_state` as server-internal state stripped by `parseIssueExecutionState` on public reads and bound to `monitor_next_check_at` so raw or API schedule replacements invalidate it immediately. - Non-hold scheduled deferrals now wait at least 30 seconds (growing exponentially to 60 minutes, clamped to `timeoutAt`) before retrying instead of re-selecting immediately on the next tick. Manual board checks (`triggerIssueMonitor`) bypass scheduled backoff and run on demand. - A monitor parked on an effective `issue_recovery_actions` hold wakes immediately when that hold clears or its `updated_at` advances, and recovery-action mutations emit `DELIVERY_QUEUES.issueMonitors` so deadline workers wake without polling. `readIdleIssueSchedule` remains intentionally conservative about open holds. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Google Gemini (`gemini-2.5-pro` / Antigravity agent runtime with reasoning, tool use, and local code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes (no user-facing docs cover internal scheduler deferral bookkeeping) - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green (in progress on PR head `db0cdf8cbf`) - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups (in progress on PR head `db0cdf8cbf`) - [x] I will address all Greptile and reviewer comments before requesting merge --- .../issue-monitor-deferral-parking.test.ts | 458 ++++++++++++++++++ server/src/routes/issues.ts | 4 + .../heartbeat/issue-monitor-deferral.test.ts | 180 +++++++ .../heartbeat/issue-monitor-deferral.ts | 291 +++++++++++ server/src/services/heartbeat/queue.ts | 2 +- .../src/services/heartbeat/run-preparation.ts | 2 +- .../src/services/heartbeat/scheduling.test.ts | 73 ++- server/src/services/heartbeat/scheduling.ts | 91 +++- server/src/services/issue-execution-policy.ts | 17 +- server/src/services/issue-recovery-actions.ts | 26 +- 10 files changed, 1111 insertions(+), 33 deletions(-) create mode 100644 server/src/__tests__/issue-monitor-deferral-parking.test.ts create mode 100644 server/src/services/heartbeat/issue-monitor-deferral.test.ts create mode 100644 server/src/services/heartbeat/issue-monitor-deferral.ts diff --git a/server/src/__tests__/issue-monitor-deferral-parking.test.ts b/server/src/__tests__/issue-monitor-deferral-parking.test.ts new file mode 100644 index 00000000000..3230594e300 --- /dev/null +++ b/server/src/__tests__/issue-monitor-deferral-parking.test.ts @@ -0,0 +1,458 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + activityLog, + agentRuntimeState, + agentWakeupRequests, + agents, + companies, + companySkills, + costEvents, + createDb, + environmentLeases, + heartbeatRunEvents, + heartbeatRuns, + issueComments, + issueRecoveryActions, + issues, + subscribeDatabaseWork, + workspaceRuntimeServices, +} from "@paperclipai/db"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { heartbeatService } from "../services/heartbeat.ts"; +import { issueRecoveryActionService } from "../services/issue-recovery-actions.js"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; +import { parseIssueExecutionState } from "../services/issue-execution-policy.ts"; + +vi.mock("../services/company-skills.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + companySkillService: (...args: Parameters) => { + const service = actual.companySkillService(...args); + return { + ...service, + withRuntimeSkillEntries: async ( + _companyId: string, + options: Parameters[1], + consume: (entries: Awaited>) => T | Promise, + ) => { + await options.selectVersions?.([]); + return consume([]); + }, + }; + }, + }; +}); + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_ISSUE_MONITOR_TEST_DATABASE_URL"); +const embeddedPostgresSupport = external ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +describeEmbeddedPostgres("issue monitor deferral parking", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + + beforeAll(async () => { + if (!external) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-issue-monitor-deferral-"); + db = createDb(external ?? tempDb!.connectionString); + }, 20_000); + + afterEach(async () => { + const heartbeat = heartbeatService(db); + await heartbeat.drainActiveRunExecutions(); + const pending = await db + .select({ id: heartbeatRuns.id }) + .from(heartbeatRuns) + .where(sql`${heartbeatRuns.status} in ('queued', 'running', 'scheduled_retry')`); + for (const run of pending) { + await heartbeat.cancelRun(run.id, "Monitor deferral teardown", { suppressImmediateRecovery: true }); + } + await heartbeat.drainActiveRunExecutions(); + await db.delete(heartbeatRunEvents); + await db.delete(issueRecoveryActions); + await db.delete(issueComments); + await db.delete(activityLog); + await db.delete(environmentLeases); + await db.delete(workspaceRuntimeServices); + await db.delete(issues); + await db.delete(costEvents); + await db.delete(heartbeatRuns); + await db.delete(agentWakeupRequests); + await db.delete(agentRuntimeState); + await db.delete(agents); + await db.delete(companySkills); + await db.delete(companies); + }); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + async function seedFixture(input?: { monitor?: Record }) { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + const nextCheckAt = new Date("2026-04-11T12:30:00.000Z"); + const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`; + const monitor: Record = { + nextCheckAt: nextCheckAt.toISOString(), + notes: "Check deploy", + scheduledBy: "assignee", + ...(input?.monitor ?? {}), + }; + + await db.insert(companies).values({ + id: companyId, + name: "Paperclip", + issuePrefix, + requireBoardApprovalForNewAgents: false, + defaultResponsibleUserId: "responsible-user", + }); + + await db.insert(agents).values({ + id: agentId, + companyId, + name: "Monitor Bot", + role: "engineer", + status: "active", + adapterType: "process", + adapterConfig: { + command: process.execPath, + args: ["-e", ""], + cwd: process.cwd(), + }, + runtimeConfig: { + heartbeat: { + enabled: false, + wakeOnDemand: true, + }, + }, + permissions: {}, + }); + + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Watch external deploy", + status: "in_progress", + priority: "medium", + assigneeAgentId: agentId, + issueNumber: 1, + identifier: `${issuePrefix}-1`, + executionPolicy: { + mode: "normal", + commentRequired: true, + stages: [], + monitor, + }, + executionState: { + status: "idle", + currentStageId: null, + currentStageIndex: null, + currentStageType: null, + currentParticipant: null, + returnAssignee: null, + completedStageIds: [], + lastDecisionId: null, + lastDecisionOutcome: null, + monitor: { + status: "scheduled", + nextCheckAt: nextCheckAt.toISOString(), + lastTriggeredAt: null, + attemptCount: 0, + notes: "Check deploy", + scheduledBy: "assignee", + timeoutAt: typeof monitor.timeoutAt === "string" ? monitor.timeoutAt : null, + maxAttempts: typeof monitor.maxAttempts === "number" ? monitor.maxAttempts : null, + recoveryPolicy: typeof monitor.recoveryPolicy === "string" ? monitor.recoveryPolicy : null, + clearedAt: null, + clearReason: null, + }, + }, + monitorNextCheckAt: nextCheckAt, + monitorAttemptCount: 0, + monitorNotes: "Check deploy", + monitorScheduledBy: "assignee", + }); + + return { companyId, agentId, issueId, nextCheckAt }; + } + + it.each([ + { cause: "provider_failure_meaning_unverified" as const, runtimeMode: "native" as const, status: "failed" as const }, + { cause: "legacy_execution_requires_reconciliation" as const, runtimeMode: "legacy" as const, status: "interrupted" as const }, + ])("parks a monitor deferred by $cause without bumping updatedAt or spamming activity_log, and fires once reconciliation clears", async ({ cause, runtimeMode, status }) => { + const { companyId, issueId, agentId, nextCheckAt } = await seedFixture(); + const sourceRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ + id: sourceRunId, + companyId, + agentId, + nativeIssueId: runtimeMode === "native" ? issueId : null, + runtimeMode, + status, + errorCode: "permission_denied", + finishedAt: new Date("2026-04-11T12:00:00.000Z"), + contextSnapshot: { issueId }, + }); + const [hold] = await db.insert(issueRecoveryActions).values({ + companyId, + sourceIssueId: issueId, + kind: "active_run_watchdog", + status: "active", + ownerType: "board", + cause, + fingerprint: `${cause}:${sourceRunId}`, + evidence: { runId: sourceRunId }, + nextAction: "Inspect the failed execution before continuing.", + }).returning(); + const seededUpdatedAt = new Date("2026-04-11T12:00:00.000Z"); + await db.update(issues).set({ updatedAt: seededUpdatedAt }).where(eq(issues.id, issueId)); + + const heartbeat = heartbeatService(db); + const firstTickAt = new Date(nextCheckAt.getTime() + 39 * 60 * 60_000); + expect(await heartbeat.tickTimers(firstTickAt)).toMatchObject({ checked: 1, enqueued: 0, skipped: 1 }); + + const [parked] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(parked!.updatedAt).toEqual(seededUpdatedAt); + expect(parked!.monitorNextCheckAt).toEqual(nextCheckAt); + expect(parked!.monitorWakeRequestedAt).toBeNull(); + expect(parked!.monitorAttemptCount).toBe(0); + expect(await heartbeat.nextIssueMonitorAt()).toBeNull(); + + const firstEvents = (await db.select().from(activityLog).where(eq(activityLog.entityId, issueId))) + .filter((row) => row.action === "issue.monitor_deferred"); + expect(firstEvents).toHaveLength(1); + expect(firstEvents[0]!.details).toMatchObject({ + reason: "execution_reconciliation_required", + blockerCause: cause, + nextCheckAt: nextCheckAt.toISOString(), + }); + + await db.update(activityLog) + .set({ createdAt: new Date(Date.now() - 10 * 60_000) }) + .where(eq(activityLog.entityId, issueId)); + + for (const offsetMs of [5 * 60_000, 10 * 60_000, 30 * 60_000, 6 * 60 * 60_000]) { + expect(await heartbeat.tickTimers(new Date(firstTickAt.getTime() + offsetMs))).toEqual({ + checked: 0, + enqueued: 0, + skipped: 0, + }); + } + + const [stillParked] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(stillParked!.updatedAt).toEqual(seededUpdatedAt); + expect(stillParked!.monitorAttemptCount).toBe(0); + const deferredEventsAfterHours = (await db.select().from(activityLog).where(eq(activityLog.entityId, issueId))) + .filter((row) => row.action === "issue.monitor_deferred"); + expect(deferredEventsAfterHours).toHaveLength(1); + + const notified: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.issueMonitors, (event) => { + notified.push(event); + }); + try { + await issueRecoveryActionService(db).resolveActiveForIssue({ + companyId, + sourceIssueId: issueId, + actionId: hold!.id, + status: "resolved", + outcome: "restored", + resolutionNote: "Operator reconciled execution.", + }); + await db.update(issueRecoveryActions) + .set({ evidence: { runId: sourceRunId, executionReconciliation: { action: "continue" } } }) + .where(eq(issueRecoveryActions.id, hold!.id)); + } finally { + unsubscribe(); + } + expect(notified).toContain("settled"); + expect(await heartbeat.nextIssueMonitorAt()).toBe(nextCheckAt.getTime()); + + const afterClearAt = new Date(firstTickAt.getTime() + 6 * 60 * 60_000 + 60_000); + expect(await heartbeat.tickTimers(afterClearAt)).toMatchObject({ checked: 1, enqueued: 1, skipped: 0 }); + + const [dispatched] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(dispatched!.monitorNextCheckAt).toBeNull(); + expect(dispatched!.monitorAttemptCount).toBe(1); + expect(dispatched!.updatedAt.getTime()).toBeGreaterThan(seededUpdatedAt.getTime()); + }); + + it("parks a monitor deferred by a resolved no-replay hold until its blocking evidence is retired", async () => { + const { companyId, issueId, agentId, nextCheckAt } = await seedFixture(); + const sourceRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ + id: sourceRunId, + companyId, + agentId, + runtimeMode: "legacy", + status: "interrupted", + errorCode: "permission_denied", + finishedAt: new Date("2026-04-11T12:00:00.000Z"), + contextSnapshot: { issueId }, + }); + const [hold] = await db.insert(issueRecoveryActions).values({ + companyId, + sourceIssueId: issueId, + kind: "active_run_watchdog", + status: "resolved", + outcome: "blocked", + ownerType: "board", + cause: "legacy_execution_requires_reconciliation", + fingerprint: `no-replay:${sourceRunId}`, + evidence: { runId: sourceRunId, automaticRecovery: { replay: "blocked" } }, + nextAction: "Inspect the interrupted execution before continuing.", + resolvedAt: new Date("2026-04-11T12:05:00.000Z"), + }).returning(); + const seededUpdatedAt = new Date("2026-04-11T12:00:00.000Z"); + await db.update(issues).set({ updatedAt: seededUpdatedAt }).where(eq(issues.id, issueId)); + + const heartbeat = heartbeatService(db); + const firstTickAt = new Date(nextCheckAt.getTime() + 60_000); + expect(await heartbeat.tickTimers(firstTickAt)).toMatchObject({ checked: 1, enqueued: 0, skipped: 1 }); + expect(await heartbeat.nextIssueMonitorAt()).toBeNull(); + + // Even after hours, the resolved no-replay hold stays parked with zero retries or updatedAt churn. + expect(await heartbeat.tickTimers(new Date(firstTickAt.getTime() + 2 * 60 * 60_000))).toEqual({ + checked: 0, + enqueued: 0, + skipped: 0, + }); + const [parked] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(parked!.updatedAt).toEqual(seededUpdatedAt); + expect( + (await db.select().from(activityLog).where(eq(activityLog.entityId, issueId))) + .filter((row) => row.action === "issue.monitor_deferred"), + ).toHaveLength(1); + + // Retiring the blocking evidence immediately unparks and dispatches the monitor. + await db.update(issueRecoveryActions).set({ + evidence: { runId: sourceRunId, executionReconciliation: { action: "continue" } }, + updatedAt: new Date(hold!.updatedAt.getTime() + 1_000), + }).where(eq(issueRecoveryActions.id, hold!.id)); + + expect(await heartbeat.nextIssueMonitorAt()).toBe(nextCheckAt.getTime()); + expect(await heartbeat.tickTimers(new Date(firstTickAt.getTime() + 2 * 60 * 60_000 + 60_000))) + .toMatchObject({ checked: 1, enqueued: 1, skipped: 0 }); + }); + + it("respects timeoutAt on a parked escalate_to_board monitor and keeps wake_owner parked until reconciliation clears", async () => { + const timeoutAt = new Date("2026-04-11T14:30:00.000Z"); + const { companyId, issueId, agentId, nextCheckAt } = await seedFixture({ + monitor: { timeoutAt: timeoutAt.toISOString(), recoveryPolicy: "escalate_to_board" }, + }); + const sourceRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ + id: sourceRunId, + companyId, + agentId, + nativeIssueId: issueId, + runtimeMode: "native", + status: "failed", + errorCode: "permission_denied", + finishedAt: new Date("2026-04-11T12:00:00.000Z"), + contextSnapshot: { issueId }, + }); + await db.insert(issueRecoveryActions).values({ + companyId, + sourceIssueId: issueId, + kind: "active_run_watchdog", + status: "active", + ownerType: "board", + cause: "provider_failure_meaning_unverified", + fingerprint: `escalate:${sourceRunId}`, + evidence: { runId: sourceRunId }, + nextAction: "Inspect the failed execution before continuing.", + }); + + const heartbeat = heartbeatService(db); + const firstTickAt = new Date(nextCheckAt.getTime() + 60_000); + expect(await heartbeat.tickTimers(firstTickAt)).toMatchObject({ checked: 1, enqueued: 0, skipped: 1 }); + expect(await heartbeat.nextIssueMonitorAt()).toBe(timeoutAt.getTime()); + expect(await heartbeat.tickTimers(new Date(timeoutAt.getTime() - 1_000))).toEqual({ + checked: 0, + enqueued: 0, + skipped: 0, + }); + + expect(await heartbeat.tickTimers(timeoutAt)).toMatchObject({ checked: 1, enqueued: 0, skipped: 1 }); + const [escalated] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(escalated!.monitorNextCheckAt).toBeNull(); + expect(parseIssueExecutionState(escalated!.executionState)?.monitor).toMatchObject({ + status: "cleared", + clearReason: "timeout_exceeded", + }); + + const wakeOwnerFixture = await seedFixture({ + monitor: { timeoutAt: timeoutAt.toISOString(), recoveryPolicy: "wake_owner" }, + }); + const wakeSourceRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ + id: wakeSourceRunId, + companyId: wakeOwnerFixture.companyId, + agentId: wakeOwnerFixture.agentId, + nativeIssueId: wakeOwnerFixture.issueId, + runtimeMode: "native", + status: "failed", + errorCode: "permission_denied", + finishedAt: new Date("2026-04-11T12:00:00.000Z"), + contextSnapshot: { issueId: wakeOwnerFixture.issueId }, + }); + const [wakeHold] = await db.insert(issueRecoveryActions).values({ + companyId: wakeOwnerFixture.companyId, + sourceIssueId: wakeOwnerFixture.issueId, + kind: "active_run_watchdog", + status: "active", + ownerType: "board", + cause: "provider_failure_meaning_unverified", + fingerprint: `wake-owner:${wakeSourceRunId}`, + evidence: { runId: wakeSourceRunId }, + nextAction: "Inspect the failed execution before continuing.", + }).returning(); + const wakeSeededUpdatedAt = new Date("2026-04-11T12:00:00.000Z"); + await db.update(issues).set({ updatedAt: wakeSeededUpdatedAt }).where(eq(issues.id, wakeOwnerFixture.issueId)); + + const pastTimeout = new Date(timeoutAt.getTime() + 60_000); + expect(await heartbeat.tickTimers(pastTimeout)).toMatchObject({ checked: 1, enqueued: 0, skipped: 1 }); + expect(await heartbeat.nextIssueMonitorAt()).toBeNull(); + expect(await heartbeat.tickTimers(new Date(pastTimeout.getTime() + 30 * 60_000))).toEqual({ + checked: 0, + enqueued: 0, + skipped: 0, + }); + const [parkedWakeOwner] = await db.select().from(issues).where(eq(issues.id, wakeOwnerFixture.issueId)); + expect(parkedWakeOwner!.updatedAt).toEqual(wakeSeededUpdatedAt); + expect(parkedWakeOwner!.monitorNextCheckAt).toEqual(wakeOwnerFixture.nextCheckAt); + + await issueRecoveryActionService(db).resolveActiveForIssue({ + companyId: wakeOwnerFixture.companyId, + sourceIssueId: wakeOwnerFixture.issueId, + actionId: wakeHold!.id, + status: "resolved", + outcome: "restored", + resolutionNote: "Reconciled.", + }); + await db.update(issueRecoveryActions) + .set({ evidence: { runId: wakeSourceRunId, executionReconciliation: { action: "continue" } } }) + .where(eq(issueRecoveryActions.id, wakeHold!.id)); + + expect(await heartbeat.nextIssueMonitorAt()).toBe(wakeOwnerFixture.nextCheckAt.getTime()); + expect(await heartbeat.tickTimers(new Date(pastTimeout.getTime() + 31 * 60_000))).toMatchObject({ + checked: 1, + skipped: 1, + }); + const [clearedWakeOwner] = await db.select().from(issues).where(eq(issues.id, wakeOwnerFixture.issueId)); + expect(clearedWakeOwner!.monitorNextCheckAt).toBeNull(); + expect(parseIssueExecutionState(clearedWakeOwner!.executionState)?.monitor).toMatchObject({ + status: "cleared", + clearReason: "timeout_exceeded", + }); + }); +}); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index d60f1a329b1..6c1d0511227 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -3,6 +3,7 @@ import { isAppQuestionCardKey } from "../services/mcp-elicitation.js"; import { listStalledDependencies } from "../services/recovery/blocker-stall-wakeups.js"; import { confirmMcpAttachmentCleanup, recordMcpAttachmentCleanup, type McpAttachmentCleanup } from "../services/public-mcp/upload-cleanup.js"; import { notifyDeferredExecutionWork } from "../services/deferred-execution-notifications.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../services/delivery-work-notifications.js"; import { notifyNativeRecoveryNotices } from "../services/native-recovery-notice-notifications.js"; import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js"; import { notifyUnsafeWorkspaceExportRecovery } from "../services/unsafe-workspace-export-notifications.js"; @@ -10368,6 +10369,9 @@ export function issueRoutes( await markExecutionReconciliation(tx as unknown as Db, workspaceRepairAction, executionReconciliation!, actor.actorId, undefined, { workspaceRepairOnly: true }); await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: lockedIssue.companyId, issueId: lockedIssue.id }); + if (lockedIssue.monitorNextCheckAt) { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); + } const [recoveryAction] = await tx.update(issueRecoveryActions).set({ status: "resolved", outcome: "restored", resolutionNote: resolutionNote ?? null, resolvedAt: new Date(), updatedAt: new Date(), }).where(eq(issueRecoveryActions.id, workspaceRepairAction.id)).returning(); diff --git a/server/src/services/heartbeat/issue-monitor-deferral.test.ts b/server/src/services/heartbeat/issue-monitor-deferral.test.ts new file mode 100644 index 00000000000..071ba319ec9 --- /dev/null +++ b/server/src/services/heartbeat/issue-monitor-deferral.test.ts @@ -0,0 +1,180 @@ +import { describe, expect, it } from "vitest"; +import { + ISSUE_MONITOR_DEFERRAL_BASE_DELAY_MS, + ISSUE_MONITOR_DEFERRAL_MAX_DELAY_MS, + ISSUE_MONITOR_DIAGNOSTIC_MIN_QUIET_MS, + buildIssueMonitorDeferralState, + issueMonitorDeferralDelayMs, + readIssueMonitorDeferral, +} from "./issue-monitor-deferral.js"; +import { applyIssueExecutionPolicyTransition, normalizeIssueExecutionPolicy } from "../issue-execution-policy.js"; + +describe("issue monitor deferral state", () => { + const scheduledAtIso = "2026-04-11T12:30:00.000Z"; + const now = new Date("2026-04-11T13:00:00.000Z"); + + it("grows non-hold deferral backoff exponentially from 30s to a 60m cap", () => { + expect(issueMonitorDeferralDelayMs(1)).toBe(ISSUE_MONITOR_DEFERRAL_BASE_DELAY_MS); + expect(issueMonitorDeferralDelayMs(2)).toBe(60_000); + expect(issueMonitorDeferralDelayMs(3)).toBe(2 * 60_000); + expect(issueMonitorDeferralDelayMs(4)).toBe(4 * 60_000); + expect(issueMonitorDeferralDelayMs(7)).toBe(32 * 60_000); + expect(issueMonitorDeferralDelayMs(8)).toBe(ISSUE_MONITOR_DEFERRAL_MAX_DELAY_MS); + expect(issueMonitorDeferralDelayMs(20)).toBe(ISSUE_MONITOR_DEFERRAL_MAX_DELAY_MS); + }); + + it("clamps backoff retryAt to timeoutAt when timeoutAt is sooner", () => { + const timeoutAt = new Date(now.getTime() + 10_000); + const { state, quietWindowMs } = buildIssueMonitorDeferralState({ + existing: null, + scheduledAtIso, + now, + timeoutAt, + reason: "monitor_dispatch_deferred", + recoveryHold: null, + }); + expect(state).toEqual({ + nextCheckAt: scheduledAtIso, + deferredCount: 1, + retryAt: timeoutAt.toISOString(), + recoveryActionId: null, + recoveryActionUpdatedAt: null, + reason: "monitor_dispatch_deferred", + }); + expect(quietWindowMs).toBe(ISSUE_MONITOR_DIAGNOSTIC_MIN_QUIET_MS); + }); + + it("parks on an active recovery hold with null retryAt and ignores deferral state after monitor replacement", () => { + const { state } = buildIssueMonitorDeferralState({ + existing: null, + scheduledAtIso, + now, + timeoutAt: null, + reason: "execution_reconciliation_required", + recoveryHold: { + id: "11111111-1111-4111-8111-111111111111", + updatedAtIso: "2026-04-11T12:00:00.123456Z", + }, + }); + expect(state.retryAt).toBeNull(); + expect(state.recoveryActionId).toBe("11111111-1111-4111-8111-111111111111"); + expect(readIssueMonitorDeferral({ monitorDeferral: state }, scheduledAtIso)).toEqual(state); + expect(readIssueMonitorDeferral({ monitorDeferral: state }, "2026-04-11T12:45:00.000Z")).toBeNull(); + }); + + it("preserves monitorDeferral on unrelated policy transitions and drops it on monitor replacement", () => { + const policy = normalizeIssueExecutionPolicy({ + mode: "normal", + commentRequired: true, + stages: [], + monitor: { + nextCheckAt: scheduledAtIso, + notes: "Watch external job", + scheduledBy: "assignee", + }, + }); + const deferral = { + nextCheckAt: scheduledAtIso, + deferredCount: 1, + retryAt: null, + recoveryActionId: "11111111-1111-4111-8111-111111111111", + recoveryActionUpdatedAt: "2026-04-11T12:00:00.123456Z", + reason: "execution_reconciliation_required", + }; + const issue = { + status: "in_progress", + assigneeAgentId: "22222222-2222-4222-8222-222222222222", + assigneeUserId: null, + executionPolicy: policy, + executionState: { + status: "idle", + currentStageId: null, + currentStageIndex: null, + currentStageType: null, + currentParticipant: null, + returnAssignee: null, + reviewRequest: null, + completedStageIds: [], + lastDecisionId: null, + lastDecisionOutcome: null, + monitor: { + status: "scheduled", + nextCheckAt: scheduledAtIso, + lastTriggeredAt: null, + attemptCount: 0, + notes: "Old notes", + scheduledBy: "assignee", + clearedAt: null, + clearReason: null, + }, + monitorDeferral: deferral, + }, + monitorNextCheckAt: new Date(scheduledAtIso), + monitorAttemptCount: 0, + monitorNotes: "Old notes", + monitorScheduledBy: "assignee", + }; + + // Unrelated edit with unchanged policy leaves executionState untouched in DB. + const unchanged = applyIssueExecutionPolicyTransition({ + issue, + policy, + previousPolicy: policy, + requestedStatus: "in_progress", + requestedAssigneePatch: {}, + actor: { agentId: null, userId: "user-1" }, + monitorExplicitlyUpdated: false, + }); + expect(unchanged.patch.executionState).toBeUndefined(); + + // Unrelated stage/policy rewrite that does not touch the monitor preserves monitorDeferral. + const withReviewStage = normalizeIssueExecutionPolicy({ + mode: "normal", + commentRequired: true, + stages: [ + { + id: "33333333-3333-4333-8333-333333333333", + type: "review", + approvalsNeeded: 1, + participants: [{ type: "agent", agentId: "44444444-4444-4444-8444-444444444444" }], + }, + ], + monitor: { + nextCheckAt: scheduledAtIso, + notes: "Watch external job", + scheduledBy: "assignee", + }, + }); + const stageRewrite = applyIssueExecutionPolicyTransition({ + issue: { ...issue, executionPolicy: withReviewStage }, + policy: withReviewStage, + previousPolicy: withReviewStage, + requestedStatus: "done", + requestedAssigneePatch: {}, + actor: { agentId: "22222222-2222-4222-8222-222222222222", userId: null }, + monitorExplicitlyUpdated: false, + }); + expect((stageRewrite.patch.executionState as Record | undefined)?.monitorDeferral).toEqual(deferral); + + const replacementPolicy = normalizeIssueExecutionPolicy({ + mode: "normal", + commentRequired: true, + stages: [], + monitor: { + nextCheckAt: "2026-04-11T14:00:00.000Z", + notes: "Updated schedule", + scheduledBy: "assignee", + }, + }); + const replaced = applyIssueExecutionPolicyTransition({ + issue, + policy: replacementPolicy, + previousPolicy: policy, + requestedStatus: "in_progress", + requestedAssigneePatch: {}, + actor: { agentId: null, userId: "user-1" }, + monitorExplicitlyUpdated: true, + }); + expect((replaced.patch.executionState as Record | undefined)?.monitorDeferral).toBeUndefined(); + }); +}); diff --git a/server/src/services/heartbeat/issue-monitor-deferral.ts b/server/src/services/heartbeat/issue-monitor-deferral.ts new file mode 100644 index 00000000000..abfbbf29b16 --- /dev/null +++ b/server/src/services/heartbeat/issue-monitor-deferral.ts @@ -0,0 +1,291 @@ +import { issueRecoveryActions, issues, type Db } from "@paperclipai/db"; +import { isUuidLike } from "@paperclipai/shared"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; + +export const ISSUE_MONITOR_DEFERRAL_BASE_DELAY_MS = 30_000; +export const ISSUE_MONITOR_DEFERRAL_MAX_DELAY_MS = 60 * 60_000; +export const ISSUE_MONITOR_DIAGNOSTIC_MIN_QUIET_MS = 5 * 60_000; + +export interface IssueMonitorDeferralState { + nextCheckAt: string; + deferredCount: number; + retryAt: string | null; + recoveryActionId: string | null; + recoveryActionUpdatedAt: string | null; + reason: string; +} + +const BLANK_EXECUTION_STATE = { + status: "idle", + currentStageId: null, + currentStageIndex: null, + currentStageType: null, + currentParticipant: null, + returnAssignee: null, + reviewRequest: null, + completedStageIds: [], + lastDecisionId: null, + lastDecisionOutcome: null, + monitor: null, +}; + +export function issueMonitorDeferralDelayMs(deferredCount: number): number { + const exponent = Math.max(0, Math.min(deferredCount - 1, 30)); + return Math.min( + ISSUE_MONITOR_DEFERRAL_BASE_DELAY_MS * 2 ** exponent, + ISSUE_MONITOR_DEFERRAL_MAX_DELAY_MS, + ); +} + +function asObject(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +function asIsoString(value: unknown): string | null { + if (typeof value !== "string" || value.trim().length === 0) return null; + return Number.isNaN(Date.parse(value)) ? null : value; +} + +export function readIssueMonitorDeferral( + executionState: Record | null | undefined, + scheduledAtIso: string, +): IssueMonitorDeferralState | null { + const raw = asObject(asObject(executionState)?.monitorDeferral); + if (!raw) return null; + const nextCheckAt = asIsoString(raw.nextCheckAt); + if (!nextCheckAt) return null; + const expectedTime = Date.parse(scheduledAtIso); + if (Number.isNaN(expectedTime) || Date.parse(nextCheckAt) !== expectedTime) { + return null; + } + const deferredCount = + typeof raw.deferredCount === "number" && + Number.isInteger(raw.deferredCount) && + raw.deferredCount >= 0 + ? raw.deferredCount + : 0; + const retryAt = asIsoString(raw.retryAt); + const recoveryActionId = + typeof raw.recoveryActionId === "string" && raw.recoveryActionId.trim().length > 0 + ? raw.recoveryActionId + : null; + const recoveryActionUpdatedAt = asIsoString(raw.recoveryActionUpdatedAt); + const reason = typeof raw.reason === "string" ? raw.reason : ""; + return { + nextCheckAt, + deferredCount, + retryAt, + recoveryActionId, + recoveryActionUpdatedAt, + reason, + }; +} + +export function buildIssueMonitorDeferralState(input: { + existing: IssueMonitorDeferralState | null; + scheduledAtIso: string; + now: Date; + timeoutAt: Date | null; + reason: string; + recoveryHold: { id: string; updatedAtIso: string } | null; +}): { state: IssueMonitorDeferralState; quietWindowMs: number } { + const deferredCount = (input.existing?.deferredCount ?? 0) + 1; + if (input.recoveryHold) { + return { + state: { + nextCheckAt: input.scheduledAtIso, + deferredCount, + retryAt: null, + recoveryActionId: input.recoveryHold.id, + recoveryActionUpdatedAt: input.recoveryHold.updatedAtIso, + reason: input.reason, + }, + quietWindowMs: ISSUE_MONITOR_DIAGNOSTIC_MIN_QUIET_MS, + }; + } + + const delayMs = issueMonitorDeferralDelayMs(deferredCount); + let retryAtMs = input.now.getTime() + delayMs; + if ( + input.timeoutAt && + input.timeoutAt.getTime() > input.now.getTime() && + input.timeoutAt.getTime() < retryAtMs + ) { + retryAtMs = input.timeoutAt.getTime(); + } + return { + state: { + nextCheckAt: input.scheduledAtIso, + deferredCount, + retryAt: new Date(retryAtMs).toISOString(), + recoveryActionId: null, + recoveryActionUpdatedAt: null, + reason: input.reason, + }, + quietWindowMs: Math.max(ISSUE_MONITOR_DIAGNOSTIC_MIN_QUIET_MS, delayMs), + }; +} + +export function monitorDeferralExecutionStateSql(deferral: IssueMonitorDeferralState) { + return sql`jsonb_set( + case when ${issues.executionState} is not null and ${issues.executionState} ? 'status' + then ${issues.executionState} + else ${JSON.stringify(BLANK_EXECUTION_STATE)}::jsonb end, + '{monitorDeferral}', + ${JSON.stringify(deferral)}::jsonb + )`; +} + +const UUID_REGEX = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; +const ISO_TS_REGEX = "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$"; + +function deferralMatchesMonitorSql() { + return sql`coalesce((jsonb_typeof(${issues.executionState}->'monitorDeferral') = 'object' + and (case + when (${issues.executionState}->'monitorDeferral'->>'nextCheckAt') ~ ${ISO_TS_REGEX} + then (${issues.executionState}->'monitorDeferral'->>'nextCheckAt')::timestamptz + else null + end) = ${issues.monitorNextCheckAt}), false)`; +} + +/** + * Single-row predicate matching recovery actions that remain effective holds: + * open (`active`/`escalated`) rows as well as resolved rows that still block + * execution (`automaticRecovery.replay = 'blocked'` or unreconciled native + * workspace exports). Admission (`getExecutionBlocker`) already validated this + * action before parking, so checking the row directly uses the primary-key + * index without nested `heartbeat_runs` subqueries. + */ +export function parkableRecoveryHoldCondition() { + return or( + inArray(issueRecoveryActions.status, ["active", "escalated"]), + sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`, + and( + eq(issueRecoveryActions.status, "resolved"), + eq(issueRecoveryActions.resolutionNote, "new_source_execution_path"), + sql`${issueRecoveryActions.evidence}->'executionReconciliation'->'workspaceReconstruction' is null`, + ), + and( + eq(issueRecoveryActions.status, "resolved"), + sql`${issueRecoveryActions.evidence}->'executionReconciliation'->'workspaceReconstruction'->>'schema' = 'paperclip.workspace-reconstruction.v1'`, + sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'pending'`, + ), + )!; +} + +function parkedOnUnchangedRecoveryHoldSql() { + return sql`coalesce((${deferralMatchesMonitorSql()} + and exists (select 1 from ${issueRecoveryActions} + where ${issueRecoveryActions.id} = (case + when (${issues.executionState}->'monitorDeferral'->>'recoveryActionId') ~ ${UUID_REGEX} + then (${issues.executionState}->'monitorDeferral'->>'recoveryActionId')::uuid + else null + end) + and ${issueRecoveryActions.companyId} = ${issues.companyId} + and ${issueRecoveryActions.sourceIssueId} = ${issues.id} + and (${parkableRecoveryHoldCondition()}) + and ${issueRecoveryActions.updatedAt} <= (case + when (${issues.executionState}->'monitorDeferral'->>'recoveryActionUpdatedAt') ~ ${ISO_TS_REGEX} + then (${issues.executionState}->'monitorDeferral'->>'recoveryActionUpdatedAt')::timestamptz + else null + end))), false)`; +} + +function nonWakeOwnerTimeoutAtSql() { + return sql`(case + when coalesce(${issues.executionPolicy}->'monitor'->>'recoveryPolicy', 'wake_owner') in ('escalate_to_board', 'create_recovery_issue') + and (${issues.executionPolicy}->'monitor'->>'timeoutAt') ~ ${ISO_TS_REGEX} + then (${issues.executionPolicy}->'monitor'->>'timeoutAt')::timestamptz + else null + end)`; +} + +function matchingDeferredRetryAtSql() { + return sql`(case + when ${deferralMatchesMonitorSql()} + and (${issues.executionState}->'monitorDeferral'->>'retryAt') ~ ${ISO_TS_REGEX} + then (${issues.executionState}->'monitorDeferral'->>'retryAt')::timestamptz + else null + end)`; +} + +/** + * Excludes scheduled monitors that are either parked on an unchanged active + * execution-reconciliation hold (unless a non-wake_owner timeoutAt is now due) + * or waiting out their exponential deferral backoff window. + */ +export function eligibleDeferredMonitorCondition(now: Date) { + const nowIso = now.toISOString(); + const parked = parkedOnUnchangedRecoveryHoldSql(); + const nonWakeTimeout = nonWakeOwnerTimeoutAtSql(); + const retryAt = matchingDeferredRetryAtSql(); + return sql`((not ${parked} and (${retryAt} is null or ${retryAt} <= ${nowIso}::timestamptz)) + or (${parked} and ${nonWakeTimeout} is not null and ${nonWakeTimeout} <= ${nowIso}::timestamptz))`; +} + +export function nextIssueMonitorWhereCondition() { + return sql`(not ${parkedOnUnchangedRecoveryHoldSql()} or ${nonWakeOwnerTimeoutAtSql()} is not null)`; +} + +export async function resolveScheduledMonitorDeferralUpdate( + tx: Pick, + input: { + companyId: string; + issueId: string; + executionState: Record | null; + scheduledAtIso: string; + now: Date; + activitySource: "manual" | "scheduled"; + reason: string; + blockerRecoveryActionId?: string | null; + timeoutAt?: Date | null; + }, +): Promise<{ patch: Record; quietWindowMs: number }> { + if (input.activitySource !== "scheduled") { + return { + patch: { monitorWakeRequestedAt: null }, + quietWindowMs: ISSUE_MONITOR_DIAGNOSTIC_MIN_QUIET_MS, + }; + } + let recoveryHold: { id: string; updatedAtIso: string } | null = null; + if (input.blockerRecoveryActionId && isUuidLike(input.blockerRecoveryActionId)) { + const [hold] = await tx.select({ + id: issueRecoveryActions.id, + updatedAtIso: sql`to_char(${issueRecoveryActions.updatedAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`, + }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, input.companyId), + eq(issueRecoveryActions.sourceIssueId, input.issueId), + eq(issueRecoveryActions.id, input.blockerRecoveryActionId), + parkableRecoveryHoldCondition(), + )).limit(1); + if (hold) recoveryHold = hold; + } + const { state, quietWindowMs } = buildIssueMonitorDeferralState({ + existing: readIssueMonitorDeferral(input.executionState, input.scheduledAtIso), + scheduledAtIso: input.scheduledAtIso, + now: input.now, + timeoutAt: input.timeoutAt ?? null, + reason: input.reason, + recoveryHold, + }); + return { + patch: { + monitorWakeRequestedAt: null, + executionState: monitorDeferralExecutionStateSql(state), + }, + quietWindowMs, + }; +} + +export function nextIssueMonitorAtSelectSql() { + const parked = parkedOnUnchangedRecoveryHoldSql(); + const nonWakeTimeout = nonWakeOwnerTimeoutAtSql(); + const retryAt = matchingDeferredRetryAtSql(); + return sql`min(case + when ${parked} + then greatest(${nonWakeTimeout}, ${issues.monitorWakeRequestedAt} + interval '5 minutes' + interval '1 millisecond') + else greatest(${issues.monitorNextCheckAt}, ${retryAt}, ${issues.monitorWakeRequestedAt} + interval '5 minutes' + interval '1 millisecond') + end)`; +} diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index ca4d5e99111..648baf870ad 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -4035,7 +4035,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende executionBlocker: Pick>>, "recoveryActionId" | "cause" | "nextAction">, ) => { if (caseRequest) waitForCaseAdmission("execution_reconciliation_required", executionBlocker.nextAction); - opts.issueStateGuard?.onExecutionDeferred?.(executionBlocker.cause); + opts.issueStateGuard?.onExecutionDeferred?.(executionBlocker.cause, executionBlocker.recoveryActionId ?? null); return recovery.defer({ existingRequestId: executionWaitRequestId, commentId: wakeCommentId, diff --git a/server/src/services/heartbeat/run-preparation.ts b/server/src/services/heartbeat/run-preparation.ts index e23e251a9bb..f5ad230df93 100644 --- a/server/src/services/heartbeat/run-preparation.ts +++ b/server/src/services/heartbeat/run-preparation.ts @@ -839,7 +839,7 @@ export interface WakeupOptions { monitorNextCheckAt?: string; monitorWakeRequestedAt?: string; /** Internal diagnostic only; the callback cannot grant admission. */ - onExecutionDeferred?: (blockerCause: string) => void; + onExecutionDeferred?: (blockerCause: string, recoveryActionId?: string | null) => void; }; /** Keep causally distinct external chat continuations out of an existing run. */ allowRunCoalescing?: boolean; diff --git a/server/src/services/heartbeat/scheduling.test.ts b/server/src/services/heartbeat/scheduling.test.ts index a46e6abe880..1efcb7a6b1f 100644 --- a/server/src/services/heartbeat/scheduling.test.ts +++ b/server/src/services/heartbeat/scheduling.test.ts @@ -189,12 +189,71 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", ( expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: replacement, monitorAttemptCount: 0 }); }); - it("retains a deferred monitor and releases its claim for a later tick", async () => { + it("backs off non-hold deferred monitors exponentially without bumping updatedAt or starving tied monitors", async () => { + const f = await fixture(); + const initialUpdatedAt = new Date(now.getTime() - 120_000); + await db.update(issues).set({ updatedAt: initialUpdatedAt }).where(eq(issues.id, f.issue.id)); + f.deps.enqueueWakeup.mockResolvedValue(null); + + // Tick 1: defers with 30s backoff, preserves updatedAt and attemptCount. + expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 }); + expect(await readIssue(f.issue.id)).toMatchObject({ + updatedAt: initialUpdatedAt, + monitorNextCheckAt: dueAt, + monitorWakeRequestedAt: null, + monitorAttemptCount: 0, + }); + expect(await f.scheduler.nextIssueMonitorAt()).toBe(now.getTime() + 30_000); + expect(await f.scheduler.tickTimers(new Date(now.getTime() + 29_999))).toEqual({ checked: 0, enqueued: 0, skipped: 0 }); + + // Tick 2 at +30s: defers again, backoff grows to 60s (total +90s), still preserves updatedAt. + const t2 = new Date(now.getTime() + 30_000); + expect(await f.scheduler.tickTimers(t2)).toEqual({ checked: 1, enqueued: 0, skipped: 1 }); + expect(await f.scheduler.nextIssueMonitorAt()).toBe(t2.getTime() + 60_000); + expect(await f.scheduler.tickTimers(new Date(t2.getTime() + 59_999))).toEqual({ checked: 0, enqueued: 0, skipped: 0 }); + expect((await readIssue(f.issue.id)).updatedAt).toEqual(initialUpdatedAt); + + // Replacing monitorNextCheckAt immediately invalidates the old backoff. + const replacement = new Date(t2.getTime() + 10_000); + await db.update(issues).set({ monitorNextCheckAt: replacement }).where(eq(issues.id, f.issue.id)); + expect(await f.scheduler.nextIssueMonitorAt()).toBe(replacement.getTime()); + f.deps.enqueueWakeup.mockResolvedValueOnce(admitted); + expect(await f.scheduler.tickTimers(replacement)).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); + }); + + it("lets a ready tied monitor pass fifty deferred monitors on the next sweep without bumping updatedAt", async () => { + const f = await fixture(); + const olderUpdatedAt = new Date(now.getTime() - 120_000); + const newerUpdatedAt = new Date(now.getTime() - 60_000); + await db.update(issues).set({ updatedAt: newerUpdatedAt }).where(eq(issues.id, f.issue.id)); + const deferredIds = await db.insert(issues).values(Array.from({ length: 50 }, (_, index) => ({ + companyId: f.company.id, + title: `Deferred tied monitor ${index}`, + status: "in_progress", + assigneeAgentId: f.agent.id, + monitorNextCheckAt: dueAt, + executionPolicy: f.issue.executionPolicy, + updatedAt: olderUpdatedAt, + }))).returning({ id: issues.id }); + const deferredSet = new Set(deferredIds.map((row) => row.id)); + f.deps.enqueueWakeup.mockImplementation(async (_agentId, options) => { + const issueId = (options?.payload as { issueId?: string } | undefined)?.issueId; + return issueId && deferredSet.has(issueId) ? null : admitted; + }); + + expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 50, enqueued: 0, skipped: 50 }); + // Second sweep 1s later skips the 50 backed-off rows and reaches the 51st ready row. + expect(await f.scheduler.tickTimers(new Date(now.getTime() + 1_000))).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); + expect((await readIssue(deferredIds[0]!.id)).updatedAt).toEqual(olderUpdatedAt); + }); + + it("retains a deferred monitor, backs off its retry, and releases its claim for a later tick", async () => { const f = await fixture(); f.deps.enqueueWakeup.mockResolvedValueOnce(null); expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 }); expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null, monitorAttemptCount: 0 }); - expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); + expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 }); + expect(await f.scheduler.tickTimers(new Date(now.getTime() + 30_000))).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); const calls = f.deps.enqueueWakeup.mock.calls; expect(calls[0]![1]!.idempotencyKey).toBe(calls[1]![1]!.idempotencyKey); expect(calls[0]![1]!.issueStateGuard).toMatchObject({ @@ -241,7 +300,8 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", ( f.deps.enqueueWakeup.mockRejectedValueOnce(new Error("Temporary admission failure")); await f.scheduler.tickTimers(now); expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null }); - expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); + expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 }); + expect(await f.scheduler.tickTimers(new Date(now.getTime() + 30_000))).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); }); it("records bounded dispatch failure diagnostics while retaining the schedule", async () => { @@ -263,7 +323,7 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", ( await f.scheduler.tickTimers(new Date(now.getTime() + 30_000)); expect(await db.select().from(activityLog).where(eq(activityLog.entityId, f.issue.id))).toHaveLength(1); await db.update(activityLog).set({ createdAt: new Date(Date.now() - 6 * 60_000) }).where(eq(activityLog.entityId, f.issue.id)); - await f.scheduler.tickTimers(new Date(now.getTime() + 60_000)); + await f.scheduler.tickTimers(new Date(now.getTime() + 90_000)); expect(await db.select().from(activityLog).where(eq(activityLog.entityId, f.issue.id))).toHaveLength(2); expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorAttemptCount: 0 }); }); @@ -280,7 +340,7 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", ( expect(JSON.stringify(events)).not.toContain("PRIVATE_BLOCKER_CAUSE"); }); - it("releases a monitor claim when diagnostic storage fails", async () => { + it("releases a monitor claim and backs off when diagnostic storage fails", async () => { const f = await fixture(); await db.execute(sql`create function fail_monitor_diagnostic_test() returns trigger language plpgsql as $$ begin if new.action = 'issue.monitor_deferred' then raise exception 'Synthetic diagnostic storage failure'; end if; return new; end; $$`); @@ -290,7 +350,8 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", ( f.deps.enqueueWakeup.mockResolvedValueOnce(null); expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 }); expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null, monitorAttemptCount: 0 }); - expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); + expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 }); + expect(await f.scheduler.tickTimers(new Date(now.getTime() + 30_000))).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); } finally { await db.execute(sql`drop trigger fail_monitor_diagnostic_test on activity_log`); await db.execute(sql`drop function fail_monitor_diagnostic_test()`); diff --git a/server/src/services/heartbeat/scheduling.ts b/server/src/services/heartbeat/scheduling.ts index 7ed62fe5015..29bb1d059f9 100644 --- a/server/src/services/heartbeat/scheduling.ts +++ b/server/src/services/heartbeat/scheduling.ts @@ -65,6 +65,12 @@ import type { createHeartbeatQueue } from "./queue.js"; import type { createHeartbeatRetries, HeartbeatRetryDependencies } from "./retries.js"; import type { createHeartbeatRunPreparation } from "./run-preparation.js"; import type { NativeSessionGoalControl } from "../../vendor/paperclip-runner/index.js"; +import { + eligibleDeferredMonitorCondition, + nextIssueMonitorAtSelectSql, + nextIssueMonitorWhereCondition, + resolveScheduledMonitorDeferralUpdate, +} from "./issue-monitor-deferral.js"; type HeartbeatQueue = ReturnType; type RunPreparation = ReturnType; @@ -296,6 +302,7 @@ export function createHeartbeatScheduling( agentId: string | null; runId: string | null; activitySource: "manual" | "scheduled"; + onExecutionDeferred?: (cause: string, recoveryActionId?: string | null) => void; }) { const reviewPathLost = input.claimed.status === "in_review" && @@ -417,7 +424,8 @@ export function createHeartbeatScheduling( const wake = accepted ?? await enqueueWakeup(input.claimed.assigneeAgentId!, { issueStateGuard: { statuses: [input.claimed.status], assigneeAgentId: input.claimed.assigneeAgentId!, monitorNextCheckAt: input.scheduledAtIso, - monitorWakeRequestedAt: input.claimed.monitorWakeRequestedAt!.toISOString() }, + monitorWakeRequestedAt: input.claimed.monitorWakeRequestedAt!.toISOString(), + onExecutionDeferred: input.onExecutionDeferred }, source: "automation", triggerDetail: "system", reason: "issue_monitor_recovery", @@ -485,18 +493,35 @@ export function createHeartbeatScheduling( runId: string | null; activitySource: "manual" | "scheduled"; }) { - const recover = () => performIssueMonitorRecovery(input); + let recoveryDeferredCause: string | null = null; + let recoveryDeferredActionId: string | null = null; + const recover = () => performIssueMonitorRecovery({ + ...input, + onExecutionDeferred: (cause, recoveryActionId) => { + recoveryDeferredCause = cause; + recoveryDeferredActionId = recoveryActionId ?? null; + }, + }); if (input.recoveryPolicy === "wake_owner") { try { if (!await recover()) { + const blockerCause = recoveryDeferredCause && + ([...EXECUTION_RECONCILIATION_CAUSES, "execution_owner_active"] as readonly string[]).includes(recoveryDeferredCause) + ? recoveryDeferredCause : undefined; await releaseIssueMonitorWithDiagnostic(input.claimed, input, { - action: "issue.monitor_deferred", reason: "monitor_recovery_deferred", + action: "issue.monitor_deferred", + reason: "monitor_recovery_deferred", + ...(blockerCause ? { blockerCause } : {}), + blockerRecoveryActionId: recoveryDeferredActionId, + timeoutAt: parseMonitorDate(input.monitor?.timeoutAt ?? null), }); return { outcome: "skipped" as const, reason: "monitor_recovery_deferred" }; } } catch (error) { await releaseIssueMonitorWithDiagnostic(input.claimed, input, { - action: "issue.monitor_dispatch_failed", reason: "monitor_recovery_failed", + action: "issue.monitor_dispatch_failed", + reason: "monitor_recovery_failed", + timeoutAt: parseMonitorDate(input.monitor?.timeoutAt ?? null), }); throw error; } @@ -575,7 +600,7 @@ export function createHeartbeatScheduling( return { ...patch, executionPolicy: sql`nullif(${issues.executionPolicy} - 'monitor', '{}'::jsonb)`, - executionState: sql`jsonb_set(coalesce(${issues.executionState}, ${JSON.stringify(patch.executionState)}::jsonb), + executionState: sql`jsonb_set(coalesce(${issues.executionState}, ${JSON.stringify(patch.executionState)}::jsonb) - 'monitorDeferral', '{monitor}', ${JSON.stringify(patch.executionState?.monitor ?? null)}::jsonb)`, }; } @@ -592,15 +617,31 @@ export function createHeartbeatScheduling( input: Pick[1], "now" | "actorType" | "actorId" | "agentId" | "runId" | "activitySource">, diagnostic: { action: "issue.monitor_deferred" | "issue.monitor_dispatch_failed"; - reason: string; blockerCause?: string; httpStatus?: number }, + reason: string; blockerCause?: string; blockerRecoveryActionId?: string | null; + httpStatus?: number; timeoutAt?: Date | null }, ) { const publications: ActivityPublication[] = []; + const scheduledAtIso = claimed.monitorNextCheckAt!.toISOString(); + const resolveReleaseUpdate = (tx: Pick) => + resolveScheduledMonitorDeferralUpdate(tx, { + companyId: claimed.companyId, + issueId: claimed.id, + executionState: claimed.executionState, + scheduledAtIso, + now: input.now, + activitySource: input.activitySource, + reason: diagnostic.reason, + blockerRecoveryActionId: diagnostic.blockerRecoveryActionId, + timeoutAt: diagnostic.timeoutAt, + }); + try { await db.transaction(async (tx) => { await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); await notifyStatusCardIssueChange(tx, claimed.companyId); + const { patch, quietWindowMs } = await resolveReleaseUpdate(tx as unknown as Db); const released = await tx.update(issues) - .set({ monitorWakeRequestedAt: null, updatedAt: input.now }) + .set(patch) .where(issueMonitorClaimCondition(claimed)).returning({ id: issues.id }); if (released.length === 0) return; // The issue lock serializes diagnostics from competing scheduler instances. @@ -608,8 +649,8 @@ export function createHeartbeatScheduling( const [recent] = await tx.select({ id: activityLog.id }).from(activityLog).where(and( eq(activityLog.companyId, claimed.companyId), eq(activityLog.entityType, "issue"), eq(activityLog.entityId, claimed.id), eq(activityLog.action, diagnostic.action), - gte(activityLog.createdAt, new Date(Date.now() - 5 * 60_000)), - sql`${activityLog.details}->>'nextCheckAt' = ${claimed.monitorNextCheckAt!.toISOString()}`, + gte(activityLog.createdAt, new Date(Date.now() - quietWindowMs)), + sql`${activityLog.details}->>'nextCheckAt' = ${scheduledAtIso}`, sql`${activityLog.details}->>'reason' = ${diagnostic.reason}`, sql`coalesce(${activityLog.details}->>'blockerCause', '') = ${diagnostic.blockerCause ?? ""}`, )).limit(1); @@ -618,7 +659,7 @@ export function createHeartbeatScheduling( companyId: claimed.companyId, actorType: input.actorType, actorId: input.actorId, agentId: input.agentId, runId: input.runId, action: diagnostic.action, entityType: "issue", entityId: claimed.id, - details: { nextCheckAt: claimed.monitorNextCheckAt!.toISOString(), + details: { nextCheckAt: scheduledAtIso, checkedAt: input.now.toISOString(), attemptCount: claimed.monitorAttemptCount ?? 0, reason: diagnostic.reason, source: input.activitySource, ...(diagnostic.blockerCause ? { blockerCause: diagnostic.blockerCause } : {}), @@ -633,7 +674,8 @@ export function createHeartbeatScheduling( await db.transaction(async tx => { await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); await notifyStatusCardIssueChange(tx, claimed.companyId); - await tx.update(issues).set({ monitorWakeRequestedAt: null, updatedAt: input.now }) + const { patch } = await resolveReleaseUpdate(tx as unknown as Db); + await tx.update(issues).set(patch) .where(issueMonitorClaimCondition(claimed)); }); logger.warn({ err, issueId: claimed.id }, "issue monitor diagnostic could not be recorded"); @@ -786,10 +828,14 @@ export function createHeartbeatScheduling( } } else { let executionDeferredCause: string | null = null; + let executionDeferredRecoveryActionId: string | null = null; const wake = await enqueueWakeup(targetAgentId, { issueStateGuard: { statuses: [claimed.status], assigneeAgentId: claimed.assigneeAgentId, monitorNextCheckAt: scheduledAtIso, monitorWakeRequestedAt: claimed.monitorWakeRequestedAt!.toISOString(), - onExecutionDeferred: cause => { executionDeferredCause = cause; } }, + onExecutionDeferred: (cause, recoveryActionId) => { + executionDeferredCause = cause; + executionDeferredRecoveryActionId = recoveryActionId ?? null; + } }, source: input.source, triggerDetail: input.triggerDetail, reason: wakeReason, @@ -825,7 +871,11 @@ export function createHeartbeatScheduling( ? executionDeferredCause : undefined; const reason = executionDeferredCause ? "execution_reconciliation_required" : "monitor_dispatch_deferred"; await releaseIssueMonitorWithDiagnostic(claimed, input, { - action: "issue.monitor_deferred", reason, ...(blockerCause ? { blockerCause } : {}), + action: "issue.monitor_deferred", + reason, + ...(blockerCause ? { blockerCause } : {}), + blockerRecoveryActionId: executionDeferredRecoveryActionId, + timeoutAt: parseMonitorDate(monitor?.timeoutAt ?? null), }); return { outcome: "skipped" as const, reason }; } @@ -911,8 +961,10 @@ export function createHeartbeatScheduling( } } await releaseIssueMonitorWithDiagnostic(claimed, input, { - action: "issue.monitor_dispatch_failed", reason: "monitor_dispatch_failed", + action: "issue.monitor_dispatch_failed", + reason: "monitor_dispatch_failed", ...(err instanceof HttpError ? { httpStatus: err.status } : {}), + timeoutAt: parseMonitorDate(monitor?.timeoutAt ?? null), }); throw err; } @@ -989,7 +1041,6 @@ export function createHeartbeatScheduling( .update(issues) .set({ monitorWakeRequestedAt: now, - updatedAt: now, }) .where( and( @@ -1039,6 +1090,7 @@ export function createHeartbeatScheduling( noActiveNativeMonitorRun(), sql`${issues.monitorNextCheckAt} is not null`, lte(issues.monitorNextCheckAt, now), + eligibleDeferredMonitorCondition(now), isNull(issues.assigneeUserId), sql`${issues.assigneeAgentId} is not null`, inArray(issues.status, ["in_progress", "in_review"]), @@ -1063,7 +1115,6 @@ export function createHeartbeatScheduling( .update(issues) .set({ monitorWakeRequestedAt: now, - updatedAt: now, }) .where( and( @@ -1071,6 +1122,7 @@ export function createHeartbeatScheduling( noActiveNativeMonitorRun(), sql`${issues.monitorNextCheckAt} is not null`, lte(issues.monitorNextCheckAt, now), + eligibleDeferredMonitorCondition(now), isNull(issues.assigneeUserId), sql`${issues.assigneeAgentId} is not null`, inArray(issues.status, ["in_progress", "in_review"]), @@ -1123,14 +1175,13 @@ export function createHeartbeatScheduling( async function nextIssueMonitorAt(): Promise { if ((await getSchedulingSuppression(true)).suppressed) return null; - const [row] = await db.select({ at: sql`min(greatest(${issues.monitorNextCheckAt}, - ${issues.monitorWakeRequestedAt} + interval '5 minutes' + interval '1 millisecond'))` }) + const [row] = await db.select({ at: nextIssueMonitorAtSelectSql() }) .from(issues).innerJoin(companies, eq(companies.id, issues.companyId)) .where(and(eq(companies.status, "active"), noActiveNativeMonitorRun(), - sql`${issues.monitorNextCheckAt} is not null`, isNull(issues.assigneeUserId), + sql`${issues.monitorNextCheckAt} is not null`, nextIssueMonitorWhereCondition(), + isNull(issues.assigneeUserId), sql`${issues.assigneeAgentId} is not null`, inArray(issues.status, ["in_progress", "in_review"]))); - return row?.at == null ? null : new Date(row.at).getTime(); } diff --git a/server/src/services/issue-execution-policy.ts b/server/src/services/issue-execution-policy.ts index 16d3e8b45f0..32effac8b85 100644 --- a/server/src/services/issue-execution-policy.ts +++ b/server/src/services/issue-execution-policy.ts @@ -1141,7 +1141,22 @@ function applyMonitorTransition(input: TransitionInput, stagePatch: Record).monitorDeferral + : undefined; + patch.executionState = + nextExecutionState && previousDeferral !== undefined + ? { ...nextExecutionState, monitorDeferral: previousDeferral } + : nextExecutionState; } return patch; diff --git a/server/src/services/issue-recovery-actions.ts b/server/src/services/issue-recovery-actions.ts index 9fb786b91fc..fd7462df492 100644 --- a/server/src/services/issue-recovery-actions.ts +++ b/server/src/services/issue-recovery-actions.ts @@ -432,10 +432,18 @@ export function issueRecoveryActionService(db: DbOrTransaction) { if (existing.cause === "native_workspace_finalization_owner_unverified" && input.cause === existing.cause && input.fingerprint === existing.fingerprint && !existing.evidence?.workspaceOwnerStop && existing.nextAction !== input.nextAction) { - const [updated] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], tx => tx.update(issueRecoveryActions).set({ nextAction: input.nextAction, updatedAt: now }) - .where(and(eq(issueRecoveryActions.id, existing.id), - inArray(issueRecoveryActions.status, [...ACTIVE_RECOVERY_ACTION_STATUSES]), - sql`${issueRecoveryActions.evidence}->'workspaceOwnerStop' is null`)).returning(), { companyId: input.companyId, issueId: input.sourceIssueId }); + const [updated] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], async tx => { + const [monitored] = await tx.select({ id: issues.id }).from(issues).where(and( + eq(issues.companyId, input.companyId), + eq(issues.id, input.sourceIssueId), + isNotNull(issues.monitorNextCheckAt), + )).limit(1); + if (monitored) await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); + return tx.update(issueRecoveryActions).set({ nextAction: input.nextAction, updatedAt: now }) + .where(and(eq(issueRecoveryActions.id, existing.id), + inArray(issueRecoveryActions.status, [...ACTIVE_RECOVERY_ACTION_STATUSES]), + sql`${issueRecoveryActions.evidence}->'workspaceOwnerStop' is null`)).returning(); + }, { companyId: input.companyId, issueId: input.sourceIssueId }); if (updated) return toReadModel(updated); } return existing; @@ -651,6 +659,15 @@ export function issueRecoveryActionService(db: DbOrTransaction) { if (waiter) await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionFinalization); }; + const releaseParkedMonitor = async (tx: DbOrTransaction) => { + const [monitored] = await tx.select({ id: issues.id }).from(issues).where(and( + eq(issues.companyId, input.companyId), + eq(issues.id, input.sourceIssueId), + isNotNull(issues.monitorNextCheckAt), + )).limit(1); + if (monitored) await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); + }; + if (input.sourceTerminal) { const [settled] = await dbOrTx.transaction(async tx => { await releaseWaiter(tx as unknown as DbOrTransaction); @@ -672,6 +689,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) { // Resolving another attention releases this issue's preserved Native // waiter to one normal inspection. No recurring monitor or new turn. await releaseWaiter(tx as unknown as DbOrTransaction); + await releaseParkedMonitor(tx as unknown as DbOrTransaction); await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId }); await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId });