offPeakTaskRepo.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. import {
  2. isTasksStorageMigrated,
  3. isTasksStoragePrepared,
  4. } from "#src/session/tasksDatabase/prepared.js";
  5. /* eslint-disable max-lines -- 与 automationRepo 同理:off-peak 仓库集中维护 off_peak_tasks 的
  6. sqlite schema、状态机守卫写入与调度认领,稳定后再按读写职责拆分。 */
  7. /* off-peak 任务仓库:off_peak_tasks 的 sqlite schema、状态机守卫写入与调度认领。
  8. 与 automation 共用 tasks-index.sqlite 与 Repo 模式,但表/状态机/常量全部独立,
  9. 禁止往 automations 表或 ZCodeAutomation 类型上加字段。 */
  10. import { mkdir } from "node:fs/promises";
  11. import { createRequire } from "node:module";
  12. import { dirname } from "node:path";
  13. import { randomUUID } from "node:crypto";
  14. import {
  15. OFF_PEAK_TERMINAL_STATUSES,
  16. modelSelectionSchema,
  17. resolveWorkspaceKey,
  18. type ZCodeOffPeakTask,
  19. type ZCodeOffPeakTaskCreateParams,
  20. type ZCodeOffPeakTaskStatus,
  21. type ZCodeTaskMode,
  22. } from "@zcode/shared";
  23. import { getTasksIndexDatabasePath } from "#src/paths.js";
  24. import { runTasksDatabaseMigrations } from "#src/session/tasksDatabase/migrations.js";
  25. const require = createRequire(import.meta.url);
  26. const { DatabaseSync } = require("node:sqlite") as typeof import("node:sqlite");
  27. type DatabaseSyncInstance = InstanceType<typeof DatabaseSync>;
  28. /** 认领超时回收:claim_running=1 超过该时长仍未结算,视为持有者已崩溃,允许重新认领。
  29. 独立于 automation 的 CLAIM_STALE_MS(语义相同、常量独立一份,勿互相引用)。 */
  30. export const OFF_PEAK_CLAIM_STALE_MS = 10 * 60_000;
  31. /** 终态 SQL IN 片段;OFF_PEAK_TERMINAL_STATUSES 的单一来源投影。 */
  32. const TERMINAL_SQL_LIST = OFF_PEAK_TERMINAL_STATUSES.map((s) => `'${s}'`).join(", ");
  33. interface OffPeakTaskRow {
  34. off_peak_task_id: string;
  35. server_ticket_id: string | null;
  36. title: string;
  37. conversation_id: string | null;
  38. session_id: string | null;
  39. /** list() 联查 tasks-index 得到的绑定会话标题;单行读取不带该列。 */
  40. session_title?: string | null;
  41. prompt: string;
  42. permission_mode: string;
  43. model: string | null;
  44. thought_level: string | null;
  45. model_selection: string | null;
  46. workspace_key: string;
  47. workspace_path: string;
  48. workspace_identity: string | null;
  49. status: string;
  50. queued_at: number;
  51. started_at: number | null;
  52. ended_at: number | null;
  53. failure_reason: string | null;
  54. files_changed: number | null;
  55. settled_at: number | null;
  56. history_deleted_at: number | null;
  57. registered_at: number | null;
  58. schedulable: number;
  59. queue_position: number | null;
  60. next_poll_at: number | null;
  61. claim_running: number;
  62. claimed_at: number | null;
  63. attempt_count: number;
  64. last_error: string | null;
  65. created_at: number;
  66. updated_at: number;
  67. }
  68. function rowToTask(row: OffPeakTaskRow): ZCodeOffPeakTask {
  69. const modelSelection = readOffPeakModelSelection(row);
  70. return {
  71. offPeakTaskId: row.off_peak_task_id,
  72. serverTicketId: row.server_ticket_id ?? undefined,
  73. title: row.title,
  74. conversationId: row.conversation_id ?? undefined,
  75. sessionId: row.session_id ?? undefined,
  76. ...(row.session_title ? { sessionTitle: row.session_title } : {}),
  77. prompt: row.prompt,
  78. permissionMode: row.permission_mode as ZCodeTaskMode,
  79. ...(modelSelection ? { modelSelection } : {}),
  80. ...(!modelSelection
  81. ? {
  82. modelSelectionIssue: {
  83. code: "repair-required" as const,
  84. },
  85. }
  86. : {}),
  87. workspaceKey: row.workspace_key,
  88. workspacePath: row.workspace_path,
  89. workspaceIdentity: row.workspace_identity ?? undefined,
  90. status: row.status as ZCodeOffPeakTaskStatus,
  91. queuedAt: row.queued_at,
  92. startedAt: row.started_at ?? undefined,
  93. endedAt: row.ended_at ?? undefined,
  94. failureReason: row.failure_reason ?? undefined,
  95. filesChanged: row.files_changed ?? undefined,
  96. settledAt: row.settled_at ?? undefined,
  97. historyDeletedAt: row.history_deleted_at ?? undefined,
  98. registeredAt: row.registered_at ?? undefined,
  99. schedulable: row.schedulable === 1,
  100. queuePosition: row.queue_position ?? undefined,
  101. nextPollAt: row.next_poll_at ?? undefined,
  102. createdAt: row.created_at,
  103. updatedAt: row.updated_at,
  104. };
  105. }
  106. function readOffPeakModelSelection(row: OffPeakTaskRow): ZCodeOffPeakTask["modelSelection"] | null {
  107. if (row.model_selection) {
  108. try {
  109. const parsed = modelSelectionSchema.safeParse(JSON.parse(row.model_selection));
  110. if (parsed.success) return parsed.data;
  111. } catch {
  112. // 继续尝试已发布旧列的单向导入。
  113. }
  114. }
  115. // 旧单列没有 Provider Family,不能安全迁移到任一新 Off-Peak Provider。
  116. return null;
  117. }
  118. function serializeOffPeakModelSelection(
  119. selection: NonNullable<ZCodeOffPeakTask["modelSelection"]>,
  120. ): string {
  121. const options = selection.options;
  122. return JSON.stringify(
  123. modelSelectionSchema.parse({
  124. providerId: selection.providerId,
  125. modelId: selection.modelId,
  126. ...(options && Object.keys(options).length > 0 ? { options } : {}),
  127. }),
  128. );
  129. }
  130. /**
  131. * 闲时任务存储仓库(tasks-index.sqlite,WAL、多进程安全)。
  132. *
  133. * 仓库只做存储与原子状态迁移,守卫两条不变量:
  134. * 终态不可逆出;单任务认领 single-flight(任务间并发不设本地上限)。
  135. * 排队/晋级语义在服务端,仓库不感知——schedulable 只是 host 轮询写回的快照。
  136. */
  137. /** INSERT 撞上 idx_off_peak_bound_active(并发双创建的失败方)。 */
  138. export function isOffPeakBoundSessionConflict(error: unknown): boolean {
  139. return (
  140. error instanceof Error &&
  141. /UNIQUE constraint failed: off_peak_tasks\.workspace_key, off_peak_tasks\.session_id/.test(
  142. error.message,
  143. )
  144. );
  145. }
  146. export class OffPeakTaskRepo {
  147. private db: DatabaseSyncInstance | null = null;
  148. private dbPath: string | null = null;
  149. private initializePromise: Promise<void> | null = null;
  150. // 同 AutomationRepo,db 路径不能依赖进程级全局 _dataBaseDir:
  151. // vitest threads 并发跑测试文件时全局值被互相覆盖,存在写进真实库的窗口。
  152. // 改为构造期固定 dbPath,测试通过依赖注入传入临时库路径,生产路径不传则回退默认。
  153. private readonly resolvedDbPath: string | null;
  154. constructor(
  155. dbPath?: string,
  156. private readonly startupBusyTimeoutMs = 5000,
  157. ) {
  158. this.resolvedDbPath = dbPath?.trim() || null;
  159. }
  160. private resolveDbPath(): string {
  161. return this.resolvedDbPath ?? getTasksIndexDatabasePath();
  162. }
  163. async ensureReady(): Promise<void> {
  164. const path = this.resolveDbPath();
  165. if (this.dbPath && this.dbPath !== path) {
  166. this.close();
  167. }
  168. if (!this.initializePromise) {
  169. this.initializePromise = this.initialize(path).catch((error) => {
  170. this.close();
  171. throw error;
  172. });
  173. }
  174. await this.initializePromise;
  175. }
  176. close(options?: { throwOnError?: boolean }): void {
  177. let closeError: unknown;
  178. try {
  179. this.db?.close();
  180. } catch (error) {
  181. closeError = error;
  182. // ignore
  183. }
  184. this.db = null;
  185. this.dbPath = null;
  186. this.initializePromise = null;
  187. if (options?.throwOnError && closeError) throw closeError;
  188. }
  189. private async initialize(path: string): Promise<void> {
  190. await mkdir(dirname(path), { recursive: true });
  191. if (!this.db) {
  192. this.db = new DatabaseSync(path);
  193. this.dbPath = path;
  194. this.db.exec(`PRAGMA busy_timeout = ${this.startupBusyTimeoutMs}`);
  195. this.db.exec("PRAGMA journal_mode = WAL");
  196. this.db.exec("PRAGMA synchronous = NORMAL");
  197. }
  198. // Worker 已完成该路径的原始准备,业务连接不再重复全表修复。
  199. if (isTasksStoragePrepared(path, this.db)) return;
  200. if (!isTasksStorageMigrated(path, this.db)) runTasksDatabaseMigrations(this.db);
  201. // 早期预留了 awaiting_approval,但生产链路从未写入,UI 却把它包装成可用能力。
  202. // 当前确认只走普通 session;迁移遗留行回 running,随后由启动回收按真实进程状态处理。
  203. this.getDatabase()
  204. .prepare(
  205. `UPDATE off_peak_tasks
  206. SET status = 'running', updated_at = @now
  207. WHERE status = 'awaiting_approval'`,
  208. )
  209. .run({ now: Date.now() });
  210. }
  211. private getDatabase(): DatabaseSyncInstance {
  212. if (!this.db) {
  213. throw new Error("OffPeakTaskRepo 未初始化:请先 await ensureReady()");
  214. }
  215. return this.db;
  216. }
  217. private hasTasksIndexTable(): boolean {
  218. return Boolean(
  219. this.getDatabase()
  220. .prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tasks'`)
  221. .get(),
  222. );
  223. }
  224. private getRow(offPeakTaskId: string): OffPeakTaskRow | null {
  225. const row = this.getDatabase()
  226. .prepare(`SELECT * FROM off_peak_tasks WHERE off_peak_task_id = ?`)
  227. .get(offPeakTaskId) as OffPeakTaskRow | undefined;
  228. return row ?? null;
  229. }
  230. // ---- 管理 CRUD ----
  231. /**
  232. * 创建即入队(status=queued)。取号在 service 层先行(POST /ticket 成功才落库),
  233. * 取号结果经 options 一并写入;mock 先行阶段允许不带服务端字段。
  234. */
  235. async create(
  236. params: ZCodeOffPeakTaskCreateParams,
  237. options?: {
  238. /** 测试注入用;缺省 Date.now()。 */
  239. now?: number;
  240. /** service 层先取号后落库时外部指定主键(取号需先有 task_id);缺省内部生成。 */
  241. offPeakTaskId?: string;
  242. serverTicketId?: string;
  243. queuePosition?: number;
  244. registeredAt?: number;
  245. /** 取号即 ready(低峰空闲时服务端可直接晋级)时随建随派。 */
  246. schedulable?: boolean;
  247. },
  248. ): Promise<ZCodeOffPeakTask> {
  249. await this.ensureReady();
  250. const now = options?.now ?? Date.now();
  251. const offPeakTaskId = options?.offPeakTaskId ?? `offpeak-${randomUUID()}`;
  252. const workspaceKey = resolveWorkspaceKey({
  253. workspacePath: params.workspacePath,
  254. workspaceIdentity: params.workspaceIdentity,
  255. });
  256. this.getDatabase()
  257. .prepare(
  258. `INSERT INTO off_peak_tasks (
  259. off_peak_task_id, server_ticket_id, title, conversation_id, session_id,
  260. prompt, permission_mode, model, thought_level, model_selection,
  261. workspace_key, workspace_path, workspace_identity,
  262. status, queued_at, registered_at, schedulable, queue_position,
  263. claim_running, attempt_count, created_at, updated_at
  264. ) VALUES (
  265. @off_peak_task_id, @server_ticket_id, @title, NULL, @session_id,
  266. @prompt, @permission_mode, @model, @thought_level, @model_selection,
  267. @workspace_key, @workspace_path, @workspace_identity,
  268. 'queued', @queued_at, @registered_at, @schedulable, @queue_position,
  269. 0, 0, @now, @now
  270. )`,
  271. )
  272. .run({
  273. off_peak_task_id: offPeakTaskId,
  274. server_ticket_id: options?.serverTicketId ?? null,
  275. title: params.title,
  276. // 会话内创建绑定当前会话;conversation_id 仍等首跑回填(非空 = 已跑过)。
  277. session_id: params.boundSessionId ?? null,
  278. prompt: params.prompt,
  279. permission_mode: params.permissionMode,
  280. model: null,
  281. thought_level: null,
  282. model_selection: serializeOffPeakModelSelection(params.modelSelection),
  283. workspace_key: workspaceKey,
  284. workspace_path: params.workspacePath,
  285. workspace_identity: params.workspaceIdentity ?? null,
  286. queued_at: now,
  287. registered_at: options?.registeredAt ?? null,
  288. schedulable: options?.schedulable ? 1 : 0,
  289. queue_position: options?.queuePosition ?? null,
  290. now,
  291. });
  292. return rowToTask(this.getRow(offPeakTaskId)!);
  293. }
  294. async list(scope?: {
  295. workspacePath?: string;
  296. workspaceIdentity?: string;
  297. }): Promise<ZCodeOffPeakTask[]> {
  298. await this.ensureReady();
  299. const workspaceKey = scope?.workspacePath
  300. ? resolveWorkspaceKey({
  301. workspacePath: scope.workspacePath,
  302. workspaceIdentity: scope.workspaceIdentity,
  303. })
  304. : null;
  305. // 绑定会话标题联查 tasks-index 同库 tasks 表(卡片展示);独立库(测试/迁移前)无该表则不联。
  306. const withSessionTitle = this.hasTasksIndexTable();
  307. const rows = this.getDatabase()
  308. .prepare(
  309. withSessionTitle
  310. ? `SELECT t.*, s.title AS session_title FROM off_peak_tasks t
  311. LEFT JOIN tasks s ON s.workspace_key = t.workspace_key AND s.task_id = t.session_id
  312. WHERE (@workspace_key IS NULL OR t.workspace_key = @workspace_key)
  313. ORDER BY t.created_at DESC`
  314. : `SELECT * FROM off_peak_tasks
  315. WHERE (@workspace_key IS NULL OR workspace_key = @workspace_key)
  316. ORDER BY created_at DESC`,
  317. )
  318. .all({ workspace_key: workspaceKey }) as unknown as OffPeakTaskRow[];
  319. return rows.map(rowToTask);
  320. }
  321. async get(offPeakTaskId: string): Promise<ZCodeOffPeakTask | null> {
  322. await this.ensureReady();
  323. const row = this.getRow(offPeakTaskId);
  324. return row ? rowToTask(row) : null;
  325. }
  326. /**
  327. * Registry 变化使已保存 Selection 失效时,保留原模型与档位供用户修复或后续可靠恢复,
  328. * 同时清空正式 Selection 并撤销可调度状态,避免旧配置继续被 scheduler 认领。
  329. */
  330. async invalidateModelSelection(
  331. offPeakTaskId: string,
  332. modelSelection: NonNullable<ZCodeOffPeakTask["modelSelection"]>,
  333. options?: { now?: number },
  334. ): Promise<ZCodeOffPeakTask | null> {
  335. await this.ensureReady();
  336. const db = this.getDatabase();
  337. db.exec("BEGIN IMMEDIATE");
  338. try {
  339. const current = this.getRow(offPeakTaskId);
  340. if (!current) {
  341. db.exec("COMMIT");
  342. return null;
  343. }
  344. const currentSelection = readOffPeakModelSelection(current);
  345. if (
  346. currentSelection &&
  347. (currentSelection.providerId !== modelSelection.providerId ||
  348. currentSelection.modelId !== modelSelection.modelId ||
  349. currentSelection.options?.reasoningLevel !== modelSelection.options?.reasoningLevel)
  350. ) {
  351. // 另一进程已完成用户修复,以更新后的值为准,不能用旧 Registry 观察覆盖它。
  352. db.exec("COMMIT");
  353. return rowToTask(current);
  354. }
  355. db.prepare(
  356. `UPDATE off_peak_tasks
  357. SET model = @model, thought_level = @thought_level,
  358. model_selection = NULL, schedulable = 0, updated_at = @now
  359. WHERE off_peak_task_id = @id`,
  360. ).run({
  361. id: offPeakTaskId,
  362. model: modelSelection.modelId,
  363. thought_level: modelSelection.options?.reasoningLevel ?? null,
  364. now: options?.now ?? Date.now(),
  365. });
  366. const invalidated = this.getRow(offPeakTaskId);
  367. db.exec("COMMIT");
  368. return invalidated ? rowToTask(invalidated) : null;
  369. } catch (error) {
  370. db.exec("ROLLBACK");
  371. throw error;
  372. }
  373. }
  374. /** 卡片 Delete:任何状态均可删(非终态删除的服务端核销由 service 层先行取消处理)。 */
  375. async delete(offPeakTaskId: string): Promise<void> {
  376. await this.ensureReady();
  377. this.getDatabase()
  378. .prepare(`DELETE FROM off_peak_tasks WHERE off_peak_task_id = ?`)
  379. .run(offPeakTaskId);
  380. }
  381. /**
  382. * 仅隐藏 History 行:任务必须已经实际启动;重复调用幂等。
  383. * 不修改状态、session、started/ended/filesChanged 或服务端核销字段。
  384. */
  385. async markHistoryDeleted(
  386. offPeakTaskId: string,
  387. options?: { now?: number },
  388. ): Promise<ZCodeOffPeakTask | null> {
  389. await this.ensureReady();
  390. const row = this.getRow(offPeakTaskId);
  391. if (!row || row.started_at === null) return row ? rowToTask(row) : null;
  392. if (row.history_deleted_at !== null) return rowToTask(row);
  393. const now = options?.now ?? Date.now();
  394. this.getDatabase()
  395. .prepare(
  396. `UPDATE off_peak_tasks
  397. SET history_deleted_at = @now, updated_at = @now
  398. WHERE off_peak_task_id = @id AND started_at IS NOT NULL`,
  399. )
  400. .run({ id: offPeakTaskId, now });
  401. return rowToTask(this.getRow(offPeakTaskId)!);
  402. }
  403. /** 创建上限的本地预判用(权威是服务端取号 429/3103)。 */
  404. async countNonTerminal(): Promise<number> {
  405. await this.ensureReady();
  406. const row = this.getDatabase()
  407. .prepare(
  408. `SELECT COUNT(*) AS n FROM off_peak_tasks WHERE status NOT IN (${TERMINAL_SQL_LIST})`,
  409. )
  410. .get() as { n: number };
  411. return row.n;
  412. }
  413. /** 本会话是否已有未终态绑定任务(创建前预检;索引 idx_off_peak_bound_active 同条件)。 */
  414. async hasActiveBoundTask(workspaceKey: string, sessionId: string): Promise<boolean> {
  415. await this.ensureReady();
  416. const row = this.getDatabase()
  417. .prepare(
  418. `SELECT 1 AS hit FROM off_peak_tasks
  419. WHERE workspace_key = @workspace_key AND session_id = @session_id
  420. AND status NOT IN (${TERMINAL_SQL_LIST})
  421. LIMIT 1`,
  422. )
  423. .get({ workspace_key: workspaceKey, session_id: sessionId }) as { hit: number } | undefined;
  424. return row !== undefined;
  425. }
  426. /** 执行中计数:keep-awake powerSaveBlocker 判据。 */
  427. async countActive(): Promise<number> {
  428. await this.ensureReady();
  429. const row = this.getDatabase()
  430. .prepare(`SELECT COUNT(*) AS n FROM off_peak_tasks WHERE status = 'running'`)
  431. .get() as { n: number };
  432. return row.n;
  433. }
  434. /**
  435. * 编辑窗口期字段:仅 queued/paused 可编辑;票只锁队列身份,prompt 派发时才读。
  436. * modelSelection 只能替换为另一份明确 Selection;undefined = 不改。
  437. */
  438. async updateEditableFields(
  439. offPeakTaskId: string,
  440. params: {
  441. title?: string;
  442. prompt?: string;
  443. permissionMode?: string;
  444. modelSelection?: ZCodeOffPeakTask["modelSelection"] | null;
  445. },
  446. options?: { now?: number },
  447. ): Promise<ZCodeOffPeakTask | null> {
  448. await this.ensureReady();
  449. const row = this.getRow(offPeakTaskId);
  450. if (!row) return null;
  451. if (row.status !== "queued" && row.status !== "paused") return null;
  452. if (params.modelSelection === null) return null;
  453. const nextModelSelection = params.modelSelection ?? readOffPeakModelSelection(row);
  454. if (!nextModelSelection) {
  455. throw new Error(`Off-Peak task 缺少有效 ModelSelection: ${offPeakTaskId}`);
  456. }
  457. // 旧列是已发布版本的回滚快照,不能因普通编辑被清空;本更新只改 model_selection,
  458. // 不反向改写旧身份/档位,也不为新记录伪造旧值。
  459. this.getDatabase()
  460. .prepare(
  461. `UPDATE off_peak_tasks SET
  462. title = @title, prompt = @prompt, permission_mode = @permission_mode,
  463. model_selection = @model_selection, updated_at = @now
  464. WHERE off_peak_task_id = @id`,
  465. )
  466. .run({
  467. id: offPeakTaskId,
  468. title: params.title ?? row.title,
  469. prompt: params.prompt ?? row.prompt,
  470. permission_mode: params.permissionMode ?? row.permission_mode,
  471. model_selection: serializeOffPeakModelSelection(nextModelSelection),
  472. now: options?.now ?? Date.now(),
  473. });
  474. return rowToTask(this.getRow(offPeakTaskId)!);
  475. }
  476. // ---- 服务端同步快照(host offPeakTaskSync 写 / scheduler 读)----
  477. /** 轮询/重新取号写回:仅覆盖显式传入的字段。 */
  478. async updateSchedulingSnapshot(
  479. offPeakTaskId: string,
  480. patch: {
  481. schedulable?: boolean;
  482. queuePosition?: number | null;
  483. nextPollAt?: number | null;
  484. serverTicketId?: string;
  485. registeredAt?: number;
  486. now?: number;
  487. },
  488. ): Promise<void> {
  489. await this.ensureReady();
  490. const row = this.getRow(offPeakTaskId);
  491. if (!row) return;
  492. this.getDatabase()
  493. .prepare(
  494. `UPDATE off_peak_tasks SET
  495. schedulable = @schedulable,
  496. queue_position = @queue_position,
  497. next_poll_at = @next_poll_at,
  498. server_ticket_id = @server_ticket_id,
  499. registered_at = @registered_at,
  500. updated_at = @now
  501. WHERE off_peak_task_id = @id`,
  502. )
  503. .run({
  504. id: offPeakTaskId,
  505. schedulable: patch.schedulable === undefined ? row.schedulable : patch.schedulable ? 1 : 0,
  506. queue_position:
  507. patch.queuePosition === undefined ? row.queue_position : patch.queuePosition,
  508. next_poll_at: patch.nextPollAt === undefined ? row.next_poll_at : patch.nextPollAt,
  509. server_ticket_id: patch.serverTicketId ?? row.server_ticket_id,
  510. registered_at: patch.registeredAt ?? row.registered_at,
  511. now: patch.now ?? Date.now(),
  512. });
  513. }
  514. // ---- 调度状态机 ----
  515. /**
  516. * single-flight 认领可派发任务:status=queued 且 schedulable=1 且无在途认领,
  517. * 原子 claim_running 0→1。FIFO 序按 queued_at(权威序由服务端取号顺序保证)。
  518. * 同时回收认领超时(claimed_at 过期)的僵尸认领。
  519. */
  520. async claimDue(now: number): Promise<ZCodeOffPeakTask[]> {
  521. await this.ensureReady();
  522. const db = this.getDatabase();
  523. db.exec("BEGIN IMMEDIATE");
  524. try {
  525. db.prepare(
  526. `UPDATE off_peak_tasks
  527. SET claim_running = 0, claimed_at = NULL
  528. WHERE claim_running = 1 AND claimed_at IS NOT NULL AND claimed_at <= @stale`,
  529. ).run({ stale: now - OFF_PEAK_CLAIM_STALE_MS });
  530. const dueRows = db
  531. .prepare(
  532. `SELECT * FROM off_peak_tasks
  533. WHERE status = 'queued' AND schedulable = 1 AND claim_running = 0
  534. ORDER BY queued_at ASC, created_at ASC`,
  535. )
  536. .all() as unknown as OffPeakTaskRow[];
  537. const claimed: ZCodeOffPeakTask[] = [];
  538. const claim = db.prepare(
  539. `UPDATE off_peak_tasks
  540. SET claim_running = 1, claimed_at = @now, updated_at = @now
  541. WHERE off_peak_task_id = @id AND claim_running = 0`,
  542. );
  543. for (const row of dueRows) {
  544. // 历史行可能没有 Provider 身份;它们必须留在列表等待修复,但不能被
  545. // scheduler 认领。逐行跳过还能保证一条旧记录不阻塞后续健康任务。
  546. if (!readOffPeakModelSelection(row)) continue;
  547. const res = claim.run({ id: row.off_peak_task_id, now });
  548. if (res.changes === 1) {
  549. claimed.push(rowToTask({ ...row, claim_running: 1, claimed_at: now }));
  550. }
  551. }
  552. db.exec("COMMIT");
  553. return claimed;
  554. } catch (error) {
  555. db.exec("ROLLBACK");
  556. throw error;
  557. }
  558. }
  559. /**
  560. * 派发成功(网关 admitted):queued→running,回填首跑产生的 conversation/session 与
  561. * 本段 ticket,释放认领。守卫:仅 queued 可入 running(终态不可逆出;paused 竞态下
  562. * 派发结果作废,返回 null 由调用方处理)。续跑段保留首段 started_at(用户视角单任务)。
  563. */
  564. async markRunning(
  565. offPeakTaskId: string,
  566. options: {
  567. startedAt: number;
  568. conversationId?: string;
  569. sessionId?: string;
  570. serverTicketId?: string;
  571. },
  572. ): Promise<ZCodeOffPeakTask | null> {
  573. await this.ensureReady();
  574. const res = this.getDatabase()
  575. .prepare(
  576. `UPDATE off_peak_tasks
  577. SET status = 'running',
  578. started_at = COALESCE(started_at, @started_at),
  579. conversation_id = COALESCE(@conversation_id, conversation_id),
  580. session_id = COALESCE(@session_id, session_id),
  581. server_ticket_id = COALESCE(@server_ticket_id, server_ticket_id),
  582. claim_running = 0, claimed_at = NULL,
  583. last_error = NULL,
  584. updated_at = @started_at
  585. WHERE off_peak_task_id = @id AND status = 'queued'`,
  586. )
  587. .run({
  588. id: offPeakTaskId,
  589. started_at: options.startedAt,
  590. conversation_id: options.conversationId ?? null,
  591. session_id: options.sessionId ?? null,
  592. server_ticket_id: options.serverTicketId ?? null,
  593. });
  594. if (res.changes !== 1) return null;
  595. return rowToTask(this.getRow(offPeakTaskId)!);
  596. }
  597. /**
  598. * 终态落库(completed/failed/cancelled)。守卫:终态不可逆出——已终态的行拒绝二次迁移,
  599. * 返回 null(OffPeakRunResult 迟到兜底时调用方据此丢弃)。settled_at 由核销单独回填。
  600. */
  601. async markTerminal(
  602. offPeakTaskId: string,
  603. options: {
  604. status: "completed" | "failed" | "cancelled";
  605. endedAt: number;
  606. failureReason?: string;
  607. filesChanged?: number;
  608. /** scheduler 派发阶段的确定性错误;存在时原子累计一次派发尝试并留 last_error。 */
  609. dispatchError?: string;
  610. },
  611. ): Promise<ZCodeOffPeakTask | null> {
  612. await this.ensureReady();
  613. const res = this.getDatabase()
  614. .prepare(
  615. `UPDATE off_peak_tasks
  616. SET status = @status,
  617. ended_at = @ended_at,
  618. failure_reason = @failure_reason,
  619. files_changed = COALESCE(@files_changed, files_changed),
  620. attempt_count = attempt_count + @dispatch_attempt_inc,
  621. last_error = COALESCE(@dispatch_error, last_error),
  622. schedulable = 0,
  623. claim_running = 0, claimed_at = NULL,
  624. updated_at = @ended_at
  625. WHERE off_peak_task_id = @id AND status NOT IN (${TERMINAL_SQL_LIST})`,
  626. )
  627. .run({
  628. id: offPeakTaskId,
  629. status: options.status,
  630. ended_at: options.endedAt,
  631. failure_reason: options.failureReason ?? null,
  632. files_changed: options.filesChanged ?? null,
  633. dispatch_attempt_inc: options.dispatchError ? 1 : 0,
  634. dispatch_error: options.dispatchError ?? null,
  635. });
  636. if (res.changes !== 1) return null;
  637. return rowToTask(this.getRow(offPeakTaskId)!);
  638. }
  639. /**
  640. * 用户 Pause / Continue:queued ⇄ paused。
  641. * Pause 只停本地派发(票留服务端队列);Continue 的票有效性判断与重取号在 service 层。
  642. * 已被认领派发在途(claim_running=1)的任务不可 Pause,返回 null。
  643. */
  644. async setPaused(
  645. offPeakTaskId: string,
  646. paused: boolean,
  647. options?: { now?: number },
  648. ): Promise<ZCodeOffPeakTask | null> {
  649. await this.ensureReady();
  650. const res = this.getDatabase()
  651. .prepare(
  652. `UPDATE off_peak_tasks
  653. SET status = @to, updated_at = @now
  654. WHERE off_peak_task_id = @id AND status = @from AND claim_running = 0`,
  655. )
  656. .run({
  657. id: offPeakTaskId,
  658. to: paused ? "paused" : "queued",
  659. from: paused ? "queued" : "paused",
  660. now: options?.now ?? Date.now(),
  661. });
  662. if (res.changes !== 1) return null;
  663. return rowToTask(this.getRow(offPeakTaskId)!);
  664. }
  665. /**
  666. * 释放认领(派发失败/关机退出):复位 single-flight 锁;带 error 时累计 attempt_count
  667. * 并记 last_error(供派发退避与诊断)。不改 status——任务留在 queued 等下轮认领(无 skip)。
  668. */
  669. async releaseClaim(
  670. offPeakTaskId: string,
  671. options?: { error?: string; now?: number },
  672. ): Promise<void> {
  673. await this.ensureReady();
  674. this.getDatabase()
  675. .prepare(
  676. `UPDATE off_peak_tasks
  677. SET claim_running = 0, claimed_at = NULL,
  678. attempt_count = attempt_count + @attempt_inc,
  679. last_error = COALESCE(@error, last_error),
  680. updated_at = @now
  681. WHERE off_peak_task_id = @id AND claim_running = 1`,
  682. )
  683. .run({
  684. id: offPeakTaskId,
  685. attempt_inc: options?.error ? 1 : 0,
  686. error: options?.error ?? null,
  687. now: options?.now ?? Date.now(),
  688. });
  689. }
  690. /**
  691. * 启动回收(app 级启动时调用一次,先于任何派发):进程死亡时残留的
  692. * running 置回 queued(保留 queued_at,天然仍在队首附近;保留 session_id 供 resume
  693. * 续跑),并清理超时认领。返回回收的任务数。
  694. * ⚠ 调用方必须保证调用时无在跑 off-peak loop(属主应为 app 单例进程,非每个 host)。
  695. */
  696. async recoverInterrupted(now: number): Promise<number> {
  697. await this.ensureReady();
  698. const db = this.getDatabase();
  699. db.exec("BEGIN IMMEDIATE");
  700. try {
  701. const recovered = db
  702. .prepare(
  703. `UPDATE off_peak_tasks
  704. SET status = 'queued', claim_running = 0, claimed_at = NULL, updated_at = @now
  705. WHERE status = 'running'`,
  706. )
  707. .run({ now });
  708. db.prepare(
  709. `UPDATE off_peak_tasks
  710. SET claim_running = 0, claimed_at = NULL, updated_at = @now
  711. WHERE claim_running = 1 AND claimed_at IS NOT NULL AND claimed_at <= @stale`,
  712. ).run({ now, stale: now - OFF_PEAK_CLAIM_STALE_MS });
  713. db.exec("COMMIT");
  714. return Number(recovered.changes ?? 0);
  715. } catch (error) {
  716. db.exec("ROLLBACK");
  717. throw error;
  718. }
  719. }
  720. /**
  721. * 3h 时间盒到期 / ready 废票的续跑回队:running → queued,保留
  722. * session/conversation/started_at 供 resume 接续;清 schedulable 与位次等待重新取号后由轮询刷新。
  723. * 终态/paused 不可回队,返回 null(如用户已抢先取消)。
  724. */
  725. async requeueForContinuation(
  726. offPeakTaskId: string,
  727. options?: { now?: number },
  728. ): Promise<ZCodeOffPeakTask | null> {
  729. await this.ensureReady();
  730. const res = this.getDatabase()
  731. .prepare(
  732. `UPDATE off_peak_tasks
  733. SET status = 'queued', schedulable = 0, queue_position = NULL,
  734. claim_running = 0, claimed_at = NULL, updated_at = @now
  735. WHERE off_peak_task_id = @id AND status = 'running'`,
  736. )
  737. .run({ id: offPeakTaskId, now: options?.now ?? Date.now() });
  738. if (res.changes !== 1) return null;
  739. return rowToTask(this.getRow(offPeakTaskId)!);
  740. }
  741. /** 全部非终态任务(offPeakTaskSync 轮询输入:有非终态才轮)。 */
  742. async listNonTerminal(): Promise<ZCodeOffPeakTask[]> {
  743. await this.ensureReady();
  744. const rows = this.getDatabase()
  745. .prepare(
  746. `SELECT * FROM off_peak_tasks
  747. WHERE status NOT IN (${TERMINAL_SQL_LIST})
  748. ORDER BY queued_at ASC`,
  749. )
  750. .all() as unknown as OffPeakTaskRow[];
  751. return rows.map(rowToTask);
  752. }
  753. // ---- 终态核销 outbox----
  754. /** settle 服务端 ack 后回填;仅终态行可核销(幂等,重复回填覆盖为最新 ack 时间)。 */
  755. async markSettled(offPeakTaskId: string, settledAt: number): Promise<void> {
  756. await this.ensureReady();
  757. this.getDatabase()
  758. .prepare(
  759. `UPDATE off_peak_tasks
  760. SET settled_at = @settled_at, updated_at = @settled_at
  761. WHERE off_peak_task_id = @id AND status IN (${TERMINAL_SQL_LIST})`,
  762. )
  763. .run({ id: offPeakTaskId, settled_at: settledAt });
  764. }
  765. /** 未核销的终态任务:poll 周期捎带补报 + host 启动扫描(不新增计时器)。 */
  766. async listUnsettledTerminal(): Promise<ZCodeOffPeakTask[]> {
  767. await this.ensureReady();
  768. const rows = this.getDatabase()
  769. .prepare(
  770. `SELECT * FROM off_peak_tasks
  771. WHERE status IN (${TERMINAL_SQL_LIST}) AND settled_at IS NULL
  772. ORDER BY ended_at ASC`,
  773. )
  774. .all() as unknown as OffPeakTaskRow[];
  775. return rows.map(rowToTask);
  776. }
  777. }