pi-better-background-tasks 0.15.1 → 0.15.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.15.1",
3
+ "version": "0.15.3",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1032,7 +1032,7 @@ export class ObservedWaitHost {
1032
1032
  /** Recover a callback a previous host recorded terminal but never delivered. */
1033
1033
  private recoverTerminalNotifications(): void {
1034
1034
  if (!this.store) return;
1035
- for (const operation of this.store.listOperations({ phase: "terminal" })) {
1035
+ for (const operation of this.activeParentTerminalOperations()) {
1036
1036
  if (operation.terminalOutcome === null) continue;
1037
1037
  this.attemptTerminalCallback(
1038
1038
  operation,
@@ -1043,6 +1043,15 @@ export class ObservedWaitHost {
1043
1043
  }
1044
1044
  }
1045
1045
 
1046
+ private activeParentTerminalOperations(): OperationRecord[] {
1047
+ const origin = this.activeOrigin;
1048
+ if (!this.store || !origin?.sessionId) return [];
1049
+ return this.store.listOperations({
1050
+ phase: "terminal",
1051
+ ownerScope: { kind: "parent-session", sessionId: origin.sessionId, workspace: origin.cwd },
1052
+ });
1053
+ }
1054
+
1046
1055
  /**
1047
1056
  * Discover durable tasks launched by any host sharing this supervisor
1048
1057
  * directory. A host that started before a task was registered never saw it in
@@ -3345,7 +3354,7 @@ export class ObservedWaitHost {
3345
3354
  });
3346
3355
  } catch { /* another host already recovered it */ }
3347
3356
  }
3348
- for (const operation of store.listOperations({ phase: "terminal" })) {
3357
+ for (const operation of this.activeParentTerminalOperations()) {
3349
3358
  const context = this.currentLaunchContext(operation.taskId);
3350
3359
  if (!context?.callbackClaimedBy || context.callbackClaimedBy === this.hostId) continue;
3351
3360
  if (this.claimState(context.callbackClaimedBy) !== "dead") continue;
@@ -3369,16 +3378,9 @@ export class ObservedWaitHost {
3369
3378
  private async dispatchOutbox(): Promise<void> {
3370
3379
  const store = this.store;
3371
3380
  if (!store || this.closed) return;
3372
- const pending = store.listOutbox({ state: "pending" });
3381
+ const pending = store.listDispatchableOutboxRecipients();
3373
3382
  if (pending.length === 0) return;
3374
- const byRecipient = new Map<string, { owner: OwnerIdentity; events: OutboxEventRecord[] }>();
3375
- for (const event of pending) {
3376
- const key = ownerKey(event.recipient);
3377
- const entry = byRecipient.get(key) ?? { owner: event.recipient, events: [] };
3378
- entry.events.push(event);
3379
- byRecipient.set(key, entry);
3380
- }
3381
- for (const { owner, events } of byRecipient.values()) {
3383
+ for (const { recipient: owner, count } of pending) {
3382
3384
  // Foreign parents cannot receive a handoff here. Leave their events pending
3383
3385
  // without taking a write lock on every reconciliation pass.
3384
3386
  if (owner.kind === "parent-session") {
@@ -3394,7 +3396,7 @@ export class ObservedWaitHost {
3394
3396
  recipient: owner,
3395
3397
  claimToken,
3396
3398
  claimedBy: this.hostId,
3397
- limit: Math.min(events.length, 20),
3399
+ limit: Math.min(count, 20),
3398
3400
  });
3399
3401
  } catch (error) {
3400
3402
  this.options.logger?.(`observed waits: outbox claim failed: ${oneLine(String(error), 160)}`);
@@ -24,11 +24,12 @@ import { StoreError } from "./errors.ts";
24
24
  import {
25
25
  dependencyState,
26
26
  mapOutbox,
27
+ ownerFromRow,
27
28
  readOperationEvidence,
28
29
  readOutboxRow,
29
30
  requireWaitRow,
30
31
  } from "./rows.ts";
31
- import { columnJson, columnNullableText, columnText, getRows, run, type StoreContext } from "./sqlite.ts";
32
+ import { columnJson, columnNullableText, columnNumber, columnText, getRows, run, type StoreContext } from "./sqlite.ts";
32
33
  import type {
33
34
  ClaimOutboxInput,
34
35
  OutboxDispatchClaim,
@@ -280,6 +281,23 @@ export function listOutbox(ctx: StoreContext, filter: OutboxFilter = {}): Outbox
280
281
  ).map((row) => mapOutbox(ctx, row));
281
282
  }
282
283
 
284
+ /** Find recipients with deliverable dependencies without loading each event's evidence. */
285
+ export function listDispatchableOutboxRecipients(ctx: StoreContext): Array<{ recipient: OwnerIdentity; count: number }> {
286
+ return getRows(
287
+ ctx,
288
+ `SELECT recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
289
+ count(*) AS pending_count
290
+ FROM outbox_events
291
+ WHERE state = 'pending' AND event_type = 'dependency-ready'
292
+ AND EXISTS (SELECT 1 FROM waits w WHERE w.wait_id = outbox_events.wait_id
293
+ AND w.generation = outbox_events.generation
294
+ AND w.phase IN (${placeholders(DELIVERABLE_WAIT_PHASES.length)}))
295
+ GROUP BY recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id
296
+ ORDER BY min(created_at), min(event_id)`,
297
+ ...DELIVERABLE_WAIT_PHASES,
298
+ ).map((row) => ({ recipient: ownerFromRow(row, "recipient"), count: columnNumber(row, "pending_count") }));
299
+ }
300
+
283
301
  function readDispatchClaim(row: Record<string, unknown>): OutboxDispatchClaim | null {
284
302
  return columnJson<OutboxDispatchClaim>(row, "dispatch_claim_json");
285
303
  }
@@ -58,6 +58,7 @@ import {
58
58
  } from "./waits.ts";
59
59
  import {
60
60
  claimOutbox as writeOutboxClaim,
61
+ listDispatchableOutboxRecipients as readDispatchableOutboxRecipients,
61
62
  listOutbox as readOutbox,
62
63
  markOutboxDelivered as writeOutboxDelivery,
63
64
  releaseOutbox as writeOutboxRelease,
@@ -272,6 +273,8 @@ export interface Store {
272
273
  // ---- outbox ----
273
274
 
274
275
  listOutbox(filter?: OutboxFilter): OutboxEventRecord[];
276
+ /** Lightweight dispatch candidates; evidence is read only after a claim succeeds. */
277
+ listDispatchableOutboxRecipients(): Array<{ recipient: OwnerIdentity; count: number }>;
275
278
  /** Claim pending deliveries for a `ready`/`resuming` generation. */
276
279
  claimOutbox(input: ClaimOutboxInput): OutboxEventRecord[];
277
280
  /** Mark a claimed delivery delivered; the result is still unconsumed. */
@@ -457,6 +460,10 @@ export function openStore(options: StoreOptions): Store {
457
460
  alive();
458
461
  return readOutbox(ctx, filter);
459
462
  },
463
+ listDispatchableOutboxRecipients() {
464
+ alive();
465
+ return readDispatchableOutboxRecipients(ctx);
466
+ },
460
467
  claimOutbox(input) {
461
468
  alive();
462
469
  return writeOutboxClaim(ctx, input);
@@ -484,7 +484,7 @@ export interface ReleaseResumeClaimResult {
484
484
  }
485
485
 
486
486
  /**
487
- * Proof that the published resume attempt can never interpret the generation:
487
+ * Proof that the published resume attempt can no longer write the conversation:
488
488
  * its writer process is gone and its conversation writer lease is free. A live
489
489
  * writer or an unverifiable identity must never be passed here.
490
490
  */
@@ -499,6 +499,8 @@ export interface ResumeAttemptExitProof {
499
499
  * evidence pins stay, and the generation remains visible to its owner. The claim
500
500
  * is invalidated (it can never publish again), which is what makes a second
501
501
  * automatic attempt impossible.
502
+ * If interpretation already consumed the wait, exact exit proof only invalidates
503
+ * the published writer claim and preserves the interpretation receipt.
502
504
  */
503
505
  export interface HoldFailedResumeInput {
504
506
  waitId: string;
@@ -508,7 +510,7 @@ export interface HoldFailedResumeInput {
508
510
  attemptId: string;
509
511
  launchToken: string;
510
512
  proof: ResumeAttemptExitProof;
511
- /** Why the attempt never interpreted the generation; retained on both records. */
513
+ /** Exit reason; a consumed generation's receipt is preserved. */
512
514
  reason: string;
513
515
  }
514
516
 
@@ -913,10 +913,14 @@ export function holdFailedResume(
913
913
 
914
914
  return ctx.transaction(() => {
915
915
  const terminal = getRow(ctx, "SELECT assignment_id FROM assignment_outcome_waits WHERE wait_id = ? AND generation = ?", waitId, generation);
916
- if (terminal) {
916
+ const recorded = requireWait(ctx, waitId, generation);
917
+ // Interpretation ends the wait, but its writer may continue until exit.
918
+ // Exact exit proof releases only that writer's claim, preserving the receipt.
919
+ if (terminal || recorded.phase === "consumed") {
917
920
  const claim = requireClaim(ctx, claimId);
918
921
  if (claim.waitId !== waitId || claim.generation !== generation || claim.claimToken !== claimToken
919
922
  || claim.attemptId !== attemptId || claim.launchToken !== launchToken) throw new StoreError("claim-state", "Terminal writer exit proof does not match the published attempt.");
923
+ if (!terminal && claim.cancelEpoch !== recorded.cancelEpoch) throw new StoreError("stale-cancel-epoch", "Writer exit proof belongs to a different cancellation epoch.");
920
924
  const applied = claim.state === "published";
921
925
  if (applied) run(ctx, "UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ? WHERE claim_id = ?", ctx.now(), reason, claimId);
922
926
  return { wait: requireWait(ctx, waitId, generation), claim: requireClaim(ctx, claimId), applied };