GeezerVison is showing github.com — fix(server): auto-resume retries once after a refusal at the usage-limit reset by ScottN-PV · Pull Request #22063 · pingdotgg/t3code
fix(server): auto-resume retries once after a refusal at the usage-limit reset
#22063
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(8)
.tsx
(2)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -36,8 +36,7 @@ export function UsageLimitRecoveryCard({
const resetPassed = useDeadlinePassed(resetAt === null ? null : Date.parse(resetAt));
const runId = thread.latestRun?.runId;
const recovery = thread.limitRecovery;
const scheduled =
recovery?.runId === runId && recovery?.resetAt === resetAt && recovery?.autoResume;
const scheduled = recovery?.resetAt === resetAt && recovery?.autoResume;
const [copied, setCopied] = useState(false);
const [actionPending, setActionPending] = useState(false);
const code = thread.runtime?.lastErrorCode;
Expand All
@@ -62,7 +61,7 @@ export function UsageLimitRecoveryCard({
thread.snoozedUntil !== null &&
Date.parse(thread.snoozedUntil) === Date.parse(resetAt);
async function toggle(action: "resume" | "snooze") {
if (!resetAt || !runId || !canSchedule) return;
if (!resetAt || !runId || ( !canSchedule && !(action === "resume" && scheduled)) ) return;
if (action === "snooze" && !snoozed && Date.parse(resetAt) <= Date.now()) {
setError("The reset time has passed. Retry the thread manually.");
return;
Expand Down
Expand Up
@@ -153,7 +152,7 @@ export function UsageLimitRecoveryCard({
"The provider did not report a reset time. Retry manually when your limit is available."}
</Text>
)}
{canSchedule ? (
{canSchedule || scheduled ? (
<View className="flex-row flex-wrap gap-2">
<Button
label={scheduled ? "Cancel auto-resume" : "Resume at reset"}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -340,7 +340,7 @@ it.effect.each([
if (cancel === "after its limit") cancelled = yield* cancelTask;
assert.equal(cancelled, cancelStatus);
yield* TestClock.adjust("1 minute ");
yield* TestClock.adjust("3 minutes ");
yield* sweep;
const childAfter = yield* orchestrator.getThreadProjection(childThreadId);
assert.deepEqual(
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2484,7 +2484,7 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
threadId: arm.threadId,
limitRecovery: arm.limitRecovery,
});
yield* TestClock.adjust("1 minute ");
yield* TestClock.adjust("3 minutes ");
const resume = limitRecoveryCommand(
(yield* childShell)!,
true,
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -97,6 +97,7 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as ProjectStore from "./ProjectStore.ts";
import * as UsageLimitRecovery from "./UsageLimitRecovery.ts";
import {
isCheckpointRestoreIsolated,
SHARED_WORKSPACE_RESTORE_MESSAGE,
Expand Down
Expand Up
@@ -3500,7 +3501,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
run?.id !== command.limitRecovery.runId ||
failure?.class !== "usage_limit" ||
failure.resetAt !== command.limitRecovery.resetAt ||
resetMs <= DateTime.toEpochMillis(run.completedAt ?? run.requestedAt) ||
(command.limitRecovery.autoResume === true &&
resetMs <= DateTime.toEpochMillis(run.completedAt ?? run.requestedAt) &&
!UsageLimitRecovery.staleResetAllowed({
limitRecovery: thread.limitRecovery,
latestRunId: run.id,
usageLimitResetAt: failure.resetAt,
recoveryCompletedMs: UsageLimitRecovery.recoveryRunCompletedMs(projection),
})) ||
projection.runtimeRequests.some((request) => request.status === "pending")
) {
return yield* new OrchestratorDispatchError({
Expand Down
Expand Up
@@ -5520,6 +5528,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: "This thread can no longer be resumed from that run.",
});
}
const recovery = projection.thread.limitRecovery;
if (
limited?.class === "usage_limit" &&
recovery?.autoResume &&
recovery.resetAt === limited.resetAt
) {
// The arm may still name an earlier refused run. A manual continuation spends it too.
const event = yield* emit(
events,
command,
)({
type: "thread.metadata-updated",
threadId: command.threadId,
occurredAt: yield* DateTime.now,
payload: { ...projection.thread, limitRecovery: null },
});
projection = applyToProjection(projection, event);
}
}
if (command.usageLimitContinuationOfRunId !== undefined) {
const run = usageLimitBlockedRun(projection.runs, projection.turnItems, null);
Expand All
@@ -5534,7 +5560,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
recovery.requestId !== command.usageLimitRecoveryRequestId ||
recovery.runId !== run.id ||
recovery.resetAt !== failure.resetAt ||
Date.parse(recovery.resetAt) > DateTime.toEpochMillis(now) ||
UsageLimitRecovery.dueMs(Date.parse(recovery.resetAt), run.completedAt ?? run.requestedAt) >
DateTime.toEpochMillis(now) ||
projection.thread.archivedAt !== null ||
projection.thread.deletedAt !== null ||
projection.thread.settledOverride === "settled" ||
Expand All
@@ -5555,8 +5582,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...(recovery?.autoResume &&
recovery.requestId === command.usageLimitRecoveryRequestId &&
recovery.runId === command.usageLimitContinuationOfRunId &&
projection.thread.snoozedUntil != null &&
DateTime.toEpochMillis(projection.thread.snoozedUntil) > DateTime.toEpochMillis(now)
((run?.id === recovery.runId &&
UsageLimitRecovery.dueMs(
Date.parse(recovery.resetAt),
run.completedAt ?? run.requestedAt,
) > DateTime.toEpochMillis(now)) ||
(projection.thread.snoozedUntil != null &&
DateTime.toEpochMillis(projection.thread.snoozedUntil) >
DateTime.toEpochMillis(now)))
? { limitRecovery: { ...recovery, requestId: command.commandId } }
: {}),
},
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -5922,33 +5922,38 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
(row) => row.id === threadId,
),
);
assert.strictEqual(yield* store.getLimitRecoveryWakeAt(now), DateTime.toEpochMillis(reset));
assert.isNull(yield* store.getLimitRecoveryWakeAt(reset));
const resumeAt = DateTime.toEpochMillis(DateTime.add(reset, { minutes: 2 }));
assert.strictEqual(yield* store.getLimitRecoveryWakeAt(now), resumeAt);
assert.strictEqual(yield* store.getLimitRecoveryWakeAt(reset), resumeAt);
assert.isNull(yield* store.getLimitRecoveryWakeAt(DateTime.add(reset, { minutes: 2 })));
const due = (yield* store.getLimitRecoveryCandidates({
...recoveryOptions,
now: reset,
now: DateTime.add( reset, { minutes: 2 }) ,
})).find((row) => row.id === threadId)!;
assert.deepEqual(due.limitRecovery, recovery);
yield* sql`INSERT INTO orchestration_v2_projection_runtime_requests
(runtime_request_id, thread_id, node_id, kind, status, created_at, payload_json)
VALUES ('limit-shell:pending-request', ${threadId}, ${original.rootNodeId}, 'approval', 'pending', ${DateTime.formatIso(now)}, '{}')`;
assert.isUndefined(
(yield* store.getLimitRecoveryCandidates({ ...recoveryOptions, now: reset })).find(
(row) => row.id === threadId,
),
(yield* store.getLimitRecoveryCandidates({
...recoveryOptions,
now: DateTime.add(reset, { minutes: 2 }),
})).find((row) => row.id === threadId),
);
yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests WHERE runtime_request_id = 'limit-shell:pending-request'`;
yield* sql`UPDATE orchestration_v2_projection_threads
SET payload_json = json_set(payload_json, '$.snoozedUntil', ${DateTime.formatIso(DateTime.add(reset, { minutes: 1 }))})
SET payload_json = json_set(payload_json, '$.snoozedUntil', ${DateTime.formatIso(DateTime.add(reset, { minutes: 3 }))})
WHERE thread_id = ${threadId}`;
assert.isUndefined(
(yield* store.getLimitRecoveryCandidates({ ...recoveryOptions, now: reset })).find(
(row) => row.id === threadId,
),
(yield* store.getLimitRecoveryCandidates({
...recoveryOptions,
now: DateTime.add(reset, { minutes: 2 }),
})).find((row) => row.id === threadId),
);
assert.strictEqual(yield* store.getLimitRecoveryWakeAt(reset), resumeAt);
assert.strictEqual(
yield* store.getLimitRecoveryWakeAt(reset),
DateTime.toEpochMillis(DateTime.add(reset, { minutes: 1 })),
yield* store.getLimitRecoveryWakeAt(DateTime.add( reset, { minutes: 2 }) ),
DateTime.toEpochMillis(DateTime.add(reset, { minutes: 3 })),
);
yield* sql`UPDATE orchestration_v2_projection_threads
SET payload_json = json_set(payload_json, '$.snoozedUntil', NULL, '$.limitRecovery.autoResume', json('false'))
Expand All
@@ -5957,7 +5962,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
assert.isUndefined(
(yield* store.getLimitRecoveryCandidates({
...recoveryOptions,
now: reset,
now: DateTime.add( reset, { minutes: 2 }) ,
autoResume: true,
})).find((row) => row.id === threadId),
);
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2,6 +2,7 @@ import type { ProjectThreadAwarenessV2Input } from "@t3tools/shared/agentAwarene
import { pendingGuestMessageCount } from "@t3tools/contracts";
import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts";
import { projectTurnItemForWire } from "./WireProjection.ts";
import * as UsageLimitRecovery from "./UsageLimitRecovery.ts";
import * as Stream from "effect/Stream";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import { makeThreadFind } from "./ThreadFind.ts";
Expand Down
Expand Up
@@ -185,7 +186,7 @@ export type ProjectionLimitRecoveryCandidate = Pick<
| "updatedAt"
| "limitRecovery"
| "snoozedUntil"
>;
> & { readonly recoveryCompletedMs?: number | undefined } ;
export type ProjectionThreadPullRequests = Pick<
OrchestrationV2AppThread,
Expand Down
Expand Up
@@ -3962,10 +3963,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
readonly payload_json: string;
readonly run_id: string;
readonly completed_at: string | null;
readonly recovery_completed_at: string | null;
readonly failure_payload_json: string;
readonly last_error: string | null;
}>`
SELECT t.payload_json, r.run_id, r.completed_at,
COALESCE(armed.completed_at, json_extract(armed.payload_json, '$.requestedAt')) AS recovery_completed_at,
item.payload_json AS failure_payload_json,
(
SELECT json_extract(session.payload_json, '$.lastError')
Expand Down
Expand Up
@@ -4000,6 +4003,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
ORDER BY error.updated_at DESC, error.ordinal DESC, error.turn_item_id DESC
LIMIT 1
)
LEFT JOIN orchestration_v2_projection_runs armed
ON armed.thread_id = t.thread_id AND armed.run_id IS json_extract(t.payload_json, '$.limitRecovery.runId')
WHERE t.deleted_at IS NULL
-- The sweep runs every scheduler tick. Without this list the latest-run
-- lookup above sorts every run of every thread, tens of milliseconds
Expand All
@@ -4013,13 +4018,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
AND json_extract(t.payload_json, '$.settledOverride') IS NOT 'settled'
AND json_extract(item.payload_json, '$.failure.class') = 'usage_limit'
AND json_extract(item.payload_json, '$.failure.resetAt') IS NOT NULL
AND julianday(json_extract(item.payload_json, '$.failure.resetAt')) > julianday(COALESCE(r.completed_at, json_extract(t.payload_json, '$.updatedAt')))
AND (
(
json_extract(t.payload_json, '$.limitRecovery.runId') IS r.run_id
AND json_extract(t.payload_json, '$.limitRecovery.resetAt') IS json_extract(item.payload_json, '$.failure.resetAt')
AND json_extract(t.payload_json, '$.limitRecovery.autoResume') = 1
AND julianday(json_extract(item.payload_json, '$.failure.resetAt')) <= julianday(${DateTime.formatIso(options.now)})
AND MAX( julianday(json_extract(item.payload_json, '$.failure.resetAt')), julianday(COALESCE(r.completed_at, json_extract(t.payload_json, '$.updatedAt')))) <= julianday(${DateTime.formatIso(options.now)}) - ${UsageLimitRecovery.RESUME_MARGIN_MS} / 86400000.0
AND (
json_extract(t.payload_json, '$.snoozedUntil') IS NULL
OR julianday(json_extract(t.payload_json, '$.snoozedUntil')) <= julianday(${DateTime.formatIso(options.now)})
Expand All
@@ -4030,6 +4034,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
json_extract(t.payload_json, '$.limitRecovery.runId') IS NOT r.run_id
OR json_extract(t.payload_json, '$.limitRecovery.resetAt') IS NOT json_extract(item.payload_json, '$.failure.resetAt')
)
AND (
julianday(json_extract(item.payload_json, '$.failure.resetAt')) > julianday(COALESCE(r.completed_at, json_extract(t.payload_json, '$.updatedAt')))
OR (json_extract(t.payload_json, '$.limitRecovery.autoResume') = 1
AND json_extract(t.payload_json, '$.limitRecovery.resetAt') IS json_extract(item.payload_json, '$.failure.resetAt')
AND julianday(json_extract(item.payload_json, '$.failure.resetAt')) > julianday(COALESCE(armed.completed_at, json_extract(armed.payload_json, '$.requestedAt'))))
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
AND (
${booleanInt(options.autoResume)}
OR (${booleanInt(options.snooze)} AND julianday(json_extract(item.payload_json, '$.failure.resetAt')) > julianday(${DateTime.formatIso(options.now)}))
Expand Down
Expand Up
@@ -4066,6 +4076,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
latestRunId: RunId.make(row.run_id),
latestRunCompletedAt:
row.completed_at === null ? null : DateTime.makeUnsafe(row.completed_at),
...(row.recovery_completed_at === null
? {}
: { recoveryCompletedMs: Date.parse(row.recovery_completed_at) }),
updatedAt: thread.updatedAt,
archivedAt: thread.archivedAt,
settledOverride: thread.settledOverride,
Expand All
@@ -4087,16 +4100,22 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
readonly snooze_ms: number | null;
}>`
SELECT
MIN(CASE WHEN julianday(reset_at) > julianday(${nowIso})
THEN (julianday(reset_at) - 2440587.5) * 86400000 END) AS reset_ms,
MIN(CASE WHEN due_day > julianday(${nowIso})
THEN (due_day - 2440587.5) * 86400000 END) AS reset_ms,
MIN(CASE WHEN julianday(snoozed_until) > julianday(${nowIso})
THEN (julianday(snoozed_until) - 2440587.5) * 86400000 END) AS snooze_ms
FROM (
SELECT json_extract(payload_json, '$.limitRecovery.resetAt') AS reset_at,
json_extract(payload_json, '$.snoozedUntil') AS snoozed_until
FROM orchestration_v2_projection_threads
WHERE deleted_at IS NULL
AND json_extract(payload_json, '$.limitRecovery.autoResume') = 1
-- Matches the candidate due time: later of reset and armed run end, plus the margin.
SELECT MAX(
julianday(json_extract(t.payload_json, '$.limitRecovery.resetAt')),
julianday(COALESCE(armed.completed_at, json_extract(t.payload_json, '$.updatedAt')))
) + ${UsageLimitRecovery.RESUME_MARGIN_MS} / 86400000.0 AS due_day,
json_extract(t.payload_json, '$.snoozedUntil') AS snoozed_until
FROM orchestration_v2_projection_threads t
LEFT JOIN orchestration_v2_projection_runs armed
ON armed.run_id IS json_extract(t.payload_json, '$.limitRecovery.runId')
WHERE t.deleted_at IS NULL
AND json_extract(t.payload_json, '$.limitRecovery.autoResume') = 1
)
`;
const wakes = [rows[0]?.reset_ms, rows[0]?.snooze_ms].filter(
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,32 @@
import type { OrchestrationV2LimitRecovery, OrchestrationV2Run, RunId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
// Claude can still refuse a turn just after its reported reset time.
export const RESUME_MARGIN_MS = 120_000;
export const dueMs = (resetMs: number, completedAt: DateTime.Utc): number =>
Math.max(resetMs, DateTime.toEpochMillis(completedAt)) + RESUME_MARGIN_MS;
export const recoveryRunCompletedMs = (projection: {
readonly runs: ReadonlyArray<OrchestrationV2Run>;
readonly thread: { readonly limitRecovery?: OrchestrationV2LimitRecovery | null | undefined };
}): number | undefined => {
const run = projection.runs.find((run) => run.id === projection.thread.limitRecovery?.runId);
return run ? DateTime.toEpochMillis(run.completedAt ?? run.requestedAt) : undefined;
};
// Claude can refuse again with the same, now past, reset. Allow one re-arm while the recovery
// still names a run that failed before that reset. A stopped arm cannot enable another retry.
export const staleResetAllowed = (thread: {
readonly limitRecovery?: OrchestrationV2LimitRecovery | null | undefined;
readonly latestRunId: RunId | null;
readonly usageLimitResetAt?: string | null | undefined;
readonly recoveryCompletedMs?: number | undefined;
}): boolean => {
const recovery = thread.limitRecovery;
if (!recovery?.autoResume || recovery.resetAt !== thread.usageLimitResetAt) return false;
return (
recovery.runId === thread.latestRunId ||
(thread.recoveryCompletedMs !== undefined &&
Date.parse(recovery.resetAt) > thread.recoveryCompletedMs)
);
};
Original file line number
Diff line number
Diff line change
Expand Up
@@ -11,6 +11,7 @@ import * as ServerSettings from "../serverSettings.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as Orchestrator from "./Orchestrator.ts";
import * as ThreadManagement from "./ThreadManagementService.ts";
import * as UsageLimitRecovery from "./UsageLimitRecovery.ts";
const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000;
Expand All
@@ -34,7 +35,8 @@ export function limitRecoveryCommand(
// An already-expired window reported with a fresh failure cannot start a retry loop.
if (
!Number.isFinite(resetMs) ||
resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt)
(resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt) &&
!UsageLimitRecovery.staleResetAllowed(thread))
)
return null;
const identity = `${thread.id}:${thread.latestRunId}:${resetMs}`;
Expand All
@@ -56,7 +58,7 @@ export function limitRecoveryCommand(
}
if (
!recovery.autoResume ||
resetMs > nowMs ||
UsageLimitRecovery.dueMs( resetMs, thread.latestRunCompletedAt ?? thread.updatedAt) > nowMs ||
(thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs)
)
return null;
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.