fix(server): pause scheduled tasks bound to archived threads #11635
Closedsaphid(GitHub profile, opens in a new tab)wants to merge 27 commits into
main fromrefs/pull/11635/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/persistence/Migrations/OrchestrationV2/ScheduledTasks.ts line 25OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -22,3 +22,4 @@2222 creation_source TEXT NOT NULL,2323 created_at TEXT NOT NULL,2424 updated_at TEXT NOT NULL,25+ enabled_seq INTEGER,
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/mcp/OrchestratorMcpService.ts line 1217OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1143,10 +1207,11 @@1143- threadId,1144- workspaceStrategy,1145- modelSelection: existing.modelSelection,1146- runtimeMode: existing.runtimeMode,1147- interactionMode: existing.interactionMode,1148- createdBy: existing.createdBy,1149- creationSource: existing.creationSource,1150- };1151- const { task } = yield* scheduledTasks1152- .upsert(upsertInput)1207+ // The modes that will govern the task's next run — its bound1208+ // destination thread's, or its stored modes once unbound — must not1209+ // exceed the caller's, or a restricted caller could arm work it could1210+ // never dispatch directly.1211+ const executionModes = yield* scheduledTaskExecutionModes(1212+ scope,1213+ parent,1214+ existing,1215+ input.bindToCurrentThread,1216+ );1217+ yield* requireTaskModeAccess(parent, executionModes);
- apps/server/src/mcp/OrchestratorMcpService.ts line 1149OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1062,5 +1129,21 @@1129+ failure(1130+ "orchestration_error",1131+ `Unable to read thread ${destinationId}: ${errorMessage(error)}`,1132+ ),1133+ ),1134+ );1135+ // A missing or cross-project shell can never accept the run, so the1136+ // residual privilege is the task's stored modes once rebound.1137+ return shell === null || shell.projectId !== parent.thread.projectId1138+ ? { runtimeMode: task.runtimeMode, interactionMode: task.interactionMode }1139+ : { runtimeMode: shell.runtimeMode, interactionMode: shell.interactionMode };1140+ });1141+10621142 return OrchestratorMcpService.of({10631143 scheduleTask: (scope, input) =>10641144 Effect.gen(function* () {10651145 yield* requireCapability(scope);10661146 const parent = yield* loadProjection(scope.threadId);1147+ // The new task inherits this thread's runtime/interaction modes, so1148+ // the only additional requirement is a live caller-owned run.1149+ yield* requireActiveParentRun(scope, parent);
- apps/server/src/mcp/OrchestratorMcpService.ts lines 1128 to 1131OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1061,0 +1111,21 @@1111+ const destinationId =1112+ bindToCurrentThread === true1113+ ? scope.threadId1114+ : bindToCurrentThread === false1115+ ? null1116+ : task.threadId;1117+ if (destinationId === null || destinationId === scope.threadId) {1118+ return destinationId === null1119+ ? { runtimeMode: task.runtimeMode, interactionMode: task.interactionMode }1120+ : {1121+ runtimeMode: parent.thread.runtimeMode,1122+ interactionMode: parent.thread.interactionMode,1123+ };1124+ }1125+ const shell = yield* threadManagement1126+ .getThreadShell(destinationId)1127+ .pipe(1128+ Effect.mapError((error) =>1129+ failure(1130+ "orchestration_error",1131+ `Unable to read thread ${destinationId}: ${errorMessage(error)}`,
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 36OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -22,9 +26,11 @@2226 import * as Effect from "effect/Effect";2327 import * as Layer from "effect/Layer";2428 import * as Option from "effect/Option";29+import * as Predicate from "effect/Predicate";2530 import * as PubSub from "effect/PubSub";2631 import * as Ref from "effect/Ref";2732 import * as Result from "effect/Result";2833 import * as Schema from "effect/Schema";2934 import * as Stream from "effect/Stream";3035 import * as SqlClient from "effect/unstable/sql/SqlClient";36+import { isSqlError } from "effect/unstable/sql/SqlError";
- apps/server/src/mcp/OrchestratorMcpService.ts line 1172OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -1095,0 +1152,21 @@1152+ : bindToCurrentThread === false1153+ ? null1154+ : task.threadId;1155+ if (destinationId === null || destinationId === scope.threadId) {1156+ return destinationId === null1157+ ? { runtimeMode: task.runtimeMode, interactionMode: task.interactionMode }1158+ : {1159+ runtimeMode: parent.thread.runtimeMode,1160+ interactionMode: parent.thread.interactionMode,1161+ };1162+ }1163+ const shell = yield* threadManagement1164+ .getThreadShell(destinationId)1165+ .pipe(1166+ Effect.mapError((error) =>1167+ failure("orchestration_error", `Unable to read thread ${destinationId}.`, error),1168+ ),1169+ );1170+ // A missing or cross-project shell can never accept the run, so the1171+ // residual privilege is the task's stored modes once rebound.1172+ return shell === null || shell.projectId !== parent.thread.projectId
- apps/web/src/components/settings/ScheduledTasksSettings.tsx line 1351OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -592,20 +557 @@592- ? { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() }593- : {594- type: "worktree",595- baseRef: draft.baseRef.trim() || "main",596- startFromOrigin: draft.startFromOrigin,597- };598- const input: ScheduledTaskUpsertInput = {599- ...(draft.editingId ? { id: draft.editingId as ScheduledTaskId, requireExisting: true } : {}),600- title: draft.title.trim(),601- prompt: draft.prompt.trim(),602- enabled: draft.enabled,603- schedule,604- projectId: selectedProjectId as ProjectId,605- threadId: draft.threadId ? (draft.threadId as ThreadId) : null,606- workspaceStrategy,607- modelSelection,608- runtimeMode: draft.runtimeMode,609- interactionMode: draft.interactionMode,610- creationSource: "web",611- };557+ const workspaceStrategy = workspaceStrategyFromDraft(draft);
- apps/web/src/components/settings/scheduledTasksSettings.logic.ts line 138OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -73,0 +118,21 @@118+ };119+}120+121+function modelKey(selection: ModelSelection): string {122+ return `${selection.instanceId}:${selection.model}`;123+}124+125+export function workspaceStrategyReady(draft: DraftState): boolean {126+ return (127+ draft.workspaceMode !== "existing_worktree" || draft.existingWorktreePath.trim().length > 0128+ );129+}130+131+export function workspaceStrategyFromDraft(132+ draft: DraftState,133+ base: OrchestrationV2ThreadLaunchWorkspaceStrategy | null = draft.baseWorkspaceStrategy,134+): OrchestrationV2ThreadLaunchWorkspaceStrategy {135+ // `base` carries the fields the editor cannot express: the task's live136+ // strategy when building an edit patch, the draft's open-time baseline137+ // elsewhere.138+ if (draft.workspaceMode === "root") {apps/server/src/scheduledTasks/ScheduledTaskService.ts line 568OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -296,0 +548,21 @@548+ ? cause549+ : taskError("Could not pause schedule tasks bound to the thread.", { cause }),550+ ),551+ ),552+ );553+ if (paused.length === 0) return;554+ yield* Effect.logInfo("Paused schedule tasks bound to a thread that no longer accepts runs", {555+ threadId,556+ taskIds: paused.map((row) => row.task_id),557+ });558+ yield* notifyChanged;559+ });560+561+ // "A committed archive postdates this task's enablement." Used by the562+ // pause and by the fire-time claim so an archive+unarchive pair still563+ // queued for the reactor pauses the task rather than dispatching a run564+ // the explicit re-enable was never given. The subquery is NULL for a565+ // never-archived thread, which never satisfies the predicate.566+ const staleArchiveCommitted = (threadId: ThreadId) => sql`567+ (568+ SELECT MAX(sequence) FROM orchestration_events
- apps/server/src/mcp/OrchestratorMcpService.ts lines 2107 to 2113Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1281,4 +1427,18 @@1427+ // must follow: unbinding a root-strategy task would otherwise run1428+ // loose prompts in the shared project checkout.1429+ ...(input.bindToCurrentThread === undefined1430+ ? {}1431+ : {1432+ threadId: input.bindToCurrentThread ? scope.threadId : null,1433+ workspaceStrategy: scheduledTaskWorkspaceStrategy(input.bindToCurrentThread),1434+ }),1435+ })12811436 .pipe(1282- Effect.mapError((error) =>1283- failure("orchestration_error", `Could not update scheduled task: ${error.message}`),1284- ),1437+ Effect.catchTags({1438+ ScheduledTaskError: (error) =>1439+ Effect.fail(1440+ failure(1441+ "orchestration_error",1442+ `Could not update scheduled task: ${error.message}`,1443+ ),1444+ ),
juliusmarminge closed this
juliusmarminge added labelstriage:keep-open
juliusmarminge reopened this
- apps/server/src/persistence/Migrations/080_ScheduledTasksEnabledSeq.ts lines 10 to 15Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,15 @@1+import * as Effect from "effect/Effect";2+import * as SqlClient from "effect/unstable/sql/SqlClient";3+4+export default Effect.gen(function* () {5+ const sql = yield* SqlClient.SqlClient;6+ const columns = yield* sql<{ readonly name: string }>`7+ PRAGMA table_info(scheduled_tasks)8+ `;9+10+ if (!columns.some((column) => column.name === "enabled_seq")) {11+ yield* sql`12+ ALTER TABLE scheduled_tasks13+ ADD COLUMN enabled_seq INTEGER14+ `;15+ }apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 854 to 870Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -297,0 +570,21 @@570+ // never compacted for non-legacy commands — an accepted thread.archive571+ // receipt's result_sequence is the archived event's sequence — so the572+ // watermark unions both sources. Pin the partial archive index so the573+ // event lookup never walks the thread's unrelated event history.574+ const staleArchiveCommitted = (threadId: ThreadId) => sql`575+ (576+ SELECT MAX(sequence) FROM (577+ SELECT MAX(sequence) AS sequence FROM orchestration_events578+ INDEXED BY orchestration_events_v2_archived_threads_idx579+ WHERE aggregate_kind = 'thread' AND stream_id = ${threadId}580+ AND event_type = 'thread.archived'581+ AND application_event_version = 2582+ UNION ALL583+ SELECT MAX(result_sequence) AS sequence FROM orchestration_command_receipts584+ WHERE aggregate_kind = 'thread' AND aggregate_id = ${threadId}585+ AND command_type = 'thread.archive'586+ AND status = 'accepted'587+ AND result_sequence > 0588+ )589+ ) >= COALESCE(enabled_seq, -1)590+ `;
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 1670 to 1683OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -772,0 +1663,21 @@1663+ }1664+ }1665+ // The modes governing runs under the post-update binding are1666+ // re-resolved here — a destination's mode change committed1667+ // since the caller's authorization must fail the write, not1668+ // silently elevate the task. The destination lives under the1669+ // post-move project.1670+ yield* ensureExpectedExecutionModes({1671+ taskId: input.id,1672+ projectId: nextProjectId,1673+ threadId: nextThreadId,1674+ task: existing,1675+ ...(input.expectedExecutionRuntimeMode === undefined1676+ ? {}1677+ : { expectedExecutionRuntimeMode: input.expectedExecutionRuntimeMode }),1678+ ...(input.expectedExecutionInteractionMode === undefined1679+ ? {}1680+ : {1681+ expectedExecutionInteractionMode: input.expectedExecutionInteractionMode,1682+ }),1683+ });apps/web/src/components/settings/scheduledTasks.logic.ts line 40OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +20,21 @@20+}21+22+export function workspaceStrategyFromDraft(23+ draft: DraftState,24+): OrchestrationV2ThreadLaunchWorkspaceStrategy {25+ if (draft.workspaceMode === "root") return { type: "root" };26+ if (draft.workspaceMode === "existing_worktree") {27+ return { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() };28+ }29+ return {30+ type: "worktree",31+ baseRef: draft.baseRef.trim() || "main",32+ startFromOrigin: draft.startFromOrigin,33+ };34+}35+36+// The dialog has no thread picker, so a bound task's only expressible37+// project move is unbind-and-move — the thread cannot follow across38+// projects. The Project field surfaces this as a hint before saving.39+export function moveDetachesThreadBinding(draft: DraftState, baseline: DraftState): boolean {40+ return draft.threadId !== "" && draft.projectId !== baseline.projectId;
Sign in to join this conversation.





Bugbot is paused — on-demand spend limit reached
Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.
A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.