mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 15:52:22 +01:00
Merge decision effect recovery repair into sleep-13-grok-dispatch
Propagate decision recovery fairness, durable malformed outcomes, and precise creation notifications while preserving this PR boundary. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
42e41bb1dc
5 files changed
+270
-62
No files matched your search
@@ -35,11 +35,19 @@ heartbeat scheduling is enabled. The public combined sweep retains its default
|
||||
recovery behavior for existing callers.
|
||||
|
||||
Each pass honors the existing configured batch size (default 100, finite values
|
||||
clamped to at least one integer). Its timestamp/ID cursor advances past failed or
|
||||
invalid candidates and wraps at the end. Failed rows retain their obligation.
|
||||
Rows without a saved decider are not executed under invented authority. A missing
|
||||
option produces an error. Both cases remain visible as unfinished work and retain
|
||||
retry scheduling rather than starving later candidates or being discarded.
|
||||
clamped to at least one integer). Its timestamp/ID cursor advances past failed
|
||||
candidates within a frozen final timestamp/ID. Newer due claims wait for the next
|
||||
rotation, so a continuous stream cannot postpone an earlier failure forever.
|
||||
Both cursor positions retain PostgreSQL precision. Genuine execution or settlement
|
||||
failures retain their retry obligation.
|
||||
|
||||
A missing saved decider or chosen option is a deterministic malformed outcome.
|
||||
Recovery rechecks it under a row lock, records an audited failed outcome (partial
|
||||
if a completed effect receipt exists), and preserves all effect receipts. It
|
||||
creates no authority and executes no effect for the malformed claim. The failure
|
||||
reason and continuation obligation are saved in the same transaction as the audit.
|
||||
An audit or settlement failure rolls back and leaves the claim pending. A claim
|
||||
repaired before the lock is acquired remains eligible for normal recovery.
|
||||
|
||||
The decision service re-reads current status before recovery. Foreground and
|
||||
recovery execution share the existing per-decision flight scoped to the DB owner.
|
||||
@@ -101,8 +109,10 @@ microsecond timestamp ahead of a valid claim. With a one-row page, the original
|
||||
Date cursor selected the invalid claim again and starved the valid effect. That
|
||||
regression failed before repair. Recovery now retains the timestamp as database
|
||||
text for cursor comparisons, leaving business grace deadlines unchanged. The
|
||||
invalid claim remains durable debt and is revisited after paging wraps; the valid
|
||||
claim progresses without repeating its completed effect.
|
||||
unresolved claim remains durable debt and is revisited after paging wraps; the
|
||||
valid claim progresses without repeating its completed effect. The regression
|
||||
now holds a candidate unresolved through the dispatch callback, because known
|
||||
malformed claims receive a durable failed outcome as described above.
|
||||
All 18 effect-recovery lifecycle cases and server typechecking pass after repair.
|
||||
|
||||
### Foreground join test timing
|
||||
@@ -133,3 +143,38 @@ and startup suites passed, followed by server typechecking. Evidence:
|
||||
and `/tmp/sleep-effect-join-root-types.log` with their status files. The initial
|
||||
failure and mutation failure are expected evidence, not passing runs. Remaining
|
||||
review findings and fresh stack CI remain separate acceptance requirements.
|
||||
|
||||
|
||||
### Recovery review repairs (October 26)
|
||||
|
||||
Two regressions failed before repair: an old failure was not revisited while newer
|
||||
due claims kept each page full, and creating an open decision caused an unnecessary
|
||||
effect-recovery scan. Frozen rotation boundaries now preserve both retry fairness
|
||||
and forward progress. Creation still signals its continuation/expiry consumers;
|
||||
the effect queue is signaled by the existing claim/settlement write boundary.
|
||||
|
||||
Four malformed-outcome cases also failed before repair. Recovery now records
|
||||
`effectRecoveryError` and a `decision.recovery_failed` activity atomically. Live
|
||||
activity publication follows commit. Existing completed effect receipts remain
|
||||
unchanged, and the normal continuation owner delivers the result. A real audit
|
||||
insert failure leaves both status and audit uncommitted, then later recovery
|
||||
settles successfully. A real PostgreSQL row-lock test repairs a claim while
|
||||
settlement waits; the locked recheck leaves that claim running, and its valid
|
||||
effect executes once on the next pass.
|
||||
|
||||
The shared execution flight now loads the current claim and derives recovery
|
||||
authority together. Recovery no longer performs a redundant full-row lookup
|
||||
before entering the flight. Foreground overlap, current membership checks,
|
||||
per-effect locks, continuation behavior, and the resumption count are preserved.
|
||||
Only the two known malformed states are terminalized; other failures retain their
|
||||
existing retry policy. No schema, queue, or external-wake contract is added.
|
||||
|
||||
All 24 recovery lifecycle cases and server typechecking pass. Controlled failures
|
||||
and final evidence are retained in `/tmp/sleep-effect-fairness-red.log`,
|
||||
`/tmp/sleep-effect-invalid-red.log`, `/tmp/sleep-effect-owner-tests.log`, and
|
||||
`/tmp/sleep-effect-owner-types.log`. Broader stack and remote acceptance remain
|
||||
separate requirements; these results do not prove host suspension.
|
||||
|
||||
The owning branch also passes all 129 cases across the four complete recovery,
|
||||
decision-service, expiry, and startup suites. Database-backed suites use separate
|
||||
migrated disposable databases. See `/tmp/sleep-effect-review-owner-acceptance.log`.
|
||||
@@ -1,11 +1,12 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { activityLog, agents, authUsers, companies, companyMemberships, createDb, decisionEffectExecutions,
|
||||
import { activityLog, agents, applyPendingMigrations, authUsers, companies, companyMemberships, createDb, decisionEffectExecutions,
|
||||
decisions, decisionRetention, decisionTargetIssues, heartbeatRuns, issueComments, issues } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { decisionService } from "../services/decisions.js";
|
||||
import { decisionEffectRecoveryService } from "../services/decision-effect-recovery.js";
|
||||
import { registerDecisionEffectRecoveryWork } from "../services/decision-effect-recovery-work.js";
|
||||
import { registerDecisionContinuationWork } from "../services/decision-continuation-work.js";
|
||||
import { writeDecisionChange } from "../services/decision-work-notifications.js";
|
||||
@@ -28,7 +29,8 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
|
||||
const service = () => decisionService(db, { wakeOriginAgent: wake });
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!externalUrl) temporary = await startEmbeddedPostgresTestDatabase("decision-effects-");
|
||||
if (externalUrl) await applyPendingMigrations(externalUrl);
|
||||
else temporary = await startEmbeddedPostgresTestDatabase("decision-effects-");
|
||||
db = createDb(externalUrl ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
||||
}, 30_000);
|
||||
beforeEach(async () => {
|
||||
@@ -109,6 +111,40 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
|
||||
await decide(row.id); await quiet(); expect(await comments()).toHaveLength(1); expect(wake).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not inspect effect recovery when an open decision is created", async () => {
|
||||
await start(); await quiet();
|
||||
const sweeps = vi.mocked(recovery.recoverEffects); sweeps.mockClear();
|
||||
await create(); await quiet();
|
||||
expect(sweeps).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retries an old failure while newer due claims keep filling pages", async () => {
|
||||
const failed = await create(), healthy = await create();
|
||||
const at = Date.now() - 600_000;
|
||||
await claim(failed.id, new Date(at)); await claim(healthy.id, new Date(at + 1));
|
||||
// Preserve PostgreSQL precision at both ends of the first rotation.
|
||||
await db.execute(sql`update decisions set updated_at = updated_at + interval '456 microseconds'
|
||||
where id in (${failed.id}, ${healthy.id})`);
|
||||
const failure = new Error("temporary recovery failure");
|
||||
const attempts: string[] = [];
|
||||
const scan = decisionEffectRecoveryService(db, async id => {
|
||||
attempts.push(id);
|
||||
if (id === failed.id) throw failure;
|
||||
await db.update(decisions).set({ executionStatus: "succeeded" }).where(eq(decisions.id, id));
|
||||
return true;
|
||||
});
|
||||
await expect(scan.sweep(new Date(), 1)).rejects.toBe(failure);
|
||||
const added: string[] = [];
|
||||
for (let index = 0; index < 7; index++) {
|
||||
const row = await create(); added.push(row.id); await claim(row.id, new Date(at + index + 2));
|
||||
try { await scan.sweep(new Date(), 1); } catch (error) { expect(error).toBe(failure); }
|
||||
}
|
||||
expect(attempts).toHaveLength(8);
|
||||
expect(attempts.slice(0, 6)).toEqual([failed.id, healthy.id, failed.id, added[0], added[1], failed.id]);
|
||||
expect(new Set(attempts.filter(id => id !== failed.id)).size).toBe(5);
|
||||
expect((await service().get(failed.id))?.executionStatus).toBe("running");
|
||||
});
|
||||
|
||||
it("reactivates from the actual claim and recovers a failed settlement without repeating the effect", async () => {
|
||||
await start(); await quiet(); const row = await create(); await failSettlement();
|
||||
await expect(decide(row.id)).rejects.toMatchObject({ cause: { message: "settlement unavailable" } });
|
||||
@@ -244,46 +280,125 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
|
||||
expect(await service().sweepExpired()).toEqual({ expired: 0, resumed: 1 }); expect(await comments()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("pages past invalid legacy claims without inventing authority or losing their debt", async () => {
|
||||
it.each(["missing_decider", "missing_option"] as const)("settles %s as durable failure and then becomes quiet", async reason => {
|
||||
const row = await create(); await claim(row.id, new Date(Date.now() - 120_000));
|
||||
await db.update(decisions).set(reason === "missing_decider" ? { decidedByUserId: null } : { chosenOptionId: "missing" })
|
||||
.where(eq(decisions.id, row.id));
|
||||
expect(await service().recoverEffects()).toEqual({ resumed: 1 });
|
||||
expect(await service().get(row.id)).toMatchObject({ executionStatus: "failed", metadata: {
|
||||
effectRecoveryError: reason, continuationPending: false,
|
||||
} });
|
||||
expect(await comments()).toHaveLength(0);
|
||||
expect(await db.select().from(decisionEffectExecutions)).toHaveLength(0);
|
||||
const audit = await db.select().from(activityLog).where(eq(activityLog.action, "decision.recovery_failed"));
|
||||
expect(audit).toHaveLength(1);
|
||||
expect(audit[0]).toMatchObject({ companyId, actorType: "system", actorId: "decision-executor",
|
||||
entityId: row.id, details: { reason } });
|
||||
expect(wake).toHaveBeenCalledTimes(1);
|
||||
await start(); await quiet();
|
||||
expect(wake).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves completed effect receipts when a malformed outcome settles as partial", async () => {
|
||||
const row = await create(); await claim(row.id, new Date(Date.now() - 120_000));
|
||||
await db.update(decisions).set({ chosenOptionId: "missing" }).where(eq(decisions.id, row.id));
|
||||
const [receipt] = await db.insert(decisionEffectExecutions).values({ decisionId: row.id, effectIndex: 0,
|
||||
effectType: "comment_on_issue", targetIssueId: targetId, status: "executed", result: { preserved: true }, executedAt: new Date() }).returning();
|
||||
expect(await service().recoverEffects()).toEqual({ resumed: 1 });
|
||||
expect((await service().get(row.id))?.executionStatus).toBe("partial");
|
||||
expect(await db.select().from(decisionEffectExecutions)).toEqual([receipt]);
|
||||
expect(await comments()).toHaveLength(0);
|
||||
expect(wake).toHaveBeenCalledTimes(1);
|
||||
await start(); await quiet();
|
||||
});
|
||||
|
||||
it("keeps malformed claims pending when their failure audit cannot commit", async () => {
|
||||
const row = await create(); await claim(row.id, new Date(Date.now() - 120_000));
|
||||
await db.update(decisions).set({ decidedByUserId: null }).where(eq(decisions.id, row.id));
|
||||
await db.execute(sql`create function decision_recovery_audit_fail() returns trigger language plpgsql as $$ begin
|
||||
if NEW.action = 'decision.recovery_failed' then raise exception 'recovery audit unavailable'; end if;
|
||||
return NEW; end $$`);
|
||||
await db.execute(sql`create trigger decision_recovery_audit_fail before insert on activity_log
|
||||
for each row execute function decision_recovery_audit_fail()`);
|
||||
try {
|
||||
await expect(service().recoverEffects()).rejects.toMatchObject({ cause: { message: "recovery audit unavailable" } });
|
||||
expect((await service().get(row.id))?.executionStatus).toBe("running");
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.action, "decision.recovery_failed"))).toHaveLength(0);
|
||||
expect(wake).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await db.execute(sql`drop trigger decision_recovery_audit_fail on activity_log`);
|
||||
await db.execute(sql`drop function decision_recovery_audit_fail()`);
|
||||
}
|
||||
expect(await service().recoverEffects()).toEqual({ resumed: 1 });
|
||||
expect((await service().get(row.id))?.executionStatus).toBe("failed");
|
||||
expect(wake).toHaveBeenCalledTimes(1);
|
||||
await start(); await quiet();
|
||||
});
|
||||
|
||||
it("rechecks a malformed claim under lock before settling a concurrently repaired outcome", async () => {
|
||||
const row = await create(); const at = new Date(Date.now() - 120_000); await claim(row.id, at);
|
||||
await db.update(decisions).set({ chosenOptionId: "missing" }).where(eq(decisions.id, row.id));
|
||||
let release!: () => void, locked!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const acquired = new Promise<void>(resolve => { locked = resolve; });
|
||||
const repair = db.transaction(async tx => {
|
||||
await tx.select({ id: decisions.id }).from(decisions).where(eq(decisions.id, row.id)).for("update");
|
||||
locked(); await gate;
|
||||
await tx.update(decisions).set({ chosenOptionId: "yes", updatedAt: at }).where(eq(decisions.id, row.id));
|
||||
});
|
||||
const previousDebug = db.$client.options.debug;
|
||||
let attempts = 0;
|
||||
let pending: ReturnType<ReturnType<typeof decisionService>["recoverEffects"]> | undefined;
|
||||
try {
|
||||
await acquired;
|
||||
db.$client.options.debug = (_connection, query, parameters) => {
|
||||
if (query.includes("for update") && parameters.includes(row.id)) attempts++;
|
||||
};
|
||||
pending = service().recoverEffects();
|
||||
await vi.waitFor(() => expect(attempts).toBe(1));
|
||||
release(); await repair;
|
||||
expect(await pending).toEqual({ resumed: 0 });
|
||||
expect(await service().get(row.id)).toMatchObject({ executionStatus: "running", chosenOptionId: "yes" });
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.action, "decision.recovery_failed"))).toHaveLength(0);
|
||||
expect(wake).not.toHaveBeenCalled();
|
||||
expect(await service().recoverEffects()).toEqual({ resumed: 1 });
|
||||
expect(await comments()).toHaveLength(1); expect(wake).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
release(); await Promise.allSettled([repair, pending]); db.$client.options.debug = previousDebug;
|
||||
}
|
||||
await start(); await quiet();
|
||||
});
|
||||
|
||||
it("settles invalid legacy claims without inventing authority or blocking later effects", async () => {
|
||||
vi.stubEnv("PAPERCLIP_DECISIONS_SWEEP_BATCH_SIZE", "1");
|
||||
const invalid = await create(), valid = await create();
|
||||
await claim(invalid.id, new Date(Date.now() - 180_000)); await claim(valid.id, new Date(Date.now() - 120_000));
|
||||
await db.update(decisions).set({ decidedByUserId: null }).where(eq(decisions.id, invalid.id));
|
||||
const recovery = service();
|
||||
expect(await recovery.recoverEffects()).toEqual({ resumed: 0 }); expect(await recovery.nextEffectRecoveryAt()).not.toBeNull();
|
||||
expect(await recovery.recoverEffects()).toEqual({ resumed: 1 }); expect(await comments()).toHaveLength(1);
|
||||
expect((await recovery.get(invalid.id))?.executionStatus).toBe("running");
|
||||
expect(await recovery.nextEffectRecoveryAt()).not.toBeNull();
|
||||
});
|
||||
|
||||
it("pages past invalid claims using database timestamp precision", async () => {
|
||||
vi.stubEnv("PAPERCLIP_DECISIONS_SWEEP_BATCH_SIZE", "1");
|
||||
const invalid = await create(), valid = await create();
|
||||
await claim(invalid.id); await claim(valid.id, new Date(Date.now() - 120_000));
|
||||
await db.execute(sql`update decisions set decided_by_user_id = null,
|
||||
updated_at = date_trunc('milliseconds', now() - interval '3 minutes') + interval '456 microseconds'
|
||||
where id = ${invalid.id}`);
|
||||
const recovery = service();
|
||||
expect(await recovery.recoverEffects()).toEqual({ resumed: 0 });
|
||||
expect(await recovery.recoverEffects()).toEqual({ resumed: 1 });
|
||||
expect(await comments()).toHaveLength(1);
|
||||
expect((await recovery.get(invalid.id))?.executionStatus).toBe("running");
|
||||
expect(await recovery.nextEffectRecoveryAt()).not.toBeNull();
|
||||
expect(await recovery.recoverEffects()).toEqual({ resumed: 0 });
|
||||
expect(await recovery.recoverEffects()).toEqual({ resumed: 0 });
|
||||
expect(await comments()).toHaveLength(1);
|
||||
expect(await comments()).toHaveLength(0);
|
||||
expect(await recovery.recoverEffects()).toEqual({ resumed: 1 }); expect(await comments()).toHaveLength(1);
|
||||
expect((await recovery.get(invalid.id))?.executionStatus).toBe("failed");
|
||||
expect(await recovery.nextEffectRecoveryAt()).toBeNull();
|
||||
});
|
||||
|
||||
it("advances past malformed claims and retries them on a later pass", async () => {
|
||||
vi.stubEnv("PAPERCLIP_DECISIONS_SWEEP_BATCH_SIZE", "1");
|
||||
const invalid = await create(), valid = await create();
|
||||
await claim(invalid.id, new Date(Date.now() - 180_000)); await claim(valid.id, new Date(Date.now() - 120_000));
|
||||
await db.update(decisions).set({ chosenOptionId: "missing" }).where(eq(decisions.id, invalid.id));
|
||||
const recovery = service();
|
||||
await expect(recovery.recoverEffects()).rejects.toThrow("Stored decision outcome is invalid");
|
||||
expect(await recovery.recoverEffects()).toEqual({ resumed: 1 }); expect(await comments()).toHaveLength(1);
|
||||
await recovery.recoverEffects();
|
||||
await expect(recovery.recoverEffects()).rejects.toThrow("Stored decision outcome is invalid");
|
||||
it("pages past unresolved claims using database timestamp precision", async () => {
|
||||
const pending = await create(), valid = await create();
|
||||
await claim(pending.id); await claim(valid.id, new Date(Date.now() - 120_000));
|
||||
await db.execute(sql`update decisions set updated_at = date_trunc('milliseconds', now() - interval '3 minutes')
|
||||
+ interval '456 microseconds' where id = ${pending.id}`);
|
||||
const scan = decisionEffectRecoveryService(db, async id => {
|
||||
if (id === pending.id) return false;
|
||||
await decide(id); return true;
|
||||
});
|
||||
expect(await scan.sweep(new Date(), 1)).toEqual({ resumed: 0 });
|
||||
expect(await scan.sweep(new Date(), 1)).toEqual({ resumed: 1 });
|
||||
expect(await comments()).toHaveLength(1);
|
||||
expect((await service().get(pending.id))?.executionStatus).toBe("running");
|
||||
expect(await scan.next()).not.toBeNull();
|
||||
expect(await scan.sweep(new Date(), 1)).toEqual({ resumed: 0 });
|
||||
expect(await scan.sweep(new Date(), 1)).toEqual({ resumed: 0 });
|
||||
expect(await comments()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([false, true])("preserves archive recovery semantics with prior committed archive: %s", async committed => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, asc, lte, sql } from "drizzle-orm";
|
||||
import { and, asc, desc, lte, sql } from "drizzle-orm";
|
||||
import { decisions, type Db } from "@paperclipai/db";
|
||||
|
||||
const running = sql`${decisions.status} = 'decided' AND ${decisions.executionStatus} = 'running'`;
|
||||
@@ -14,13 +14,25 @@ function recoveryGraceMs() {
|
||||
}
|
||||
|
||||
export function decisionEffectRecoveryService(db: Db, resume: (id: string) => Promise<boolean>) {
|
||||
let cursor: { updatedAt: string; id: string } | undefined;
|
||||
type Position = { updatedAt: string; id: string };
|
||||
let cursor: Position | undefined;
|
||||
let boundary: Position | undefined;
|
||||
|
||||
async function sweep(now = new Date(), limit = decisionSweepBatchSize(), signal?: AbortSignal) {
|
||||
let resumed = 0;
|
||||
if (signal?.aborted) return { resumed };
|
||||
const rows = await db.select({ id: decisions.id, updatedAt: sql<string>`${decisions.updatedAt}::text` }).from(decisions)
|
||||
.where(and(running, lte(decisions.updatedAt, new Date(now.getTime() - recoveryGraceMs())), cursor
|
||||
const dueBefore = new Date(now.getTime() - recoveryGraceMs());
|
||||
const position = { id: decisions.id, updatedAt: sql<string>`${decisions.updatedAt}::text` };
|
||||
if (!boundary) {
|
||||
// Finish this rotation even if newer due claims arrive on every page.
|
||||
[boundary] = await db.select(position).from(decisions)
|
||||
.where(and(running, lte(decisions.updatedAt, dueBefore)))
|
||||
.orderBy(desc(decisions.updatedAt), desc(decisions.id)).limit(1);
|
||||
if (!boundary) return { resumed };
|
||||
}
|
||||
const rows = await db.select(position).from(decisions)
|
||||
.where(and(running, lte(decisions.updatedAt, dueBefore),
|
||||
sql`(${decisions.updatedAt}, ${decisions.id}) <= (${boundary.updatedAt}::timestamptz, ${boundary.id}::uuid)`, cursor
|
||||
? sql`(${decisions.updatedAt}, ${decisions.id}) > (${cursor.updatedAt}::timestamptz, ${cursor.id}::uuid)` : undefined))
|
||||
.orderBy(asc(decisions.updatedAt), asc(decisions.id)).limit(limit);
|
||||
const errors: unknown[] = [];
|
||||
@@ -29,7 +41,10 @@ export function decisionEffectRecoveryService(db: Db, resume: (id: string) => Pr
|
||||
try { if (await resume(row.id)) resumed++; } catch (error) { errors.push(error); }
|
||||
cursor = row;
|
||||
}
|
||||
if (rows.length < limit) cursor = undefined;
|
||||
const last = rows.at(-1);
|
||||
if (rows.length < limit || (last?.id === boundary.id && last.updatedAt === boundary.updatedAt)) {
|
||||
cursor = undefined; boundary = undefined;
|
||||
}
|
||||
if (errors.length === 1) throw errors[0];
|
||||
if (errors.length) throw new AggregateError(errors, "Decision effect recovery failed");
|
||||
return { resumed };
|
||||
|
||||
@@ -4,12 +4,12 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notificatio
|
||||
export async function notifyDecisionChange(transaction: object) {
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.decisionContinuation);
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.decisionExpiry);
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.decisionEffectRecovery);
|
||||
}
|
||||
|
||||
export function writeDecisionChange<T>(db: Db, write: (transaction: Db) => Promise<T>): Promise<T> {
|
||||
return db.transaction(async transaction => {
|
||||
await notifyDecisionChange(transaction);
|
||||
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.decisionEffectRecovery);
|
||||
return write(transaction as unknown as Db);
|
||||
});
|
||||
}
|
||||
@@ -27,7 +27,8 @@ type Snapshot = { status: string; assigneeAgentId: string | null; assigneeUserId
|
||||
export type DecisionServiceOptions = { wakeOriginAgent: DecisionContinuationWake };
|
||||
const DAY = 86_400_000;
|
||||
type DecisionOutcome = typeof decisions.$inferSelect & { executions: Array<typeof decisionEffectExecutions.$inferSelect> };
|
||||
const effectFlights = new WeakMap<object, Map<string, Promise<DecisionOutcome>>>();
|
||||
type EffectAttempt = { outcome: DecisionOutcome; resumed: boolean };
|
||||
const effectFlights = new WeakMap<object, Map<string, Promise<EffectAttempt | null>>>();
|
||||
|
||||
function targetIds(options: DecisionOption[]) {
|
||||
const result = new Set<string>();
|
||||
@@ -563,21 +564,53 @@ export function decisionService(db: Db, options: DecisionServiceOptions) {
|
||||
}
|
||||
}
|
||||
|
||||
function runEffects(decision: typeof decisions.$inferSelect, userActor: AuthorizationActor): Promise<DecisionOutcome> {
|
||||
const existing = executing.get(decision.id);
|
||||
function runEffects(id: string, userActor?: AuthorizationActor): Promise<EffectAttempt | null> {
|
||||
const existing = executing.get(id);
|
||||
if (existing) return existing;
|
||||
const attempt = (async () => {
|
||||
const current = await get(decision.id);
|
||||
if (!current) throw notFound("Decision not found");
|
||||
return current.executionStatus === "running" ? executeDecisionEffects(current, userActor) : outcome(current.id);
|
||||
})().finally(() => { executing.delete(decision.id); });
|
||||
executing.set(decision.id, attempt);
|
||||
const current = await get(id);
|
||||
if (!current) return null;
|
||||
if (current.status !== "decided" || current.executionStatus !== "running") {
|
||||
return { outcome: await outcome(id), resumed: false };
|
||||
}
|
||||
// Recovery derives authority from the current claim inside the shared flight.
|
||||
const actor = userActor ?? (current.decidedByUserId
|
||||
? await recoveryActor(current.companyId, current.decidedByUserId)
|
||||
: { type: "none" as const, source: "none" as const });
|
||||
return { outcome: await executeDecisionEffects(current, actor), resumed: true };
|
||||
})().finally(() => { executing.delete(id); });
|
||||
executing.set(id, attempt);
|
||||
return attempt;
|
||||
}
|
||||
|
||||
async function settleInvalidEffectOutcome(id: string) {
|
||||
const publications: ActivityPublication[] = [];
|
||||
await writeDecisionChange(db, async tx => {
|
||||
const [current] = await tx.select().from(decisions).where(eq(decisions.id, id)).for("update");
|
||||
if (!current || current.status !== "decided" || current.executionStatus !== "running") return;
|
||||
const reason = !current.decidedByUserId ? "missing_decider"
|
||||
: !current.options.some(option => option.id === current.chosenOptionId) ? "missing_option" : null;
|
||||
if (!reason) return;
|
||||
const [executed] = await tx.select({ id: decisionEffectExecutions.id }).from(decisionEffectExecutions)
|
||||
.where(and(eq(decisionEffectExecutions.decisionId, id), eq(decisionEffectExecutions.status, "executed"))).limit(1);
|
||||
const executionStatus = executed ? "partial" : "failed";
|
||||
await tx.update(decisions).set({ executionStatus, updatedAt: new Date(), metadata: { ...current.metadata,
|
||||
effectRecoveryError: reason,
|
||||
...(current.continuationPolicy === "wake_origin_agent" ? { continuationPending: true } : {}),
|
||||
} }).where(eq(decisions.id, id));
|
||||
await logActivity(tx, { companyId: current.companyId, actorType: "system", actorId: "decision-executor",
|
||||
agentId: current.originAgentId, runId: current.originRunId, responsibleUserIdOverride: current.decidedByUserId,
|
||||
action: "decision.recovery_failed", entityType: "decision", entityId: id,
|
||||
details: { reason, executionStatus, chosenOptionId: current.chosenOptionId, decidedByUserId: current.decidedByUserId },
|
||||
}, publications);
|
||||
});
|
||||
for (const publication of publications) publishActivity(publication);
|
||||
return outcome(id);
|
||||
}
|
||||
|
||||
async function executeDecisionEffects(decision: typeof decisions.$inferSelect, userActor: AuthorizationActor) {
|
||||
const option = decision.options.find((item) => item.id === decision.chosenOptionId);
|
||||
if (!option || !decision.decidedByUserId) throw unprocessable("Stored decision outcome is invalid");
|
||||
if (!option || !decision.decidedByUserId) return settleInvalidEffectOutcome(decision.id);
|
||||
const run = await db.select({ responsibleUserId: heartbeatRuns.responsibleUserId }).from(heartbeatRuns).where(eq(heartbeatRuns.id, decision.originRunId)).then((rows) => rows[0] ?? null);
|
||||
const metadata = decision.metadata as Record<string, unknown>;
|
||||
if (metadata.kind === "attention_archive_proposal") {
|
||||
@@ -641,7 +674,9 @@ export function decisionService(db: Db, options: DecisionServiceOptions) {
|
||||
}
|
||||
|
||||
async function resumeDecision(decision: typeof decisions.$inferSelect, userActor: AuthorizationActor) {
|
||||
const result = decision.executionStatus === "running" ? await runEffects(decision, userActor) : await outcome(decision.id);
|
||||
const attempt = decision.executionStatus === "running" ? await runEffects(decision.id, userActor) : undefined;
|
||||
if (attempt === null) throw notFound("Decision not found");
|
||||
const result = attempt?.outcome ?? await outcome(decision.id);
|
||||
await continuations.deliver(result.id);
|
||||
return outcome(decision.id);
|
||||
}
|
||||
@@ -723,11 +758,9 @@ export function decisionService(db: Db, options: DecisionServiceOptions) {
|
||||
}
|
||||
|
||||
async function recoverDecisionEffects(id: string) {
|
||||
const current = await get(id);
|
||||
if (!current || current.status !== "decided" || current.executionStatus !== "running" || !current.decidedByUserId) return false;
|
||||
const recovered = await runEffects(current, await recoveryActor(current.companyId, current.decidedByUserId));
|
||||
if (recovered.executionStatus === "running") return false;
|
||||
await continuations.deliver(recovered.id);
|
||||
const attempt = await runEffects(id);
|
||||
if (!attempt?.resumed || attempt.outcome.executionStatus === "running") return false;
|
||||
await continuations.deliver(attempt.outcome.id);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user