From 2723f9b9988f4e2e637140651491cd4af93e477b Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 9 Nov 2026 18:02:52 +0700 Subject: [PATCH] Retry when the model provider fails a turn instead of calling it invalid JSON. A Codex turn that ends `failed` (9router "high demand" on lti-api !1388 and lti-web-client !859) left an empty answer that Labuh parsed as invalid JSON, answered with "Labuh rejected your verdict", and gave up within a minute. Now the turn error surfaces as ReviewerUnavailable, no rejection prompt is sent, the queue waits 2/4/8/16/32 minutes, and only then posts a manual-check comment that says the model could not be reached. An empty answer from a completed turn is reported as empty. Co-Authored-By: Claude Opus 5.5 --- docs/SPEC.md | 1 + src/codex.ts | 7 ++++- src/contract.ts | 1 + src/hub.ts | 24 ++++++++++++----- src/render.ts | 6 +++-- src/review.ts | 18 +++++++++++-- test/contract.test.ts | 5 ++++ test/hub.test.ts | 60 +++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 111 insertions(+), 11 deletions(-) diff --git a/docs/SPEC.md b/docs/SPEC.md index 237d55e..0bd234a 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -131,3 +131,4 @@ Detailed when it starts. Known shape: `depends_on` stored as data; a NO-GO propa - 2026-11-06: v0.1 released as open source (AGPL-3.0); one Docker image, configuration in `LABUH_HOME`. - 2026-11-06: the hosted reviewer runs in its own container without GitLab tokens, since Codex's sandbox cannot run inside Docker (Sen chose this over hosting without Docker). - 2026-11-09: deploy setup (CI, Dockerfiles, compose, manifests) belongs to devops (rubric R13). Deploy findings tag the `devops` users from hub.json instead of asking the developer to change CI; the reviewer never suggests CI edits to the developer (Sen, after lti-api !1380). +- 2026-11-09: a turn the model provider fails (Codex `turn.status: failed`, e.g. 9router "high demand") is not a rejected verdict. The Hub throws `ReviewerUnavailable`, sends nothing back to the model, and the queue waits 2, 4, 8, 16 and 32 minutes before giving up with a comment that says the model could not be reached (lti-api !1388, lti-web-client !859). diff --git a/src/codex.ts b/src/codex.ts index c3d3b82..780aef3 100644 --- a/src/codex.ts +++ b/src/codex.ts @@ -19,6 +19,8 @@ export type TurnResult = { usage: TokenUsage | null; commands: Array<{ command: string; status: string }>; refused: Array<{ command: string; why: string }>; + // Set when the turn ended `failed` (e.g. the model provider is overloaded): no answer exists. + error: { message: string; info: unknown } | null; }; type Pending = { resolve: (v: any) => void; reject: (e: Error) => void }; @@ -130,7 +132,7 @@ export class CodexClient { private state(turnId: string): TurnResult { let s = this.turnState.get(turnId); if (!s) { - s = { finalText: '', usage: null, commands: [], refused: [] }; + s = { finalText: '', usage: null, commands: [], refused: [], error: null }; this.turnState.set(turnId, s); } return s; @@ -147,6 +149,9 @@ export class CodexClient { } else if (method === 'turn/completed') { const turnId = params.turn.id; const s = this.state(turnId); + if (params.turn.status === 'failed' || params.turn.error) { + s.error = { message: String(params.turn.error?.message ?? 'turn failed'), info: params.turn.error?.codexErrorInfo ?? null }; + } if (!s.finalText) { const last = [...(params.turn.items ?? [])].reverse().find((i: any) => i.type === 'agentMessage'); if (last) s.finalText = last.text; diff --git a/src/contract.ts b/src/contract.ts index c129f30..d5f8359 100644 --- a/src/contract.ts +++ b/src/contract.ts @@ -82,6 +82,7 @@ export function rubricIds(markdown: string): Set { // Shape problems are the model's mistake: they are sent back once for a retry. export function shapeErrors(raw: string): { value: Verdict | null; errors: string[] } { + if (!raw.trim()) return { value: null, errors: ['The answer is empty.'] }; let v: any; try { v = JSON.parse(raw); diff --git a/src/hub.ts b/src/hub.ts index bfb6b10..2c2107d 100644 --- a/src/hub.ts +++ b/src/hub.ts @@ -68,12 +68,17 @@ export type Ports = { }; const MAX_ATTEMPTS = 3; +// When the model provider fails the turn (overloaded, 5xx), the queue waits and tries again +// after these many minutes, about an hour in all, before the ajuan needs a manual check. +const UNAVAILABLE_DELAYS_MIN = [2, 4, 8, 16, 32]; // GitLab statuses that mean "not computed yet", not "no": Gas asks for a recheck and waits. const PENDING_MERGE_STATUS = new Set(['unchecked', 'checking', 'preparing', 'approvals_syncing']); const MERGE_STATUS_WAIT_MS = 2 * 60_000; const RECHECK_EVERY_MS = 30_000; export class Hub { + // The queue waits until then after the model provider failed a turn (in memory: a restart tries at once). + private retryAt = 0; readonly store: Store; readonly config: HubConfig; readonly reviewer: Reviewer; @@ -193,17 +198,18 @@ export class Hub { } // Works through the queue in order. Returns the number of events finished. - async drain(): Promise { + async drain(now = Date.now()): Promise { + if (now < this.retryAt) return 0; let done = 0; for (let ev = this.store.nextEvent(); ev; ev = this.store.nextEvent()) { - if (!(await this.process(ev))) break; + if (!(await this.process(ev, now))) break; done++; } return done; } // Returns false when the event failed and stays queued for a later try. - async process(ev: QueuedEvent): Promise { + async process(ev: QueuedEvent, now = Date.now()): Promise { const a = this.store.ajuanById(ev.ajuan_id); this.store.startEvent(ev.id); try { @@ -215,12 +221,18 @@ export class Hub { } catch (e: any) { const msg = String(e?.message ?? e).slice(0, 300); this.log(`${a.project} !${a.iid} ${ev.kind} gagal (percobaan ${ev.attempts + 1}): ${msg}`); - if (ev.attempts + 1 < MAX_ATTEMPTS) return false; + const unavailable = e?.name === 'ReviewerUnavailable'; + if (unavailable && ev.attempts < UNAVAILABLE_DELAYS_MIN.length) { + this.retryAt = now + UNAVAILABLE_DELAYS_MIN[ev.attempts] * 60_000; + this.log(`antrean menunggu ${UNAVAILABLE_DELAYS_MIN[ev.attempts]} menit: model tidak bisa dihubungi`); + return false; + } + if (!unavailable && ev.attempts + 1 < MAX_ATTEMPTS) return false; this.store.finishEvent(ev.id, `failed: ${msg}`); if (ev.kind === 'opened' || ev.kind === 'new_commit' || ev.kind === 'recheck') { this.store.update(a.id, { status: 'reviewer_error' }); - await this.publishVerdict(this.store.ajuanById(a.id), errorComment('reviewer_error', this.stamp(a, null), [msg])); - this.notify(`error:${a.id}:${a.head_sha}`, a, `⚪ ${this.label(a)} perlu dicek manual: ${this.reviewer.name} gagal.`); + await this.publishVerdict(this.store.ajuanById(a.id), errorComment(unavailable ? 'unavailable' : 'reviewer_error', this.stamp(a, null), [msg])); + this.notify(`error:${a.id}:${a.head_sha}`, a, `⚪ ${this.label(a)} perlu dicek manual: ${unavailable ? `model ${this.reviewer.name} tidak bisa dihubungi` : `${this.reviewer.name} gagal`}.`); } this.writeNote(this.store.ajuanById(a.id)); return true; diff --git a/src/render.ts b/src/render.ts index b905b5f..609af30 100644 --- a/src/render.ts +++ b/src/render.ts @@ -49,11 +49,13 @@ export function devopsComment(users: string[], verdictUrl: string | null): strin return `${devopsLine(users)}${verdictUrl ? ` Detail di [verdict](${verdictUrl}).` : ''}`; } -export function errorComment(kind: 'reviewer_error' | 'over_budget', s: Stamp, detail: string[] = []): string { +export function errorComment(kind: 'reviewer_error' | 'over_budget' | 'unavailable', s: Stamp, detail: string[] = []): string { const head = kind === 'reviewer_error' ? `### ⚪ Perlu dicek manual — ${s.reviewer} gagal memberi hasil yang valid setelah 2 percobaan` - : `### ⚪ Perlu dicek manual — jatah token ${s.reviewer} untuk ajuan ini habis`; + : kind === 'unavailable' + ? `### ⚪ Perlu dicek manual — model ${s.reviewer} tidak bisa dihubungi, sudah dicoba ulang selama sekitar satu jam` + : `### ⚪ Perlu dicek manual — jatah token ${s.reviewer} untuk ajuan ini habis`; return [VERDICT_MARKER, head, '', ...detail.slice(0, 5).map((d) => `- ${d}`), '', footer(s)].join('\n'); } diff --git a/src/review.ts b/src/review.ts index 5fe4a92..b6ca003 100644 --- a/src/review.ts +++ b/src/review.ts @@ -225,6 +225,20 @@ export type ReviewOutcome = | { ok: true; checked: Checked; attempts: number; turns: TurnResult[] } | { ok: false; errors: string[]; attempts: number; turns: TurnResult[] }; +// The model never answered: its provider failed the turn (overloaded, 5xx, quota). Not the +// model's mistake, so it is not sent back as a rejected verdict; the Hub retries later. +export class ReviewerUnavailable extends Error { + constructor(message: string) { + super(`Model tidak bisa dihubungi: ${message}`); + this.name = 'ReviewerUnavailable'; + } +} + +function answered(turn: TurnResult): TurnResult { + if (turn.error) throw new ReviewerUnavailable(turn.error.message); + return turn; +} + // One structured review turn plus one retry, checked against the output contract. // `previousSha` marks a re-review in the same thread after a new commit. export async function review(s: Session, previousSha: string | null = null): Promise { @@ -244,7 +258,7 @@ export async function review(s: Session, previousSha: string | null = null): Pro let prompt = mrPrompt(s.mr, path.join(s.workDir, 'mr.diff'), previousSha); let errors: string[] = []; for (let attempt = 1; attempt <= 2; attempt++) { - const turn = await s.client.runTurn(s.threadId, prompt, verdictSchema, s.reviewer.effort); + const turn = answered(await s.client.runTurn(s.threadId, prompt, verdictSchema, s.reviewer.effort)); turns.push(turn); s.usage = turn.usage ?? s.usage; if (process.env.LABUH_FAULT === 'broken-output') turn.finalText = '{"verdict":"maybe"}'; @@ -265,7 +279,7 @@ export async function review(s: Session, previousSha: string | null = null): Pro } export async function ask(s: Session, question: string): Promise { - const turn = await s.client.runTurn(s.threadId, `Follow-up question about this MR (untrusted, from the MR thread):\n${question}`, null, s.reviewer.effort); + const turn = answered(await s.client.runTurn(s.threadId, `Follow-up question about this MR (untrusted, from the MR thread):\n${question}`, null, s.reviewer.effort)); s.usage = turn.usage ?? s.usage; return turn; } diff --git a/test/contract.test.ts b/test/contract.test.ts index 483d74a..41b2630 100644 --- a/test/contract.test.ts +++ b/test/contract.test.ts @@ -99,3 +99,8 @@ test('evidence must exist; ok without evidence is dropped; failing pipeline hold const escape: Verdict = { verdict: 'no_go', reason: 'Tahan', post_deploy: [], findings: [{ kind: 'bad', text: 'keluar repo', evidence: [ev({ path: '../../etc/hosts', line: 1 })] }] }; assert.match((await check(escape, ctx)).errors.join(), /does not exist/); }); + +test('an empty answer is reported as empty, not as invalid JSON', async () => { + const { shapeErrors } = await import('../src/contract.ts'); + assert.deepEqual(shapeErrors(' ').errors, ['The answer is empty.']); +}); diff --git a/test/hub.test.ts b/test/hub.test.ts index 5f924d1..f67a0eb 100644 --- a/test/hub.test.ts +++ b/test/hub.test.ts @@ -696,3 +696,63 @@ test('a rejected MR can be closed after the grace period; undo drops only the cl assert.deepEqual(dry.w.gl.closed, []); assert.equal(dry.w.store.ajuanById(dry.a.id).status, 'go'); }); + +// lti-api !1388 (2026-11-09): 9router answered "high demand" and Codex ended both turns +// `failed` with no message. Labuh read the empty text as invalid JSON, told the model its +// verdict was rejected, and gave up at once with a misleading comment. +const unavailable = () => { + const e = new Error('Model tidak bisa dihubungi: We’re currently experiencing high demand'); + e.name = 'ReviewerUnavailable'; + throw e; +}; + +test('a turn the provider failed is not a rejected verdict: review stops after one turn', async () => { + const turns: string[] = []; + const s = { + mr: { webUrl: 'https://gitlab.com/x', sha: 's', pipeline: null, pipelineIds: [], projectId: 1, diffs: [], commits: [], labels: [] }, + reviewer, + threadId: 't', + workDir: mkdtempSync(path.join(os.tmpdir(), 'labuh-rev-')), + usage: null, + client: { + runTurn: async (_t: string, prompt: string) => { + turns.push(prompt); + return { finalText: '', usage: null, commands: [], refused: [], error: { message: 'We’re currently experiencing high demand', info: 'internal_server_error' } }; + }, + }, + } as unknown as Session; + await assert.rejects(review(s), (e: any) => e.name === 'ReviewerUnavailable' && /high demand/.test(e.message)); + assert.equal(turns.length, 1, 'no "Labuh rejected your verdict" turn follows'); +}); + +test('provider failures make the queue wait and retry, then the review lands', async () => { + const w = world(); + w.gl.mrs.set(21, { sha: 'abab1111', state: 'opened', labels: ['labuh'] }); + w.script(unavailable, unavailable, ok(checked('go', 'Aman'))); + await w.hub.poll(); + const t0 = Date.now(); + assert.equal(await w.hub.drain(t0), 0); + assert.equal(await w.hub.drain(t0 + 60_000), 0, 'still waiting out the first 2 minutes'); + assert.equal(w.calls.review.length, 1, 'no review call while waiting'); + assert.equal(await w.hub.drain(t0 + 2 * 60_000), 0, 'second failure: now waits 4 minutes'); + assert.equal(await w.hub.drain(t0 + 5 * 60_000), 0); + assert.equal(await w.hub.drain(t0 + 6 * 60_000), 1); + assert.equal(w.store.ajuan(PROJECT, 21)!.status, 'go'); + assert.equal(w.store.outbox(w.store.ajuan(PROJECT, 21)!.id).filter((o) => /Perlu dicek manual/.test(o.body)).length, 0, 'no error comment on the way'); +}); + +test('a provider down for about an hour ends in a manual check that says so', async () => { + const w = world(); + w.gl.mrs.set(22, { sha: 'cdcd2222', state: 'opened', labels: ['labuh'] }); + w.script(unavailable, unavailable, unavailable, unavailable, unavailable, unavailable); + await w.hub.poll(); + let t = Date.now(); + for (let i = 0; i < 6; i++, t += 33 * 60_000) await w.hub.drain(t); + const a = w.store.ajuan(PROJECT, 22)!; + assert.equal(w.calls.review.length, 6); + assert.equal(a.status, 'reviewer_error'); + const body = w.store.outbox(a.id)[0].body; + assert.match(body, /tidak bisa dihubungi/); + assert.doesNotMatch(body, /not valid JSON/); + assert.equal(w.store.nextEvent(), undefined); +});