fix(server): make scheduled-task edits atomic #11592
main fromrefs/pull/11592/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:L
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 840OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -744,3 +830,11 @@744830 return { task };745831 });746832833+ // Partial edits run inside one transaction: the scoped row is read and834+ // rewritten without another fiber's statements interleaving (the client's835+ // connection serializes transactions), so a delete racing the edit836+ // surfaces as `none` (the UPDATE never inserts) and concurrent disjoint837+ // edits each keep their own columns.838+ const update: ScheduledTaskService["Service"]["update"] = (input) =>839+ Effect.gen(function* () {840+ const task = yield* sql
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/settings/scheduledTasks.logic.ts line 85OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+function modelKey(selection: ModelSelection): string {66+ return `${selection.instanceId}:${selection.model}`;67+}68+69+export function splitModelKey(value: string): ModelSelection | null {70+ const index = value.indexOf(":");71+ if (index <= 0 || index === value.length - 1) return null;72+ return {73+ instanceId: ProviderInstanceId.make(value.slice(0, index)),74+ model: value.slice(index + 1),75+ };76+}77+78+export function workspaceStrategyFromDraft(79+ draft: DraftState,80+): OrchestrationV2ThreadLaunchWorkspaceStrategy {81+ return draft.workspaceMode === "root"82+ ? { type: "root" }83+ : draft.workspaceMode === "existing_worktree"84+ ? { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() }85+ : { type: "worktree", baseRef: draft.baseRef.trim() || "main", startFromOrigin: true };
- apps/web/src/components/settings/scheduledTasks.logic.ts line 94OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +74,21 @@74+ return `${selection.instanceId}:${selection.model}`;75+}76+77+export function splitModelKey(value: string): ModelSelection | null {78+ const index = value.indexOf(":");79+ if (index <= 0 || index === value.length - 1) return null;80+ return {81+ instanceId: ProviderInstanceId.make(value.slice(0, index)),82+ model: value.slice(index + 1),83+ };84+}85+86+export function workspaceStrategyFromDraft(87+ draft: DraftState,88+): OrchestrationV2ThreadLaunchWorkspaceStrategy {89+ const base = draft.baseWorkspaceStrategy;90+ if (draft.workspaceMode === "root") {91+ return base?.type === "root" ? base : { type: "root" };92+ }93+ if (draft.workspaceMode === "existing_worktree") {94+ const worktreePath = draft.existingWorktreePath.trim();
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 1151OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -1161,3 +1131,21 @@1131+ const updated = yield* scheduledTasks1132+ .update({1133+ id: input.scheduledTaskId,1134+ projectId: parent.thread.projectId,1135+ ...(input.title === undefined ? {} : { title: input.title }),1136+ ...(input.prompt === undefined ? {} : { prompt: input.prompt }),1137+ ...(input.enabled === undefined ? {} : { enabled: input.enabled }),1138+ ...(input.schedule === undefined ? {} : { schedule: input.schedule }),1139+ // Rebinding changes where runs execute, so the workspace strategy1140+ // must follow: unbinding a root-strategy task would otherwise run1141+ // loose prompts in the shared project checkout.1142+ ...(input.bindToCurrentThread === undefined1143+ ? {}1144+ : {1145+ threadId: input.bindToCurrentThread ? scope.threadId : null,1146+ workspaceStrategy: scheduledTaskWorkspaceStrategy(input.bindToCurrentThread),1147+ }),1148+ })11611149 .pipe(11621150 Effect.mapError((error) =>11631151 failure("orchestration_error", `Could not update scheduled task: ${error.message}`),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 34OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -22,9 +24,11 @@2224 import * as Effect from "effect/Effect";2325 import * as Layer from "effect/Layer";2426 import * as Option from "effect/Option";27+import * as Predicate from "effect/Predicate";2528 import * as PubSub from "effect/PubSub";2629 import * as Ref from "effect/Ref";2730 import * as Result from "effect/Result";2831 import * as Schema from "effect/Schema";2932 import * as Stream from "effect/Stream";3033 import * as SqlClient from "effect/unstable/sql/SqlClient";34+import { isSqlError } from "effect/unstable/sql/SqlError";
- apps/web/src/components/settings/scheduledTasks.logic.ts line 126OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+ workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,107+): ScheduledTaskUpdateInput | null {108+ const patch: {109+ -readonly [110+ K in Exclude<keyof ScheduledTaskUpdateInput, "id" | "projectId">111+ ]?: ScheduledTaskUpdateInput[K];112+ } = {};113+ const title = draft.title.trim();114+ if (title !== baseline.title.trim()) patch.title = title as ScheduledTaskUpdateInput["title"];115+ const prompt = draft.prompt.trim();116+ if (prompt !== baseline.prompt.trim()) {117+ patch.prompt = prompt as ScheduledTaskUpdateInput["prompt"];118+ }119+ if (draft.enabled !== baseline.enabled) patch.enabled = draft.enabled;120+ const schedule = scheduleFromDraft(draft);121+ if (!sameSchedule(schedule, scheduleFromDraft(baseline))) patch.schedule = schedule;122+ const threadId = draft.threadId || null;123+ // A binding cannot survive a project move — the thread stays in the old124+ // project and the server rejects the mismatched pair. The dialog has no125+ // thread picker, so the only expressible move is unbind-and-move.126+ const nextThreadId = moveDetachesThreadBinding(draft, baseline)
- apps/server/src/mcp/OrchestratorMcpService.ts lines 1732 to 1742OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1195,5 +1167,21 @@1167+ id: input.scheduledTaskId,1168+ projectId: parent.thread.projectId,1169+ ...(input.title === undefined ? {} : { title: input.title }),1170+ ...(input.prompt === undefined ? {} : { prompt: input.prompt }),1171+ ...(input.enabled === undefined ? {} : { enabled: input.enabled }),1172+ ...(input.schedule === undefined ? {} : { schedule: input.schedule }),1173+ // Rebinding changes where runs execute, so the workspace strategy1174+ // must follow: unbinding a root-strategy task would otherwise run1175+ // loose prompts in the shared project checkout.1176+ ...(input.bindToCurrentThread === undefined1177+ ? {}1178+ : {1179+ threadId: input.bindToCurrentThread ? scope.threadId : null,1180+ workspaceStrategy: scheduledTaskWorkspaceStrategy(input.bindToCurrentThread),1181+ }),1182+ })11951183 .pipe(11961184 Effect.mapError((error) =>11971185 failure("orchestration_error", `Could not update scheduled task: ${error.message}`),11981186 ),11991187 );
juliusmarminge requested changes
apps/web/src/components/settings/scheduledTasks.logic.ts line 127OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -0,0 +107,21 @@107+ const patch: {108+ -readonly [109+ K in Exclude<keyof ScheduledTaskUpdateInput, "id" | "projectId">110+ ]?: ScheduledTaskUpdateInput[K];111+ } = {};112+ const title = draft.title.trim();113+ if (title !== baseline.title.trim()) patch.title = title as ScheduledTaskUpdateInput["title"];114+ const prompt = draft.prompt.trim();115+ if (prompt !== baseline.prompt.trim()) {116+ patch.prompt = prompt as ScheduledTaskUpdateInput["prompt"];117+ }118+ if (draft.enabled !== baseline.enabled) patch.enabled = draft.enabled;119+ const schedule = scheduleFromDraft(draft);120+ if (!sameSchedule(schedule, scheduleFromDraft(baseline))) patch.schedule = schedule;121+ if (!sameWorkspaceStrategy(workspaceStrategy, workspaceStrategyFromDraft(baseline))) {122+ // The dialog cannot express every strategy field (`branch`), so a dirty123+ // workspace control patches the fields it owns while fields it cannot124+ // reach are carried over from the live task.125+ patch.workspaceStrategy =126+ task.workspaceStrategy.type === workspaceStrategy.type127+ ? { ...task.workspaceStrategy, ...workspaceStrategy }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
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 870OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -780,0 +850,21 @@850+ const patch: Record<string, unknown> = {};851+ if (input.title !== undefined) patch.title = input.title;852+ if (input.prompt !== undefined) patch.prompt = input.prompt;853+ if (input.enabled !== undefined) patch.enabled = input.enabled ? 1 : 0;854+ if (input.schedule !== undefined) {855+ patch.schedule_json = yield* encodeScheduleJson(input.schedule);856+ }857+ if (input.threadId !== undefined) patch.thread_id = input.threadId;858+ if (input.workspaceStrategy !== undefined) {859+ patch.workspace_strategy_json = yield* encodeWorkspaceStrategyJson(860+ input.workspaceStrategy,861+ );862+ }863+ if (Object.keys(patch).length === 0) return existing;864+ const now = yield* localNow;865+ // Mirror the upsert rule: only a real schedule/enabled change866+ // restarts the run clock — other edits retain the pending due time.867+ const enabled = input.enabled ?? existing.enabled;868+ const schedule = input.schedule ?? existing.schedule;869+ if (enabled !== existing.enabled || !isSameSchedule(existing.schedule, schedule)) {870+ patch.next_run_at = nextRunAt({ enabled, schedule }, now);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx line 677OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -618,13 +609,11 @@618- : {619- type: "worktree",620- baseRef: draft.baseRef.trim() || "main",621- startFromOrigin: draft.startFromOrigin,622- },623- runtimeMode: draft.runtimeMode,624- interactionMode: draft.task?.interactionMode ?? "default",625- creationSource: draft.task?.creationSource ?? "mobile",626- };627609 // Lock before React renders, and keep successful creates locked until the form closes.628610 submissionPending.current = true;629611 setSaving(true);630- const result = await upsert({ environmentId, input });612+ let result: AtomCommandResult<unknown, unknown> | null;613+ if (draft.task !== null) {614+ // Existing tasks save as a dirty-field patch through the atomic update615+ // path: a stale editor can never overwrite fields another client616+ // changed, and a delete racing the save is a typed not-found, not a617+ // resurrection. `taskMissing` already guarantees the task is in the618+ // live list.619+ const liveTask = tasks.data?.tasks.find((task) => task.id === draft.task?.id);
- apps/web/src/components/settings/ScheduledTasksSettings.tsx line 622OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -614,2 +603,20 @@614603 setSaving(true);615- const result = await upsertTask({ environmentId, input });604+ // Existing tasks save as a dirty-field patch through the atomic update605+ // path: a stale editor can never overwrite fields another client changed,606+ // and a delete racing the save is a typed not-found, not a resurrection.607+ let result;608+ if (draft.editingId !== null) {609+ // editingTaskMissing already guarantees the task is in the live list.610+ const editingTask = tasksQuery.data.tasks.find((entry) => entry.id === draft.editingId);611+ if (editingTask === undefined) {612+ setSaving(false);613+ return;614+ }615+ const patch = buildScheduledTaskUpdateInput(616+ draft,617+ baselineDraft,618+ editingTask,619+ modelSelection,620+ workspaceStrategy,621+ );622+ result = patch === null ? null : await updateTask({ environmentId, input: patch });
juliusmarminge closed this
juliusmarminge added labelstriage:keep-open
juliusmarminge reopened this
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 402OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -0,0 +243,21 @@243+ // next_run_at is a freeform string at the schema level; a stored value244+ // that cannot parse as a DateTime would defect the poll below, so the245+ // row is skipped here like any other corrupt row.246+ if (task.nextRunAt === null || Option.isSome(DateTime.make(task.nextRunAt))) {247+ tasks.push(task);248+ } else {249+ yield* Effect.logWarning("Skipping schedule task row with invalid next_run_at", {250+ taskId: row.task_id,251+ });252+ }253+ } else {254+ yield* Effect.logWarning("Skipping undecodable schedule task row", {255+ taskId: row.task_id,256+ cause: decoded.failure,257+ });258+ }259+ }260+ return tasks;261+});262+263+export const layer = Layer.effect(apps/server/src/scheduledTasks/ScheduledTaskService.ts line 248OutdatedResolvedby saphid(GitHub profile, opens in a new tab)@@ -0,0 +103,21 @@103+ * patch fails when the merged pair would bind the task to a thread outside104+ * its project (the dispatch check in `getProjectThread` would reject it).105+ * Unbind explicitly with `threadId: null` to move a bound task.106+ */107+ readonly update: (108+ input: ScheduledTaskUpdateInput,109+ ) => Effect.Effect<Option.Option<ScheduledTaskMutationResult>, ScheduledTaskError>;110+ /** Partial update flipping only the enabled flag; never touches other fields. */111+ readonly setEnabled: (112+ input: ScheduledTaskSetEnabledInput,113+ ) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;114+ readonly delete: (115+ input: ScheduledTaskDeleteInput,116+ ) => Effect.Effect<Option.Option<ScheduledTaskDeleteResult>, ScheduledTaskError>;117+ readonly runNow: (118+ input: ScheduledTaskRunNowInput,119+ ) => Effect.Effect<ScheduledTaskRunNowResult, ScheduledTaskError>;120+ }121+>()("t3/scheduledTasks/ScheduledTaskService") {}122+123+function taskError(message: string, input?: { taskId?: ScheduledTaskId; cause?: unknown }) {
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 998 to 1000OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -726,0 +980,21 @@980+ projectId: input.projectId,981+ threadId: input.threadId ?? null,982+ workspaceStrategy: input.workspaceStrategy,983+ modelSelection: input.modelSelection,984+ runtimeMode: input.runtimeMode,985+ interactionMode: input.interactionMode,986+ createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",987+ creationSource: input.creationSource ?? "web",988+ createdAt: existingTask?.createdAt ?? iso(now),989+ updatedAt: iso(now),990+ nextRunAt: scheduleUnchanged991+ ? existingTask.nextRunAt992+ : nextRunAt({ enabled: input.enabled, schedule: input.schedule }, now),993+ lastRunAt: existingTask?.lastRunAt ?? null,994+ lastRunStatus: existingTask?.lastRunStatus ?? "never",995+ lastRunError: existingTask?.lastRunError ?? null,996+ runCount: existingTask?.runCount ?? 0,997+ };998+ if (task.threadId !== null) {999+ yield* requireThreadInProject(task.id, task.projectId, task.threadId);1000+ }
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 1348 to 1357Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -773,0 +1049,21 @@1049+ "Scheduled task changed since it was loaded; retry the operation.",1050+ { taskId: input.id },1051+ );1052+ }1053+ // Patches merge with whatever concurrent edits already1054+ // committed, so the resulting pair must still be dispatchable:1055+ // a move keeps an existing threadId only when that thread1056+ // belongs to the destination project, and a binding update1057+ // keeps the current project. Passing `threadId: null` in the1058+ // same patch is the explicit unbind that lets a bound task move.1059+ if (input.threadId !== undefined || input.nextProjectId !== undefined) {1060+ const mergedThreadId =1061+ input.threadId === undefined ? existing.threadId : input.threadId;1062+ if (mergedThreadId !== null) {1063+ yield* requireThreadInProject(1064+ input.id,1065+ input.nextProjectId ?? existing.projectId,1066+ mergedThreadId,1067+ );1068+ }1069+ }
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed