@capybara-hq/kernel 0.1.0-rc.34 → 0.1.0-rc.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/admin/outbox-dead.service.d.ts +2 -0
  2. package/dist/admin/outbox-dead.service.js +34 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/conversations/conversations.service.d.ts +3 -3
  5. package/dist/conversations/conversations.service.js +58 -29
  6. package/dist/db/kernel-schema.d.ts +8 -0
  7. package/dist/infra/database/transaction-host.d.ts +1 -0
  8. package/dist/infra/database/transaction-host.js +13 -2
  9. package/dist/infra/outbox/registry.d.ts +17 -0
  10. package/dist/infra/outbox/registry.js +11 -0
  11. package/dist/local-devices/local-device-gateway.d.ts +1 -1
  12. package/dist/local-devices/local-device-gateway.js +1 -1
  13. package/dist/local-devices/local-device-provider.d.ts +2 -2
  14. package/dist/local-devices/local-device-provider.js +7 -5
  15. package/dist/orgs/offboarding.d.ts +2 -0
  16. package/dist/orgs/offboarding.js +4 -0
  17. package/dist/orgs/orgs.service.d.ts +3 -1
  18. package/dist/orgs/orgs.service.js +23 -10
  19. package/dist/runtime/checkpointer.js +3 -0
  20. package/dist/runtime/context/compaction.js +5 -5
  21. package/dist/runtime/conversation-lock.d.ts +4 -11
  22. package/dist/runtime/conversation-lock.js +14 -18
  23. package/dist/runtime/maintenance.d.ts +3 -1
  24. package/dist/runtime/maintenance.js +17 -10
  25. package/dist/runtime/project/knowledge.service.js +2 -2
  26. package/dist/runtime/run-deletion.d.ts +23 -0
  27. package/dist/runtime/run-deletion.js +130 -0
  28. package/dist/runtime/run-execution.d.ts +23 -0
  29. package/dist/runtime/run-execution.js +105 -0
  30. package/dist/runtime/run-finish.js +17 -4
  31. package/dist/runtime/run-jobs.js +11 -0
  32. package/dist/runtime/run-orphan-check.job.d.ts +12 -12
  33. package/dist/runtime/run-orphan-check.job.js +94 -26
  34. package/dist/runtime/run-queue.js +14 -0
  35. package/dist/runtime/run-worker.d.ts +9 -5
  36. package/dist/runtime/run-worker.js +90 -44
  37. package/dist/runtime/runtime.module.js +6 -0
  38. package/dist/runtime/stream.js +8 -2
  39. package/dist/runtime/subagents/tree-jobs.d.ts +4 -3
  40. package/dist/runtime/subagents/tree-jobs.js +4 -4
  41. package/dist/tools/pipeline.js +7 -1
  42. package/package.json +3 -3
  43. package/src/migrations/0135_run_execution_claim.sql +2 -0
  44. package/src/migrations/0136_run_recovery_cursor.sql +6 -0
@@ -21,6 +21,7 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
21
21
  import { KyselyCheckpointSaver } from "./checkpointer.js";
22
22
  import { ConversationLock } from "./conversation-lock.js";
23
23
  import { QueueLostJobs } from "./queue-lost-jobs.js";
24
+ import { RunDeletion } from "./run-deletion.js";
24
25
  import { notifyFinished, RunFinish } from "./run-finish.js";
25
26
  import { RunJobs, runJobId, runQueueNameFor } from "./run-jobs.js";
26
27
  import { RunQueue } from "./run-queue.js";
@@ -39,7 +40,7 @@ export const RUN_ORPHAN_CHECK_BATCH = 500;
39
40
  /**
40
41
  * The most pages one pass reads: a bound on its work. Healthy long runs and queued runs waiting
41
42
  * for a quota slot are passed over page by page, so a real orphan behind them is still reached;
42
- * beyond this many candidates the rest wait for the next minute.
43
+ * the shared cursor resumes after the last inspected row on the next pass.
43
44
  */
44
45
  export const RUN_ORPHAN_CHECK_MAX_PAGES = 10;
45
46
  /** The error the canary logs (transactional outbox spec §8.3). */
@@ -49,10 +50,8 @@ const SINCE = sql `GREATEST(COALESCE(r.queued_at, r.created_at), COALESCE(r.star
49
50
  /**
50
51
  * One page of the active runs of chat and sub-agent conversations in `statuses` that entered their
51
52
  * state more than `minAgeMs` ago, by (state start, id), after `after` (an eval's hidden
52
- * conversation drives its runs itself). A deleted org's runs are never candidates, running ones
53
- * included: its deletion purged its owed jobs on purpose, so their absence is no lost job and
54
- * nothing is re-added, and the org's data is invisible from then on, so a running orphan is left
55
- * as it is rather than failed.
53
+ * conversation drives its runs itself). Deleted rows are included for cancellation recovery;
54
+ * their intentionally removed jobs are never interpreted as queue loss or re-added.
56
55
  */
57
56
  export async function orphanCandidates(db, statuses, minAgeMs, limit, after) {
58
57
  let q = db
@@ -67,11 +66,12 @@ export async function orphanCandidates(db, statuses, minAgeMs, limit, after) {
67
66
  "r.trigger_seq",
68
67
  "c.kind",
69
68
  "c.org_id",
69
+ "c.deleted_at as conversation_deleted",
70
+ "o.deleted_at as org_deleted",
70
71
  sql `${SINCE}::text`.as("since"),
71
72
  ])
72
73
  .where("r.status", "in", statuses)
73
74
  .where("c.kind", "in", ["chat", "subagent"])
74
- .where("o.deleted_at", "is", null)
75
75
  .where(SINCE, "<", sql `now() - ${minAgeMs}::integer * interval '1 millisecond'`);
76
76
  if (after !== undefined) {
77
77
  q = q.where(sql `(${SINCE}, r.id) > (${after.since}::timestamptz, ${after.runId})`);
@@ -83,15 +83,13 @@ export async function orphanCandidates(db, statuses, minAgeMs, limit, after) {
83
83
  orgId: r.org_id,
84
84
  kind: r.kind,
85
85
  status: r.status,
86
+ deleted: r.conversation_deleted !== null || r.org_deleted !== null,
86
87
  jobId: r.job_id ?? runJobId(r.conversation_id, Number(r.trigger_seq)),
87
88
  queue: runQueueNameFor(r.kind),
88
89
  since: r.since,
89
90
  }));
90
91
  }
91
- /**
92
- * Whether the outbox holds the job `jobId` on `queue`: a pending row (it is still owed) or a dead
93
- * one (the outbox gave up on it; the super admin sees it under `outbox_dead` and retries or
94
- * discards it, so it is not a job the queue lost).
92
+ /** Whether delivery is still owed by a pending outbox row; dead copies are not active work.
95
93
  */
96
94
  export async function jobInOutbox(db, queue, jobId) {
97
95
  const row = await db
@@ -99,12 +97,12 @@ export async function jobInOutbox(db, queue, jobId) {
99
97
  .select("id")
100
98
  .where("queue", "=", queue)
101
99
  .where("job_id", "=", jobId)
100
+ .where("dead_at", "is", null)
102
101
  .executeTakeFirst();
103
102
  return row !== undefined;
104
103
  }
105
104
  /** Every page of {@link orphanCandidates}, at most {@link RUN_ORPHAN_CHECK_MAX_PAGES}. */
106
- async function* candidatePages(db, statuses, minAgeMs) {
107
- let after;
105
+ async function* candidatePages(db, statuses, minAgeMs, after) {
108
106
  for (let page = 0; page < RUN_ORPHAN_CHECK_MAX_PAGES; page++) {
109
107
  const rows = await orphanCandidates(db, statuses, minAgeMs, RUN_ORPHAN_CHECK_BATCH, after);
110
108
  if (rows.length > 0)
@@ -126,6 +124,8 @@ export async function queuedRunsWithoutJob(db, jobExists, opts) {
126
124
  const out = [];
127
125
  for await (const page of candidatePages(db, ["queued"], opts.minAgeMs)) {
128
126
  for (const c of page) {
127
+ if (c.deleted)
128
+ continue;
129
129
  if (await jobInOutbox(db, c.queue, c.jobId))
130
130
  continue;
131
131
  if (await jobExists(c.queue, c.jobId))
@@ -151,7 +151,7 @@ export async function queuedRunsWithoutJob(db, jobExists, opts) {
151
151
  * `run.orphaned` (its terminal transaction cancels its waits and owes what every run end owes),
152
152
  * then, after the commit, its checkpoints are dropped, its fork child stopped (`run.orphaned`), a
153
153
  * sub-agent's failure delivered to its parent at once and the conversation's next run started.
154
- * - `queued`, with no outbox row either (pending or dead): a canary. Every queued run has its job
154
+ * - `queued`, with no pending or current-generation dead delivery: a canary. Every queued run has its job
155
155
  * owed in its own transaction, so this means Redis lost data. It is logged as an error, counted
156
156
  * for the admin overview ({@link QueueLostJobs}) and its job owed again so the run is not stuck.
157
157
  * Redis is read before each repair's transaction, which then re-reads the run under its
@@ -167,6 +167,7 @@ let RunOrphanCheck = class RunOrphanCheck {
167
167
  checkpoints;
168
168
  waits;
169
169
  queue;
170
+ deletion;
170
171
  lostJobs;
171
172
  events;
172
173
  txHost;
@@ -177,7 +178,7 @@ let RunOrphanCheck = class RunOrphanCheck {
177
178
  /** A failed sub-agent run reports to its parent at once ({@link Waits.childFinished}). */
178
179
  waits,
179
180
  /** The conversation's next run, after a repaired run's end. */
180
- queue, lostJobs, events, txHost, config, lockService, log) {
181
+ queue, deletion, lostJobs, events, txHost, config, lockService, log) {
181
182
  this.kdb = kdb;
182
183
  this.jobs = jobs;
183
184
  this.lock = lock;
@@ -186,6 +187,7 @@ let RunOrphanCheck = class RunOrphanCheck {
186
187
  this.checkpoints = checkpoints;
187
188
  this.waits = waits;
188
189
  this.queue = queue;
190
+ this.deletion = deletion;
189
191
  this.lostJobs = lostJobs;
190
192
  this.events = events;
191
193
  this.txHost = txHost;
@@ -203,16 +205,31 @@ let RunOrphanCheck = class RunOrphanCheck {
203
205
  async check() {
204
206
  const out = { runningRepaired: 0, queuedReadded: 0 };
205
207
  const lost = [];
206
- const pages = candidatePages(this.db, ["queued", "running"], RUN_ORPHAN_MIN_AGE_MS);
208
+ const cursor = await this.db
209
+ .selectFrom("run_recovery_cursors")
210
+ .select(["run_id", sql `since::text`.as("since")])
211
+ .where("name", "=", "active-runs")
212
+ .executeTakeFirst();
213
+ const after = cursor?.since && cursor.run_id ? { since: cursor.since, runId: cursor.run_id } : undefined;
214
+ const pages = candidatePages(this.db, ["queued", "running"], RUN_ORPHAN_MIN_AGE_MS, after);
215
+ let inspected = 0;
207
216
  for await (const page of pages) {
217
+ inspected++;
208
218
  for (const c of page) {
209
219
  try {
220
+ if (c.deleted) {
221
+ await this.deletion.stopDeletedConversation(c.conversationId, null);
222
+ continue;
223
+ }
210
224
  if (!(await this.withoutJobOrHolder(c)))
211
225
  continue;
212
226
  if (c.status === "running") {
213
227
  if (await this.failRunning(c))
214
228
  out.runningRepaired++;
215
229
  }
230
+ else if (await this.hasDeadDelivery(c)) {
231
+ await this.failRunning(c, true);
232
+ }
216
233
  else if (await this.oweAgainIn(c)) {
217
234
  out.queuedReadded++;
218
235
  lost.push(c);
@@ -222,7 +239,12 @@ let RunOrphanCheck = class RunOrphanCheck {
222
239
  this.log.error("run-orphan-check: cannot repair a run", { runId: c.runId, err });
223
240
  }
224
241
  }
242
+ const last = page.at(-1);
243
+ if (last)
244
+ await this.saveCursorIn(last);
225
245
  }
246
+ if (inspected < RUN_ORPHAN_CHECK_MAX_PAGES)
247
+ await this.saveCursorIn(null);
226
248
  if (lost.length > 0) {
227
249
  this.log.error(QUEUE_LOST_JOBS_MESSAGE, {
228
250
  count: lost.length,
@@ -232,9 +254,29 @@ let RunOrphanCheck = class RunOrphanCheck {
232
254
  }
233
255
  return out;
234
256
  }
257
+ async saveCursorIn(cursor) {
258
+ const values = {
259
+ since: cursor === null ? null : sql `${cursor.since}::timestamptz`,
260
+ run_id: cursor?.runId ?? null,
261
+ };
262
+ await this.db
263
+ .insertInto("run_recovery_cursors")
264
+ .values({ name: "active-runs", ...values })
265
+ .onConflict((oc) => oc.column("name").doUpdateSet(values))
266
+ .execute();
267
+ }
268
+ async hasDeadDelivery(c) {
269
+ return ((await this.db
270
+ .selectFrom("outbox")
271
+ .select("id")
272
+ .where("queue", "=", c.queue)
273
+ .where("job_id", "=", c.jobId)
274
+ .where("dead_at", ">=", sql `${c.since}::timestamptz`)
275
+ .executeTakeFirst()) !== undefined);
276
+ }
235
277
  /**
236
278
  * Neither a conversation lock holder nor the run's job in BullMQ (nor, queued, in the outbox: an
237
- * owed row is delivered by the relay, a dead one waits for the super admin).
279
+ * owed row is delivered by the relay; a dead current delivery is settled visibly).
238
280
  */
239
281
  async withoutJobOrHolder(c) {
240
282
  if ((await this.lock.holder(c.conversationId)) !== null)
@@ -248,8 +290,8 @@ let RunOrphanCheck = class RunOrphanCheck {
248
290
  * the open pages hear it, its checkpoints go, its fork child stops, a sub-agent reports to its
249
291
  * parent and the conversation's next run starts (each also owed by the terminal transaction).
250
292
  */
251
- async failRunning(c) {
252
- const seq = await this.failIn(c);
293
+ async failRunning(c, deliveryFailed = false) {
294
+ const seq = await this.failIn(c, deliveryFailed);
253
295
  if (seq === null)
254
296
  return false;
255
297
  this.log.warn("run-orphan-check: failed a running run nobody runs", {
@@ -272,9 +314,26 @@ let RunOrphanCheck = class RunOrphanCheck {
272
314
  return true;
273
315
  }
274
316
  /** {@link failRunning}'s transaction: the terminal state, if the run is still the same orphan. */
275
- async failIn(c) {
317
+ async failIn(c, deliveryFailed = false) {
276
318
  if (!(await this.stillIn(c)))
277
319
  return null;
320
+ if (deliveryFailed) {
321
+ // Lock dead rows against admin retry. A pending retry always takes precedence over a
322
+ // historical dead copy. Producers of replacement jobs also hold this conversation lock.
323
+ const deliveries = await this.db
324
+ .selectFrom("outbox")
325
+ .select("dead_at")
326
+ .where("queue", "=", c.queue)
327
+ .where("job_id", "=", c.jobId)
328
+ .where((eb) => eb.or([
329
+ eb("dead_at", "is", null),
330
+ eb("dead_at", ">=", sql `${c.since}::timestamptz`),
331
+ ]))
332
+ .forUpdate()
333
+ .execute();
334
+ if (deliveries.length === 0 || deliveries.some((row) => row.dead_at === null))
335
+ return null;
336
+ }
278
337
  return this.finisher.finishIn({
279
338
  conversationId: c.conversationId,
280
339
  runId: c.runId,
@@ -283,7 +342,12 @@ let RunOrphanCheck = class RunOrphanCheck {
283
342
  event: {
284
343
  type: "run_failed",
285
344
  payload: {
286
- error: { code: "run.orphaned", message: "The run was lost and will not continue" },
345
+ error: deliveryFailed
346
+ ? {
347
+ code: "run.delivery_failed",
348
+ message: "The run could not be delivered. Send a new message to retry.",
349
+ }
350
+ : { code: "run.orphaned", message: "The run was lost and will not continue" },
287
351
  },
288
352
  },
289
353
  });
@@ -318,6 +382,9 @@ let RunOrphanCheck = class RunOrphanCheck {
318
382
  __decorate([
319
383
  LockedInterval(RUN_ORPHAN_CHECK_JOB, () => RUN_ORPHAN_CHECK_PERIOD_MS)
320
384
  ], RunOrphanCheck.prototype, "run", null);
385
+ __decorate([
386
+ Transactional({ propagation: "requires_new" })
387
+ ], RunOrphanCheck.prototype, "saveCursorIn", null);
321
388
  __decorate([
322
389
  Transactional({ propagation: "requires_new" })
323
390
  ], RunOrphanCheck.prototype, "failIn", null);
@@ -334,11 +401,12 @@ RunOrphanCheck = __decorate([
334
401
  __param(5, Inject(KyselyCheckpointSaver)),
335
402
  __param(6, Inject(Waits)),
336
403
  __param(7, Inject(RunQueue)),
337
- __param(8, Inject(QueueLostJobs)),
338
- __param(9, Inject(KernelEvents)),
339
- __param(10, Inject(TransactionHost)),
340
- __param(11, Inject(KernelConfigService)),
341
- __param(12, Inject(LockService)),
342
- __param(13, Inject(KERNEL_LOGGER))
404
+ __param(8, Inject(RunDeletion)),
405
+ __param(9, Inject(QueueLostJobs)),
406
+ __param(10, Inject(KernelEvents)),
407
+ __param(11, Inject(TransactionHost)),
408
+ __param(12, Inject(KernelConfigService)),
409
+ __param(13, Inject(LockService)),
410
+ __param(14, Inject(KERNEL_LOGGER))
343
411
  ], RunOrphanCheck);
344
412
  export { RunOrphanCheck };
@@ -144,6 +144,13 @@ let RunQueue = class RunQueue {
144
144
  if (!conv || conv.deleted_at !== null || conv.kind !== "chat") {
145
145
  throw new ApiError("conversation.not_found", "Conversation not found");
146
146
  }
147
+ const org = await t
148
+ .selectFrom("orgs")
149
+ .select("deleted_at")
150
+ .where("id", "=", conv.org_id)
151
+ .executeTakeFirst();
152
+ if (!org || org.deleted_at !== null)
153
+ throw new ApiError("conversation.not_found", "Conversation not found");
147
154
  const active = await t
148
155
  .selectFrom("runs")
149
156
  .select(["id", "compact"])
@@ -212,6 +219,13 @@ let RunQueue = class RunQueue {
212
219
  // A deleted conversation starts no run, whatever is still unconsumed or queued
213
220
  if (conv.deleted_at !== null)
214
221
  return null;
222
+ const org = await t
223
+ .selectFrom("orgs")
224
+ .select("deleted_at")
225
+ .where("id", "=", conv.org_id)
226
+ .executeTakeFirst();
227
+ if (!org || org.deleted_at !== null)
228
+ return null;
215
229
  if (conv.kind === "subagent")
216
230
  return this.childWakeIn(conversationId, conv, st);
217
231
  const newest = await t
@@ -19,6 +19,7 @@ import { ProviderRegistry } from "./providers.js";
19
19
  import { type OrgQuota } from "./quota.js";
20
20
  import { RunContextService } from "./run-context.service.js";
21
21
  import { RunDrafts } from "./run-drafts.js";
22
+ import { RunExecution } from "./run-execution.js";
22
23
  import { RunFinish } from "./run-finish.js";
23
24
  import { type RunJobData } from "./run-jobs.js";
24
25
  import { RunQueue } from "./run-queue.js";
@@ -82,6 +83,7 @@ export declare class RunWorker {
82
83
  private readonly projectKnowledge;
83
84
  /** The run's resolved tools, for the plugin context's `tools` (chat runs with providers). */
84
85
  private readonly tools;
86
+ private readonly execution;
85
87
  private readonly finisher;
86
88
  readonly txHost: TransactionHost;
87
89
  /** The steps' live drafts this process writes for the runs it executes. */
@@ -116,7 +118,7 @@ export declare class RunWorker {
116
118
  /** Run start's project knowledge (project root spec §4.4): a bound project's AGENTS.md, skills. */
117
119
  projectKnowledge: Pick<ProjectKnowledgeService, "record">,
118
120
  /** The run's resolved tools, for the plugin context's `tools` (chat runs with providers). */
119
- tools: Pick<ToolRegistry, "forAgent">, finisher: Pick<RunFinish, "finish">, txHost: TransactionHost,
121
+ tools: Pick<ToolRegistry, "forAgent">, execution: RunExecution, finisher: Pick<RunFinish, "finish">, txHost: TransactionHost,
120
122
  /** The steps' live drafts this process writes for the runs it executes. */
121
123
  drafts: RunDrafts, hooks?: RunHooks | undefined);
122
124
  private get db();
@@ -169,9 +171,9 @@ export declare class RunWorker {
169
171
  /** 登记一个任务结束后的处理,做完自动移除。 */
170
172
  private track;
171
173
  /**
172
- * BullMQ 判定任务失败(R29):stalled 次数超过上限(持有者反复崩溃),或处理函数在自己的终态处理之外抛错。
173
- * 运行若仍未结束:清理死去持有者留下的会话锁,写 `run_failed`(stalled → `run.stalled`,
174
- * 其他 → `run.internal`),status 置为 failed,consumed_seq 至少推进到触发消息,删除 checkpoint,然后 ensureRun(带重试)。
174
+ * A final BullMQ failure settles the run and revokes its PG claim. Never release a Redis
175
+ * acquisition by run id: another execution of that same run may now own it. The abandoned
176
+ * acquisition expires; terminal follow-up consumes the trigger and clears its checkpoints.
175
177
  */
176
178
  private onJobFailed;
177
179
  /**
@@ -220,7 +222,9 @@ export declare class RunWorker {
220
222
  private appendRunStarted;
221
223
  /** {@link fallBackIfUnavailable}'s write: null when the person switched again meanwhile. */
222
224
  private fallBackIn;
223
- /** 删除已结束运行的 checkpoint thread(失败只记日志)。 */
225
+ /** Transition only an active run, within the execution fence. */
226
+ private markRunning;
227
+ /** Delete a terminal run's checkpoint thread; log cleanup failures. */
224
228
  private dropCheckpoints;
225
229
  /**
226
230
  * 写终态(见 `finishRun`:运行仍未结束才写,同一事务内推进 `consumed_seq` 并更新 `runs.status`),
@@ -38,6 +38,7 @@ import { ProviderListError, ProviderRegistry } from "./providers.js";
38
38
  import { ORG_QUOTA_LEASE_MS, orgRunLimit, RUN_QUOTA } from "./quota.js";
39
39
  import { RunContextService } from "./run-context.service.js";
40
40
  import { RunDrafts, streamSink } from "./run-drafts.js";
41
+ import { ExecutionRevoked, RunExecution } from "./run-execution.js";
41
42
  import { RunFinish } from "./run-finish.js";
42
43
  import { TERMINAL_STATUSES } from "./run-jobs.js";
43
44
  import { RunQueue } from "./run-queue.js";
@@ -104,6 +105,7 @@ let RunWorker = class RunWorker {
104
105
  pluginContext;
105
106
  projectKnowledge;
106
107
  tools;
108
+ execution;
107
109
  finisher;
108
110
  txHost;
109
111
  drafts;
@@ -137,7 +139,7 @@ let RunWorker = class RunWorker {
137
139
  /** Run start's project knowledge (project root spec §4.4): a bound project's AGENTS.md, skills. */
138
140
  projectKnowledge,
139
141
  /** The run's resolved tools, for the plugin context's `tools` (chat runs with providers). */
140
- tools, finisher, txHost,
142
+ tools, execution, finisher, txHost,
141
143
  /** The steps' live drafts this process writes for the runs it executes. */
142
144
  drafts, hooks) {
143
145
  this.kdb = kdb;
@@ -161,6 +163,7 @@ let RunWorker = class RunWorker {
161
163
  this.pluginContext = pluginContext;
162
164
  this.projectKnowledge = projectKnowledge;
163
165
  this.tools = tools;
166
+ this.execution = execution;
164
167
  this.finisher = finisher;
165
168
  this.txHost = txHost;
166
169
  this.drafts = drafts;
@@ -312,14 +315,15 @@ let RunWorker = class RunWorker {
312
315
  void p.finally(() => this.followUps.delete(p));
313
316
  }
314
317
  /**
315
- * BullMQ 判定任务失败(R29):stalled 次数超过上限(持有者反复崩溃),或处理函数在自己的终态处理之外抛错。
316
- * 运行若仍未结束:清理死去持有者留下的会话锁,写 `run_failed`(stalled → `run.stalled`,
317
- * 其他 → `run.internal`),status 置为 failed,consumed_seq 至少推进到触发消息,删除 checkpoint,然后 ensureRun(带重试)。
318
+ * A final BullMQ failure settles the run and revokes its PG claim. Never release a Redis
319
+ * acquisition by run id: another execution of that same run may now own it. The abandoned
320
+ * acquisition expires; terminal follow-up consumes the trigger and clears its checkpoints.
318
321
  */
319
322
  async onJobFailed(data, err) {
320
323
  const { runId, conversationId } = data;
321
324
  const stalled = /stalled/i.test(err.message);
322
- await this.lock.releaseFor(conversationId, runId);
325
+ // Never release by run id: a newer acquisition may own the same run. The terminal
326
+ // transaction revokes the persisted claim; the acquisition itself expires or releases.
323
327
  // 运行已进入 waiting(暂停后任务才失败):它有自己的续跑路径(人工决定 / 超时任务),不标记失败。
324
328
  const cur = await this.db
325
329
  .selectFrom("runs")
@@ -456,6 +460,7 @@ let RunWorker = class RunWorker {
456
460
  let settle;
457
461
  const state = {
458
462
  shutdown: new AbortController(),
463
+ executionAbort: new AbortController(),
459
464
  abandoned: false,
460
465
  leaseLost: false,
461
466
  lease,
@@ -468,16 +473,21 @@ let RunWorker = class RunWorker {
468
473
  // 停机开始后才登记的运行(close() 的快照之后):同样在步骤边界停下。
469
474
  if (this.closing)
470
475
  state.shutdown.abort();
471
- // 锁丢失(R27):走与停机相同的路径——loop 在下一个步骤边界返回 interrupted,任务回到队列。
476
+ // Lease loss cancels the in-flight request now; PG claim fencing rejects stale writes.
472
477
  lease.onLost(() => {
473
478
  state.leaseLost = true;
474
479
  state.shutdown.abort();
480
+ state.executionAbort.abort();
481
+ state.quota?.abandon();
482
+ if (this.active.get(runId) === state)
483
+ this.drafts.release(runId);
475
484
  });
485
+ let claim = null;
476
486
  let entered = false;
477
487
  let delayMs = null;
478
488
  try {
479
489
  const limit = await orgRunLimit(this.settings, this.config, conv.org_id);
480
- const slot = await this.quota.enter(conv.org_id, runId, limit, ORG_QUOTA_LEASE_MS);
490
+ const slot = await this.quota.enter(conv.org_id, `${runId}/${lease.executionId}`, limit, ORG_QUOTA_LEASE_MS);
481
491
  if (slot !== undefined)
482
492
  state.quota = slot;
483
493
  entered = slot !== undefined;
@@ -485,17 +495,37 @@ let RunWorker = class RunWorker {
485
495
  delayMs = QUOTA_FULL_DELAY_MS;
486
496
  }
487
497
  else {
488
- const r = await this.execute(run, { id: conversationId, ...conv }, state).catch(async (err) => {
498
+ claim = await this.execution.claim(conversationId, runId, lease.executionId, () => !lease.lost && !state.abandoned);
499
+ if (claim === null)
500
+ return "ensure";
501
+ const r = await this.execution
502
+ .withClaim(claim, () => !lease.lost && !state.abandoned, async () => {
503
+ const result = await this.execute(run, { id: conversationId, ...conv }, state);
504
+ if (state.suspended) {
505
+ await this.waits.suspend(runId, conversationId, state.suspended.waitingFor, state.suspended.abort);
506
+ }
507
+ return result;
508
+ })
509
+ .catch(async (err) => {
489
510
  if (state.abandoned)
490
511
  return "abandoned";
491
- if (state.leaseLost)
512
+ if (state.leaseLost || err instanceof ExecutionRevoked)
492
513
  return "interrupted";
493
514
  // 编排自身出错(如写事件失败):尽力把运行标记为失败,避免会话卡在 running。
494
515
  this.log.error("run orchestration failed", { conversationId, runId, err });
495
- await this.finish(conversationId, runId, "failed", null, {
496
- type: "run_failed",
497
- payload: { error: { code: "run.internal", message: "The run failed unexpectedly" } },
498
- }).catch((e) => this.log.error("cannot mark run as failed", { runId, err: e }));
516
+ try {
517
+ await this.execution.withClaim(claim, () => !lease.lost && !state.abandoned, () => this.finish(conversationId, runId, "failed", null, {
518
+ type: "run_failed",
519
+ payload: {
520
+ error: { code: "run.internal", message: "The run failed unexpectedly" },
521
+ },
522
+ }));
523
+ }
524
+ catch (failure) {
525
+ if (failure instanceof ExecutionRevoked)
526
+ return "interrupted";
527
+ this.log.error("cannot mark run as failed", { runId, err: failure });
528
+ }
499
529
  return "broken";
500
530
  });
501
531
  if (r === "interrupted")
@@ -515,20 +545,27 @@ let RunWorker = class RunWorker {
515
545
  .catch((err) => this.log.warn("conversation lock release failed", { runId, err }));
516
546
  }
517
547
  }
518
- this.active.delete(runId);
548
+ if (this.active.get(runId) === state)
549
+ this.active.delete(runId);
519
550
  settle();
520
551
  }
521
552
  if (state.abandoned)
522
553
  return;
523
554
  if (delayMs !== null)
524
555
  return requeue(job, token, delayMs);
525
- // 暂停:会话锁与配额已释放,checkpoint 保留;置 waiting 并投递超时任务。任务就此完成,不 ensureRun
526
- // (等待期间的新消息在续跑后作为插话吸收)。
527
- if (state.suspended) {
528
- await this.waits.suspend(runId, conversationId, state.suspended.waitingFor, state.suspended.abort);
556
+ // Suspension was committed under the execution fence before releasing the lease. Keep its
557
+ // checkpoint; the decision/timeout owns resumption and this job starts no follow-up run.
558
+ if (state.suspended)
559
+ return;
560
+ // Terminal states are immutable. A stale execution cannot delete a running/waiting
561
+ // successor's checkpoint, while a completed run no longer needs any checkpoint.
562
+ const settled = await this.db
563
+ .selectFrom("runs")
564
+ .select("status")
565
+ .where("id", "=", runId)
566
+ .executeTakeFirst();
567
+ if (!settled || !TERMINAL_STATUSES.has(settled.status))
529
568
  return;
530
- }
531
- // 运行已到达终态(broken 时已尽力标记失败):checkpoint 只用于续跑,删除。
532
569
  await this.dropCheckpoints(runId);
533
570
  if (conv.kind === "subagent")
534
571
  await this.childFinished(runId);
@@ -717,13 +754,7 @@ let RunWorker = class RunWorker {
717
754
  return "finished";
718
755
  await this.hooks?.beforeRunning?.(runId, conversationId);
719
756
  // never over a terminal status: a run finished meanwhile stays finished
720
- const updated = await this.db
721
- .updateTable("runs")
722
- .set({ status: "running", started_at: sql `COALESCE(started_at, now())` })
723
- .where("id", "=", runId)
724
- .where("status", "in", ["queued", "running"])
725
- .returning("started_at")
726
- .executeTakeFirst();
757
+ const updated = await this.markRunning(runId);
727
758
  if (updated === undefined)
728
759
  return "finished";
729
760
  startedAt = updated.started_at;
@@ -800,9 +831,15 @@ let RunWorker = class RunWorker {
800
831
  role,
801
832
  agent,
802
833
  agentVersion: run.agent_version,
803
- signal: ac.signal,
834
+ signal: AbortSignal.any([ac.signal, state.executionAbort.signal]),
804
835
  shutdown: state.shutdown.signal,
805
- sink: this.sinkFor(conversationId),
836
+ sink: (() => {
837
+ const sink = this.sinkFor(conversationId);
838
+ return (delta) => {
839
+ if (!state.lease.lost && !state.abandoned && this.active.get(runId) === state)
840
+ sink(delta);
841
+ };
842
+ })(),
806
843
  pendingAbsorbable,
807
844
  limits: {
808
845
  ...(maxSteps !== undefined && { maxSteps }),
@@ -816,7 +853,7 @@ let RunWorker = class RunWorker {
816
853
  catch (e) {
817
854
  if (state.abandoned)
818
855
  return "abandoned";
819
- if (state.leaseLost)
856
+ if (state.leaseLost || e instanceof ExecutionRevoked)
820
857
  return "interrupted";
821
858
  const err = e instanceof RunError ? e : new RunError("run.internal", "The run failed unexpectedly");
822
859
  if (!(e instanceof RunError)) {
@@ -832,7 +869,8 @@ let RunWorker = class RunWorker {
832
869
  }
833
870
  finally {
834
871
  // the execution here ended: what this process held of the run's drafts goes
835
- this.drafts.release(runId);
872
+ if (this.active.get(runId) === state)
873
+ this.drafts.release(runId);
836
874
  }
837
875
  if (state.abandoned)
838
876
  return "abandoned";
@@ -919,13 +957,7 @@ let RunWorker = class RunWorker {
919
957
  }
920
958
  await this.hooks?.beforeRunning?.(runId, conversationId);
921
959
  // never over a terminal status: a run finished meanwhile stays finished
922
- const updated = await this.db
923
- .updateTable("runs")
924
- .set({ status: "running", started_at: sql `COALESCE(started_at, now())` })
925
- .where("id", "=", runId)
926
- .where("status", "in", ["queued", "running"])
927
- .returning("started_at")
928
- .executeTakeFirst();
960
+ const updated = await this.markRunning(runId);
929
961
  if (updated === undefined)
930
962
  return "finished";
931
963
  }
@@ -1165,7 +1197,17 @@ let RunWorker = class RunWorker {
1165
1197
  .execute();
1166
1198
  return written ?? null;
1167
1199
  }
1168
- /** 删除已结束运行的 checkpoint thread(失败只记日志)。 */
1200
+ /** Transition only an active run, within the execution fence. */
1201
+ async markRunning(runId) {
1202
+ return this.db
1203
+ .updateTable("runs")
1204
+ .set({ status: "running", started_at: sql `COALESCE(started_at, now())` })
1205
+ .where("id", "=", runId)
1206
+ .where("status", "in", ["queued", "running"])
1207
+ .returning("started_at")
1208
+ .executeTakeFirst();
1209
+ }
1210
+ /** Delete a terminal run's checkpoint thread; log cleanup failures. */
1169
1211
  async dropCheckpoints(runId) {
1170
1212
  await this.checkpoints
1171
1213
  .deleteThread(runId)
@@ -1196,6 +1238,9 @@ __decorate([
1196
1238
  __decorate([
1197
1239
  Transactional({ propagation: "requires_new" })
1198
1240
  ], RunWorker.prototype, "fallBackIn", null);
1241
+ __decorate([
1242
+ Transactional({ propagation: "requires_new" })
1243
+ ], RunWorker.prototype, "markRunning", null);
1199
1244
  RunWorker = __decorate([
1200
1245
  Injectable(),
1201
1246
  __param(0, Inject(KernelDb)),
@@ -1221,10 +1266,11 @@ RunWorker = __decorate([
1221
1266
  __param(20, Inject(PluginContextService)),
1222
1267
  __param(21, Inject(ProjectKnowledgeService)),
1223
1268
  __param(22, Inject(ToolRegistry)),
1224
- __param(23, Inject(RunFinish)),
1225
- __param(24, Inject(TransactionHost)),
1226
- __param(25, Inject(RunDrafts)),
1227
- __param(26, Optional()),
1228
- __param(26, Inject(RUN_HOOKS))
1269
+ __param(23, Inject(RunExecution)),
1270
+ __param(24, Inject(RunFinish)),
1271
+ __param(25, Inject(TransactionHost)),
1272
+ __param(26, Inject(RunDrafts)),
1273
+ __param(27, Optional()),
1274
+ __param(27, Inject(RUN_HOOKS))
1229
1275
  ], RunWorker);
1230
1276
  export { RunWorker };
@@ -35,7 +35,9 @@ import { ProvidersModule } from "./providers.js";
35
35
  import { EVAL_QUOTA, EVAL_QUOTA_PREFIX, OrgQuota, RUN_QUOTA, RUN_QUOTA_PREFIX } from "./quota.js";
36
36
  import { RunContextService } from "./run-context.service.js";
37
37
  import { RunControl } from "./run-control.js";
38
+ import { RunDeletion } from "./run-deletion.js";
38
39
  import { RunDrafts } from "./run-drafts.js";
40
+ import { RunExecution } from "./run-execution.js";
39
41
  import { RunFinish } from "./run-finish.js";
40
42
  import { RunJobsModule } from "./run-jobs.js";
41
43
  import { RunQueue } from "./run-queue.js";
@@ -84,6 +86,8 @@ RuntimeModule = __decorate([
84
86
  ],
85
87
  providers: [
86
88
  ConversationLock,
89
+ RunExecution,
90
+ RunDeletion,
87
91
  ConversationStreams,
88
92
  RunAbort,
89
93
  KyselyCheckpointSaver,
@@ -120,6 +124,8 @@ RuntimeModule = __decorate([
120
124
  ],
121
125
  exports: [
122
126
  ConversationLock,
127
+ RunExecution,
128
+ RunDeletion,
123
129
  ConversationStreams,
124
130
  RunAbort,
125
131
  KyselyCheckpointSaver,