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 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 18:02:52 +07:00
parent 710782b786
commit 2723f9b998
8 changed files with 111 additions and 11 deletions

View File

@@ -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).

View File

@@ -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;

View File

@@ -82,6 +82,7 @@ export function rubricIds(markdown: string): Set<string> {
// 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);

View File

@@ -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<number> {
async drain(now = Date.now()): Promise<number> {
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<boolean> {
async process(ev: QueuedEvent, now = Date.now()): Promise<boolean> {
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;

View File

@@ -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');
}

View File

@@ -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<ReviewOutcome> {
@@ -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<TurnResult> {
const turn = await s.client.runTurn(s.threadId, `Follow-up question about this MR (untrusted, from the MR thread):\n<question>${question}</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>${question}</question>`, null, s.reviewer.effort));
s.usage = turn.usage ?? s.usage;
return turn;
}

View File

@@ -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.']);
});

View File

@@ -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);
});