From 172e0d0f98aab329bc5b3a229967bf1b39a34b59 Mon Sep 17 00:00:00 2001 From: Denis Andreyev Date: Sun, 8 Nov 2026 11:58:20 +0500 Subject: [PATCH] Recover failed evaluations and preserve successful results --- apps/api/src/db/index.ts | 3 + apps/api/src/db/schema.ts | 2 + apps/api/src/routes/evaluations.ts | 16 +- apps/api/src/services/evaluation/anthropic.ts | 16 +- apps/api/src/services/evaluation/evaluator.ts | 27 ++- apps/api/src/services/evaluation/jobs.ts | 200 +++++++++++------- apps/api/src/services/evaluation/prompts.ts | 2 +- apps/api/src/services/evaluation/provider.ts | 13 +- .../evaluation/semantic/consultation.ts | 6 +- apps/api/src/services/evaluations.ts | 4 +- apps/api/src/services/review.ts | 2 +- apps/api/src/services/work.ts | 2 +- apps/api/test/evaluator.test.ts | 8 +- apps/api/test/migration.test.ts | 4 + apps/api/test/recovery.test.ts | 85 ++++++++ apps/api/test/semantic-facts.test.ts | 10 + apps/api/test/verification.test.ts | 2 +- apps/web/src/App.tsx | 33 ++- apps/web/src/api/MockCqaApi.ts | 8 +- apps/web/src/features/DialogsPage.tsx | 16 +- apps/web/src/features/EvaluationPanel.tsx | 15 +- apps/web/src/features/StatsPage.tsx | 2 +- apps/web/src/lib/analytics.ts | 5 +- apps/web/src/lib/stats.ts | 6 +- apps/web/test/recovery.test.tsx | 30 +++ docs/ARCHITECTURE.md | 9 + docs/RUNBOOK.md | 7 + .../plans/2026-11-08-evaluation-recovery.md | 13 ++ packages/contracts/src/api.ts | 7 +- packages/contracts/src/domain.ts | 6 + .../contracts/src/evaluation-selection.ts | 14 ++ packages/contracts/src/index.ts | 1 + .../test/evaluation-selection.test.ts | 13 ++ 33 files changed, 452 insertions(+), 135 deletions(-) create mode 100644 apps/api/test/recovery.test.ts create mode 100644 apps/web/test/recovery.test.tsx create mode 100644 docs/superpowers/plans/2026-11-08-evaluation-recovery.md create mode 100644 packages/contracts/src/evaluation-selection.ts create mode 100644 packages/contracts/test/evaluation-selection.test.ts diff --git a/apps/api/src/db/index.ts b/apps/api/src/db/index.ts index 2fcc51b..44d0854 100644 --- a/apps/api/src/db/index.ts +++ b/apps/api/src/db/index.ts @@ -130,6 +130,9 @@ export function openDb(path: string) { if (!columns('appeals').some((c) => c.name === 'created_by')) sqlite.exec('ALTER TABLE appeals ADD COLUMN created_by TEXT'); if (!columns('appeals').some((c) => c.name === 'decided_by')) sqlite.exec('ALTER TABLE appeals ADD COLUMN decided_by TEXT'); if (!columns('reviews').some((c) => c.name === 'by_id')) sqlite.exec('ALTER TABLE reviews ADD COLUMN by_id TEXT'); + if (!columns('evaluations').some((c) => c.name === 'diagnostics')) sqlite.exec('ALTER TABLE evaluations ADD COLUMN diagnostics TEXT'); + // Historical jobs keep their original single-attempt budget; new jobs explicitly opt into retries. + if (!columns('jobs').some((c) => c.name === 'max_attempts')) sqlite.exec('ALTER TABLE jobs ADD COLUMN max_attempts INTEGER NOT NULL DEFAULT 1'); return drizzle(sqlite, { schema }); } diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index c01be42..26d8f35 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -40,6 +40,7 @@ export const evaluations = sqliteTable('evaluations', { error: text('error'), cacheContext: text('cache_context'), decisionFacts: text('decision_facts', { mode: 'json' }), + diagnostics: text('diagnostics', { mode: 'json' }), createdAt: text('created_at').notNull(), }); @@ -66,6 +67,7 @@ export const jobs = sqliteTable('jobs', { id: text('id').primaryKey(), checklistVersionId: text('checklist_version_id').notNull(), force: integer('force', { mode: 'boolean' }).notNull().default(false), + maxAttempts: integer('max_attempts').notNull().default(1), conversationIds: text('conversation_ids', { mode: 'json' }).$type().notNull(), evaluationIds: text('evaluation_ids', { mode: 'json' }).$type().notNull(), status: text('status').notNull(), diff --git a/apps/api/src/routes/evaluations.ts b/apps/api/src/routes/evaluations.ts index 3430de5..75cd3f5 100644 --- a/apps/api/src/routes/evaluations.ts +++ b/apps/api/src/routes/evaluations.ts @@ -30,6 +30,11 @@ export function evaluationRoutes(app: FastifyInstance, db: Db, runner: JobRunner if (denied(req, reply, 'evaluate')) return; const body = StartEvaluationInputSchema.safeParse(req.body); if (!body.success) return reply.code(400).send({ error: 'body must be { conversationIds: string[], checklistVersionId: string }' }); + const actor = actorOf(req); + if (scopeOf(db, actor) !== null) { + const visible = new Set(listConversationViews(db, {}, actor).map(c => c.id)); + if (body.data.conversationIds.some(id => !visible.has(id))) return reply.code(404).send({ error: 'conversations not found' }); + } try { const job = runner.start(body.data); logEvent(db, actorOf(req), { type: 'evaluation.started', summary: `Запущена оценка диалогов: ${body.data.conversationIds.length}`, data: { jobId: job.id, count: body.data.conversationIds.length, checklistVersionId: body.data.checklistVersionId, force: !!(body.data.force || body.data.fresh) } }); @@ -40,7 +45,16 @@ export function evaluationRoutes(app: FastifyInstance, db: Db, runner: JobRunner } }); - app.get<{ Params: { id: string } }>('/api/jobs/:id', async (req, reply) => runner.getJob(req.params.id) ?? reply.code(404).send({ error: 'job not found' })); + app.get<{ Params: { id: string } }>('/api/jobs/:id', async (req, reply) => { + const ids = runner.conversationIds(req.params.id); + if (!ids) return reply.code(404).send({ error: 'job not found' }); + const actor = actorOf(req); + if (scopeOf(db, actor) !== null) { + const visible = new Set(listConversationViews(db, {}, actor).map(c => c.id)); + if (ids.some(id => !visible.has(id))) return reply.code(404).send({ error: 'job not found' }); + } + return runner.getJob(req.params.id); + }); app.get<{ Params: { id: string } }>('/api/evaluations/:id', async (req, reply) => (evaluationVisible(db, req.params.id, actorOf(req)) && getEvaluation(db, req.params.id)) || reply.code(404).send({ error: 'evaluation not found' })); diff --git a/apps/api/src/services/evaluation/anthropic.ts b/apps/api/src/services/evaluation/anthropic.ts index 07aea7a..4027c9b 100644 --- a/apps/api/src/services/evaluation/anthropic.ts +++ b/apps/api/src/services/evaluation/anthropic.ts @@ -1,4 +1,4 @@ -import { ProviderError, type LlmProvider, type ProviderRequest, type ProviderResponse } from './provider.js'; +import { addUsage, emptyUsage, ProviderError, type LlmProvider, type ProviderRequest, type ProviderResponse } from './provider.js'; export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'; export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max']; @@ -46,6 +46,7 @@ export class AnthropicProvider implements LlmProvider { const retries = this.o.retries ?? 3; const started = Date.now(); let lastStatus = 0; + const usage = emptyUsage(); // A reply without the tool call is also retried once: with `auto` the model may answer in prose. let missingTool = 0; for (let attempt = 0; attempt <= retries; attempt++) { @@ -68,17 +69,18 @@ export class AnthropicProvider implements LlmProvider { lastStatus = res.status; if (res.ok) { const body = (await res.json()) as Body; - if (body.stop_reason === 'refusal') throw new ProviderError(`model refused (${body.stop_details?.category ?? 'no category'})`); - if (body.stop_reason === 'max_tokens') throw new ProviderError('model output was cut off at max_tokens'); + const u = body.usage; + addUsage(usage, u ? { inputTokens: u.input_tokens, outputTokens: u.output_tokens, cacheReadTokens: u.cache_read_input_tokens, cacheWriteTokens: u.cache_creation_input_tokens } : undefined); + if (body.stop_reason === 'refusal') throw new ProviderError(`model refused (${body.stop_details?.category ?? 'no category'})`, usage, false); + if (body.stop_reason === 'max_tokens') throw new ProviderError('model output was cut off at max_tokens', usage); const tool = body.content?.find((c) => c.type === 'tool_use'); if (!tool) { - if (++missingTool > 1) throw new ProviderError('model returned no tool call'); + if (++missingTool > 1) throw new ProviderError('model returned no tool call', usage); continue; } - const u = body.usage; return { output: tool.input, - usage: u ? { inputTokens: u.input_tokens, outputTokens: u.output_tokens, cacheReadTokens: u.cache_read_input_tokens, cacheWriteTokens: u.cache_creation_input_tokens } : undefined, + usage, latencyMs: Date.now() - started, }; } @@ -88,6 +90,6 @@ export class AnthropicProvider implements LlmProvider { lastStatus = 0; // network/timeout: retry; details dropped on purpose } } - throw new ProviderError(`provider request failed (status ${lastStatus || 'network error'})`); + throw new ProviderError(`provider request failed (status ${lastStatus || 'network error'})`, usage, lastStatus === 0 || lastStatus === 429 || lastStatus >= 500); } } diff --git a/apps/api/src/services/evaluation/evaluator.ts b/apps/api/src/services/evaluation/evaluator.ts index 9c66bf6..7d8961c 100644 --- a/apps/api/src/services/evaluation/evaluator.ts +++ b/apps/api/src/services/evaluation/evaluator.ts @@ -7,9 +7,11 @@ import { PROMPT_VERSION, systemPromptFor } from './prompts.js'; import { originalCriterion } from './rubric.js'; import { ORIGINAL_SEMANTIC_HELPERS, type DecisionFacts } from './semantic/index.js'; import { buildOutputSchema } from './output-schema.js'; -import type { LlmProvider } from './provider.js'; +import { addUsage, ProviderError, type LlmProvider } from './provider.js'; -export class EvaluationFailure extends Error {} +export class EvaluationFailure extends Error { + constructor(message: string, public readonly provenance?: Provenance, public readonly decisionFacts?: DecisionFacts, public readonly diagnostics?: NonNullable) { super(message); } +} export { IDENTITY_VERIFIED_PATTERNS, deriveFacts as deriveContext } from './facts.js'; @@ -181,6 +183,7 @@ export type EvaluatorResult = { total: number | null; seriousViolation: boolean; provenance: Provenance; + diagnostics: NonNullable; usage: { inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }; latencyMs: number; /** Criteria the model decided or helped decide in this run (empty when rules and reuse covered everything). */ @@ -195,6 +198,7 @@ export async function evaluateConversation(provider: LlmProvider | undefined, co const { decided, assisted, undecided } = planCriteria(conversation, checklist, reuse); const usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }; let latencyMs = 0; + const calls: NonNullable['calls'] = []; const started = performance.now(); const modelResults = new Map(); const decisionFacts = new Map(); @@ -216,13 +220,18 @@ export async function evaluateConversation(provider: LlmProvider | undefined, co let problems: string[] = []; let ok = false; for (let attempt = 1; attempt <= maxAttempts && !ok; attempt++) { - const res = await provider.complete({ system, user: buildUserPayload(conversation, subset, initialDecided, assisted, problems), outputSchema }); - usage.inputTokens += res.usage?.inputTokens ?? 0; - usage.outputTokens += res.usage?.outputTokens ?? 0; - usage.cacheReadTokens += res.usage?.cacheReadTokens ?? 0; - usage.cacheWriteTokens += res.usage?.cacheWriteTokens ?? 0; + let res; + try { + res = await provider.complete({ system, user: buildUserPayload(conversation, subset, initialDecided, assisted, problems), outputSchema }); + } catch (e) { + if (e instanceof ProviderError) addUsage(usage, e.usage); + calls.push({ criteria: [...criteria, ...assisted.map(a => a.criterion)].map(c => c.id), attempt, problems: [e instanceof Error ? e.message : 'provider failed'] }); + throw e; + } + addUsage(usage, res.usage); const v = validateModelOutput(res.output, conversation, { ...checklist, criteria }); const a = validateAssisted(res.output, conversation, assisted); + calls.push({ criteria: [...criteria, ...assisted.map(a => a.criterion)].map(c => c.id), attempt, problems: [...v.problems, ...a.problems] }); if (v.results && a.problems.length === 0) { for (const r of v.results) { const { reusedFrom: _drop, ...clean } = r; @@ -240,12 +249,12 @@ export async function evaluateConversation(provider: LlmProvider | undefined, co if (!ok) throw new EvaluationFailure(`model output failed validation: ${problems.slice(0, 5).join('; ')}`); })); const failed = completed.find((r): r is PromiseRejectedResult => r.status === 'rejected'); - if (failed) throw failed.reason; + if (failed) throw new EvaluationFailure(failed.reason instanceof Error ? failed.reason.message : 'evaluation failed', { provider: provider.name, model: provider.model, promptVersion: PROMPT_VERSION, ...(provider.effort ? { effort: provider.effort } : {}), usage, latencyMs: Math.round(performance.now() - started) }, Object.fromEntries(decisionFacts), { calls, retryable: !(failed.reason instanceof ProviderError) || failed.reason.retryable }); latencyMs = Math.round(performance.now() - started); provenance = { provider: provider.name, model: provider.model, promptVersion: PROMPT_VERSION, ...(provider.effort ? { effort: provider.effort } : {}), usage, latencyMs }; } const results = checklist.criteria.map((c) => decided.get(c.id) ?? modelResults.get(c.id)!); const { total, seriousViolation } = scoreEvaluation(checklist, results); - return { results, decisionFacts: Object.fromEntries(decisionFacts), total, seriousViolation, provenance, usage, latencyMs, modelCriteria: [...modelResults.keys(), ...assisted.map((x) => x.criterion.id)] }; + return { results, decisionFacts: Object.fromEntries(decisionFacts), total, seriousViolation, provenance, diagnostics: { calls }, usage, latencyMs, modelCriteria: [...modelResults.keys(), ...assisted.map((x) => x.criterion.id)] }; } diff --git a/apps/api/src/services/evaluation/jobs.ts b/apps/api/src/services/evaluation/jobs.ts index 45055f8..cd0d228 100644 --- a/apps/api/src/services/evaluation/jobs.ts +++ b/apps/api/src/services/evaluation/jobs.ts @@ -5,119 +5,157 @@ import type { Db } from '../../db/index.js'; import { evaluations, jobs } from '../../db/schema.js'; import { getChecklist } from '../checklists.js'; import { getConversation } from '../conversations.js'; +import { notifyCritical } from '../notifications.js'; import { insertEvaluation } from '../evaluations.js'; import type { DecisionFacts } from './semantic/index.js'; -import { evaluateConversation, planCriteria } from './evaluator.js'; +import { PROMPT_VERSION } from './prompts.js'; +import { EvaluationFailure, evaluateConversation, planCriteria } from './evaluator.js'; import { evaluationCacheContext, makeReuseLookup } from './reuse.js'; import type { LlmProvider } from './provider.js'; export class JobError extends Error { - constructor( - message: string, - public readonly status: 400 | 404 | 503, - ) { - super(message); - } + constructor(message: string, public readonly status: 400 | 404 | 409 | 503) { super(message); } } - type Log = { info: (o: object, m?: string) => void; error: (o: object, m?: string) => void }; +type JobRow = typeof jobs.$inferSelect; +type EvalRow = typeof evaluations.$inferSelect; -function toJob(row: typeof jobs.$inferSelect): Job { - return JobSchema.parse({ id: row.id, status: row.status, completed: row.completed, total: row.total, evaluationIds: row.evaluationIds }); +/** A conversation is terminal only after success or exhaustion. Attempt history stays append-only. */ +function outcomes(job: JobRow, recorded: EvalRow[]) { + const byConversation = new Map(); + // evaluationIds is the durable attempt order, independent of equal timestamps or random ids. + const byId = new Map(recorded.map(e => [e.id, e])); + for (const id of job.evaluationIds) { + const e = byId.get(id); + if (e) byConversation.set(e.conversationId, [...(byConversation.get(e.conversationId) ?? []), e]); + } + let succeeded = 0, failed = 0, retrying = 0; + for (const list of byConversation.values()) { + const e = list.at(-1)!; + if (e.status === 'completed') succeeded++; + else if (e.status === 'failed' && (list.length >= job.maxAttempts || (e.diagnostics as Evaluation['diagnostics'])?.retryable === false)) failed++; + else retrying++; + } + return { byConversation, succeeded, failed, retrying }; } -/** - * In-process batch runner. State lives in SQLite, so after a restart `resume()` continues only the - * conversations that have no recorded evaluation yet; completed work is never recomputed. - */ export class JobRunner { - private running = new Set>(); + private running = new Map>(); + constructor(private readonly db: Db, private readonly provider: LlmProvider | undefined, private readonly log: Log, private readonly concurrency = 3, private readonly options: { maxAttempts?: number; retryDelayMs?: number } = {}) {} - constructor( - private readonly db: Db, - private readonly provider: LlmProvider | undefined, - private readonly log: Log, - private readonly concurrency = 3, - ) {} + private recorded(job: JobRow) { + return job.evaluationIds.length ? this.db.select().from(evaluations).where(inArray(evaluations.id, job.evaluationIds)).all() : []; + } + conversationIds(id: string): string[] | undefined { return this.db.select().from(jobs).where(eq(jobs.id, id)).get()?.conversationIds; } start(input: StartEvaluationInput): Job { const checklist = getChecklist(this.db, input.checklistVersionId); if (!checklist) throw new JobError('checklist version not found', 404); - const ids = [...new Set(input.conversationIds)]; - const missing = ids.filter((id) => !getConversation(this.db, id)); - if (missing.length) throw new JobError(`conversations not found: ${missing.slice(0, 5).join(', ')}`, 404); - // A model is needed only if rules + reuse cannot settle every criterion (e.g. switching a criterion off needs none). - if (!this.provider) { - const needing = ids.filter((id) => ((pl) => pl.undecided.length + pl.assisted.length > 0)(planCriteria(getConversation(this.db, id)!, checklist, (input.force || input.fresh) ? undefined : makeReuseLookup(this.db, id, this.provider)))); - if (needing.length) throw new JobError(`no model provider configured (set ANTHROPIC_API_KEY); ${needing.length} conversation(s) have criteria that need a model`, 503); + let ids = [...new Set(input.conversationIds)]; + if (ids.some(id => !getConversation(this.db, id))) throw new JobError('conversations not found', 404); + if (input.retryFailedOnly) { + ids = ids.filter(id => this.db.select().from(evaluations).where(eq(evaluations.conversationId, id)).all() + .filter(e => e.checklistVersionId === checklist.id).sort((a,b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)).at(-1)?.status === 'failed'); + if (!ids.length) throw new JobError('no failed conversations on this checklist to retry', 409); } - - const row = { id: `job-${randomUUID()}`, checklistVersionId: input.checklistVersionId, conversationIds: ids, evaluationIds: [] as string[], force: (input.force || input.fresh) ?? false, status: 'running', total: ids.length, completed: 0, createdAt: new Date().toISOString() }; - this.db.insert(jobs).values(row).run(); - this.launch(row.id); - return toJob(row); + const force = !!(input.force || input.fresh || input.retryFailedOnly); + // Avoid overlapping paid work; exact repeats reattach to the durable active job. + for (const active of this.db.select().from(jobs).where(inArray(jobs.status, ['pending', 'running'])).all()) { + if (active.checklistVersionId !== checklist.id || !active.conversationIds.some(id => ids.includes(id))) continue; + if (active.force === force && active.conversationIds.length === ids.length && active.conversationIds.every(id => ids.includes(id))) return this.getJob(active.id)!; + throw new JobError('evaluation already running for these conversations', 409); + } + if (!this.provider && ids.some(id => { + const p = planCriteria(getConversation(this.db, id)!, checklist, force ? undefined : makeReuseLookup(this.db, id, this.provider)); + return p.undecided.length + p.assisted.length > 0; + })) throw new JobError('no model provider configured (set ANTHROPIC_API_KEY)', 503); + const row = { id: `job-${randomUUID()}`, checklistVersionId: checklist.id, conversationIds: ids, evaluationIds: [] as string[], force, maxAttempts: this.options.maxAttempts ?? 2, status: 'running', total: ids.length, completed: 0, createdAt: new Date().toISOString() }; + this.db.insert(jobs).values(row).run(); this.launch(row.id); + return this.getJob(row.id)!; } getJob(id: string): Job | undefined { const row = this.db.select().from(jobs).where(eq(jobs.id, id)).get(); - return row ? toJob(row) : undefined; - } - - /** Call once on boot. */ - resume(): void { - for (const j of this.db.select().from(jobs).where(inArray(jobs.status, ['pending', 'running'])).all()) this.launch(j.id); + if (!row) return; + const { succeeded, failed, retrying } = outcomes(row, this.recorded(row)); + return JobSchema.parse({ ...row, succeeded, failed, retrying }); } - - async idle(): Promise { - while (this.running.size) await Promise.all([...this.running]); - } - + resume(): void { for (const j of this.db.select().from(jobs).where(inArray(jobs.status, ['pending', 'running'])).all()) this.launch(j.id); } + async idle(): Promise { while (this.running.size) await Promise.all([...this.running.values()]); } private launch(jobId: string) { - const p = this.run(jobId) - .catch((e: unknown) => { - this.log.error({ jobId, err: e instanceof Error ? e.message : 'unknown' }, 'job crashed'); - this.db.update(jobs).set({ status: 'failed' }).where(eq(jobs.id, jobId)).run(); - }) - .finally(() => this.running.delete(p)); - this.running.add(p); + if (this.running.has(jobId)) return; + const p = this.run(jobId).catch((e: unknown) => { + this.log.error({ jobId, err: e instanceof Error ? e.message : 'unknown' }, 'job crashed'); + this.db.update(jobs).set({ status: 'failed' }).where(eq(jobs.id, jobId)).run(); + }).finally(() => this.running.delete(jobId)); + this.running.set(jobId, p); } - private async run(jobId: string): Promise { - const job = this.db.select().from(jobs).where(eq(jobs.id, jobId)).get()!; - const checklist = getChecklist(this.db, job.checklistVersionId)!; - const provider = this.provider; - const recorded = job.evaluationIds.length ? this.db.select().from(evaluations).where(inArray(evaluations.id, job.evaluationIds)).all() : []; - const done = new Set(recorded.map((e) => e.conversationId)); - const queue = job.conversationIds.filter((id) => !done.has(id)); - + const initial = this.db.select().from(jobs).where(eq(jobs.id, jobId)).get()!; + const checklist = getChecklist(this.db, initial.checklistVersionId)!; + // A reserved running attempt means the old process stopped before committing its outcome. + // It consumes its durable budget; do not silently reset retries or turn unknown spend into zero. + for (const e of this.recorded(initial)) if (e.status === 'running' || e.status === 'pending') { + this.db.update(evaluations).set({ status: 'failed', error: 'Evaluation interrupted before its outcome was saved; usage unavailable', diagnostics: { ...(e.diagnostics as Evaluation['diagnostics']), calls: [], retryable: true } }).where(eq(evaluations.id, e.id)).run(); + } + const state = outcomes(initial, this.recorded(initial)); + const queue = initial.conversationIds.filter(id => { + const list = state.byConversation.get(id) ?? [], last = list.at(-1); + return last?.status !== 'completed' && list.length < initial.maxAttempts && (last?.diagnostics as Evaluation['diagnostics'])?.retryable !== false; + }); + if (!this.provider && queue.some(id => { + const plan = planCriteria(getConversation(this.db, id)!, checklist, initial.force ? undefined : makeReuseLookup(this.db, id)); + return plan.undecided.length + plan.assisted.length > 0; + })) { + this.db.update(jobs).set({ status: 'pending' }).where(eq(jobs.id, jobId)).run(); + return; // Configuration can be restored before the next restart; do not spend attempts on a missing key. + } const worker = async () => { for (let id = queue.shift(); id !== undefined; id = queue.shift()) { const conversation = getConversation(this.db, id)!; - const base = { id: `eval-${randomUUID()}`, conversationId: id, checklistVersionId: checklist.id }; - let ev: Evaluation; - let decisionFacts: DecisionFacts | undefined; - try { - const r = await evaluateConversation(provider, conversation, checklist, job.force ? undefined : makeReuseLookup(this.db, id, provider)); - decisionFacts = r.decisionFacts; - this.log.info({ conversationId: id, provider: r.provenance.provider, model: r.provenance.model, modelCriteria: r.modelCriteria.length, ...r.usage }, 'evaluation cost'); - ev = { ...base, status: 'completed', originalResults: r.results, originalTotal: r.total, finalResults: structuredClone(r.results), finalTotal: r.total, seriousViolation: r.seriousViolation, provenance: r.provenance }; - } catch (e) { - const message = e instanceof Error ? e.message : 'evaluation failed'; - this.log.error({ conversationId: id, err: message }, 'evaluation failed'); - ev = { ...base, status: 'failed', originalResults: [], originalTotal: null, finalResults: [], finalTotal: null, seriousViolation: false, provenance: { provider: provider?.name ?? 'none', model: provider?.model ?? 'none', promptVersion: 'n/a' }, error: message }; + const previous = state.byConversation.get(id) ?? []; + for (let number = previous.length + 1; number <= initial.maxAttempts; number++) { + const last = previous.at(-1); + if (last?.status === 'failed') { + const due = Date.parse(last.createdAt) + (this.options.retryDelayMs ?? 1000) * 2 ** (number - 2); + await new Promise(r => setTimeout(r, Math.max(0, due - Date.now()))); + } + const base = { id: `eval-${randomUUID()}`, conversationId: id, checklistVersionId: checklist.id }; + const reserved: Evaluation = { ...base, status: 'running', originalResults: [], finalResults: [], originalTotal: null, finalTotal: null, seriousViolation: false, provenance: { provider: this.provider?.name ?? 'none', model: this.provider?.model ?? 'none', promptVersion: PROMPT_VERSION }, diagnostics: { jobId, attempt: number, calls: [] } }; + this.db.transaction(tx => { + insertEvaluation(tx as unknown as Db, reserved, evaluationCacheContext(conversation, this.provider)); + const cur = tx.select().from(jobs).where(eq(jobs.id, jobId)).get()!; + tx.update(jobs).set({ evaluationIds: [...cur.evaluationIds, base.id] }).where(eq(jobs.id, jobId)).run(); + }); + let ev: Evaluation, decisionFacts: DecisionFacts | undefined; + try { + const r = await evaluateConversation(this.provider, conversation, checklist, initial.force ? undefined : makeReuseLookup(this.db, id, this.provider)); + decisionFacts = r.decisionFacts; + ev = { ...base, status: 'completed', originalResults: r.results, originalTotal: r.total, finalResults: structuredClone(r.results), finalTotal: r.total, seriousViolation: r.seriousViolation, provenance: r.provenance, diagnostics: { ...r.diagnostics, jobId, attempt: number } }; + } catch (e) { + const error = e instanceof Error ? e.message : 'evaluation failed'; + const failure = e instanceof EvaluationFailure ? e : undefined; + decisionFacts = failure?.decisionFacts; + ev = { ...base, status: 'failed', originalResults: [], originalTotal: null, finalResults: [], finalTotal: null, seriousViolation: false, error, provenance: failure?.provenance ?? { provider: this.provider?.name ?? 'none', model: this.provider?.model ?? 'none', promptVersion: 'n/a' }, diagnostics: { ...failure?.diagnostics, jobId, attempt: number, calls: failure?.diagnostics?.calls ?? [] } }; + } + this.db.transaction(tx => { + // A reserved row receives its AI result exactly once, at the terminal transition. + tx.update(evaluations).set({ ...ev, decisionFacts: decisionFacts ?? null, provenance: ev.provenance ?? null, error: ev.error ?? null }).where(eq(evaluations.id, ev.id)).run(); + notifyCritical(tx as unknown as Db, ev); + const cur = tx.select().from(jobs).where(eq(jobs.id, jobId)).get()!; + const updated = cur; + const rows = updated.evaluationIds.length ? tx.select().from(evaluations).where(inArray(evaluations.id, updated.evaluationIds)).all() : []; + const { succeeded, failed } = outcomes(updated, rows); + tx.update(jobs).set({ evaluationIds: updated.evaluationIds, completed: succeeded + failed }).where(eq(jobs.id, jobId)).run(); + }); + this.log.info({ jobId, conversationId: id, attempt: number, status: ev.status, ...ev.provenance?.usage }, 'evaluation attempt'); + if (ev.status === 'completed' || ev.diagnostics?.retryable === false) break; + previous.push(this.db.select().from(evaluations).where(eq(evaluations.id, ev.id)).get()!); } - // Evaluation row and job progress commit together, so a crash never loses or duplicates one. - this.db.transaction((tx) => { - insertEvaluation(tx as unknown as Db, ev, evaluationCacheContext(conversation, provider), decisionFacts); - const cur = tx.select().from(jobs).where(eq(jobs.id, jobId)).get()!; - tx.update(jobs).set({ evaluationIds: [...cur.evaluationIds, ev.id], completed: cur.completed + 1 }).where(eq(jobs.id, jobId)).run(); - }); } }; await Promise.all(Array.from({ length: Math.min(this.concurrency, queue.length) }, worker)); - - const finalEvals = this.db.select().from(evaluations).where(inArray(evaluations.id, this.db.select().from(jobs).where(eq(jobs.id, jobId)).get()!.evaluationIds)).all(); - const allFailed = finalEvals.length > 0 && finalEvals.every((e) => e.status === 'failed'); - this.db.update(jobs).set({ status: allFailed ? 'failed' : 'completed' }).where(eq(jobs.id, jobId)).run(); + const job = this.getJob(jobId)!; + this.db.update(jobs).set({ status: job.failed ? (job.succeeded ? 'partial' : 'failed') : 'completed', completed: (job.succeeded ?? 0) + (job.failed ?? 0) }).where(eq(jobs.id, jobId)).run(); } } diff --git a/apps/api/src/services/evaluation/prompts.ts b/apps/api/src/services/evaluation/prompts.ts index d43ac58..5b5730d 100644 --- a/apps/api/src/services/evaluation/prompts.ts +++ b/apps/api/src/services/evaluation/prompts.ts @@ -2,7 +2,7 @@ import type { Criterion } from '@cqa/contracts'; import { calibrationExamples } from './calibration.js'; -export const PROMPT_VERSION = 'eval-v17'; +export const PROMPT_VERSION = 'eval-v18'; export const SYSTEM_PROMPT = `You evaluate the quality of ONE customer-support conversation (a typed chat or a phone call transcript) against a checklist. diff --git a/apps/api/src/services/evaluation/provider.ts b/apps/api/src/services/evaluation/provider.ts index c89e4ce..5af6da3 100644 --- a/apps/api/src/services/evaluation/provider.ts +++ b/apps/api/src/services/evaluation/provider.ts @@ -24,4 +24,15 @@ export interface LlmProvider { complete(req: ProviderRequest): Promise; } -export class ProviderError extends Error {} +export type Usage = NonNullable; +export const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }); +export function addUsage(target: ReturnType, usage?: Usage) { + if (!usage) return; + target.inputTokens += usage.inputTokens; + target.outputTokens += usage.outputTokens; + target.cacheReadTokens += usage.cacheReadTokens ?? 0; + target.cacheWriteTokens += usage.cacheWriteTokens ?? 0; +} +export class ProviderError extends Error { + constructor(message: string, public readonly usage?: Usage, public readonly retryable = true) { super(message); } +} diff --git a/apps/api/src/services/evaluation/semantic/consultation.ts b/apps/api/src/services/evaluation/semantic/consultation.ts index 60f4cc2..b7d1acc 100644 --- a/apps/api/src/services/evaluation/semantic/consultation.ts +++ b/apps/api/src/services/evaluation/semantic/consultation.ts @@ -13,7 +13,7 @@ export type ConsultationFacts = z.infer; export const consultationDetector: AssistedDetector = { name: 'consultation-facts', description: 'Extract actual requests and how they were handled; code chooses the exact consultation tier.', appliesTo: () => true, - question: `All evidence references in these answers are original integer message indices, not quote objects. Code will copy the exact original message text for evidence. Extract facts, never a grade. First set requestFormulated to whether the client formulated a substantive consultation need. A routing-only request to reach a human, greetings, or saying they will explain later is not yet a substantive consultation request. If the client leaves before explaining the problem, requestFormulated=false and requests=[] even if the operator connected and asked how to help. List ALL actually expressed client requests, including each distinct material question and any explicitly requested minor detail. A problem report or statement of inability to perform an action is a request for assistance even without a question mark. Cite the relevant client wording; split multiple questions even if in one message. Never invent an unasked requirement such as an ETA. Combine restatements/re-asks of the same question into one request anchored at its original formulation. requestFormulated=true requires a non-empty requests array; false requires an empty array. An empty requests array means the chat ended before any request was formulated. Classify each request as main/material/minor and its handling: answered, concrete_next_step (correct appropriate actionable client OR operator/team step, including investigation/escalation with a return path), generic_hint (too vague to know how to act), or unanswered. A pending underlying process is compatible with a concrete_next_step; final resolution and an unasked ETA are not required. Explain each request in description and cite client-facing operator evidence for any handling except unanswered. incorrectKeyRecommendation identifies an incorrect FINAL operative key recommendation, as a one-item array, or [] if none. An initial wrong route that was explicitly corrected is a dialogue-management issue, not automatically a final incorrect key recommendation. Inspect the entire transcript. Use responseLanguage for descriptions/reason.`, + question: `All evidence references in these answers are original integer message indices, not quote objects. Code will copy the exact original message text for evidence. Extract facts, never a grade. First set requestFormulated to whether the client formulated a substantive consultation need. A routing-only request to reach a human, greetings, or saying they will explain later is not yet a substantive consultation request. If the client leaves before explaining the problem, requestFormulated=false and requests=[] even if the operator connected and asked how to help. List ALL actually expressed client requests, including each distinct material question and any explicitly requested minor detail. A problem report or statement of inability to perform an action is a request for assistance even without a question mark. Cite the relevant client wording; split multiple questions even if in one message. Never invent an unasked requirement such as an ETA. Combine restatements/re-asks of the same question into one request anchored at its EARLIEST original formulation, including before bot handoff. Never anchor at a later clarification if the cited operator answer appeared earlier: clientRequest must precede every operatorEvidence index. A follow-up that only confirms an implication of an earlier answer is not a new unanswered request. requestFormulated=true requires a non-empty requests array; false requires an empty array. An empty requests array means the chat ended before any request was formulated. Classify each request as main/material/minor and its handling: answered, concrete_next_step (correct appropriate actionable client OR operator/team step, including investigation/escalation with a return path), generic_hint (too vague to know how to act), or unanswered. A pending underlying process is compatible with a concrete_next_step; final resolution and an unasked ETA are not required. Explain each request in description and cite client-facing operator evidence for any handling except unanswered. For unanswered, operatorEvidence MUST be []; irrelevant, evasive or incorrect operator replies are not handling evidence. Put a demonstrably incorrect final recommendation in incorrectKeyRecommendation instead. incorrectKeyRecommendation identifies an incorrect FINAL operative key recommendation, as a one-item array, or [] if none. An initial wrong route that was explicitly corrected is a dialogue-management issue, not automatically a final incorrect key recommendation. Inspect the entire transcript. Use responseLanguage for descriptions/reason.`, answersJsonSchema: object({ ...commonJson, requestFormulated: { type: 'boolean' }, requests: list(object({ description: { type: 'string' }, clientRequest: indexJson, materiality: choice('main', 'material', 'minor'), handling: choice('answered', 'concrete_next_step', 'generic_hint', 'unanswered'), operatorEvidence: list(indexJson) })), incorrectKeyRecommendation: list(indexJson) }), validate(input, raw) { const p = parsed(Schema, raw, input); if (!p.answers) return p; @@ -24,8 +24,8 @@ export const consultationDetector: AssistedDetector = { if (!a.requests.length && a.incorrectKeyRecommendation.length) problems.push('incorrect key recommendation requires a formulated request'); for (const r of a.requests) { if (r.handling !== 'unanswered' && !r.operatorEvidence.length) problems.push('non-absent request handling requires operator evidence'); - if (r.handling === 'unanswered' && r.operatorEvidence.length) problems.push('unanswered request must not claim handling evidence'); - for (const e of r.operatorEvidence) if (!before(r.clientRequest, e, input)) problems.push('request must precede handling evidence'); + if (r.handling === 'unanswered' && r.operatorEvidence.length) problems.push(`unanswered request must not claim handling evidence (request #${r.clientRequest.messageIndex}, operator indices ${r.operatorEvidence.map(e => e.messageIndex).join(', ')}). For unanswered use operatorEvidence=[]; an irrelevant or incorrect reply is not an answer.`); + for (const e of r.operatorEvidence) if (!before(r.clientRequest, e, input)) problems.push(`request must precede handling evidence (request #${r.clientRequest.messageIndex}, operator #${e.messageIndex}). Anchor restatements at the earliest client formulation, not a later clarification; otherwise remove this unrelated evidence.`); } return problems.length ? { problems } : { answers: a, problems: [] }; }, diff --git a/apps/api/src/services/evaluations.ts b/apps/api/src/services/evaluations.ts index b3565d7..71a272a 100644 --- a/apps/api/src/services/evaluations.ts +++ b/apps/api/src/services/evaluations.ts @@ -6,8 +6,8 @@ import { evaluations } from '../db/schema.js'; import { notifyCritical } from './notifications.js'; export function toEvaluation(row: typeof evaluations.$inferSelect): Evaluation { - const { error, provenance, ...rest } = row; - return EvaluationSchema.parse({ ...rest, error: error ?? undefined, provenance: provenance ?? undefined }); + const { error, provenance, diagnostics, ...rest } = row; + return EvaluationSchema.parse({ ...rest, error: error ?? undefined, provenance: provenance ?? undefined, diagnostics: diagnostics ?? undefined }); } /** Used by the evaluation job (issue #5). Final results start as a copy of the originals. */ diff --git a/apps/api/src/services/review.ts b/apps/api/src/services/review.ts index 34c0429..74ead7c 100644 --- a/apps/api/src/services/review.ts +++ b/apps/api/src/services/review.ts @@ -9,7 +9,7 @@ import { ApiError } from './errors.js'; type Tx = Parameters[0]>[0]; const latestEvaluationId = (tx: Tx | Db, conversationId: string) => - tx.select({ id: evaluations.id }).from(evaluations).where(eq(evaluations.conversationId, conversationId)).orderBy(desc(evaluations.createdAt), desc(evaluations.id)).get()?.id; + tx.select({ id: evaluations.id }).from(evaluations).where(and(eq(evaluations.conversationId, conversationId), eq(evaluations.status, 'completed'))).orderBy(desc(evaluations.createdAt), desc(evaluations.id)).get()?.id; /** `new` reopens the dialog (drops the review); the others are bound to the dialog's latest evaluation. */ export function setReview(db: Db, conversationId: string, input: SetReviewInput, actor?: Actor): void { diff --git a/apps/api/src/services/work.ts b/apps/api/src/services/work.ts index b8d2b98..fa20bb0 100644 --- a/apps/api/src/services/work.ts +++ b/apps/api/src/services/work.ts @@ -20,7 +20,7 @@ function requireVisible(db: Db, conversationId: string, actor: Actor | undefined if (!conversationExists(db, conversationId) || !canSee(scopeOf(db, actor), { operatorId: operatorOf(db, conversationId) })) throw new ApiError('conversation not found', 404); } const latestEvaluation = (db: Db, conversationId: string) => - db.select().from(evaluations).where(eq(evaluations.conversationId, conversationId)).orderBy(desc(evaluations.createdAt), desc(evaluations.id)).get(); + db.select().from(evaluations).where(and(eq(evaluations.conversationId, conversationId), eq(evaluations.status, 'completed'))).orderBy(desc(evaluations.createdAt), desc(evaluations.id)).get(); // ---------- comments ---------- diff --git a/apps/api/test/evaluator.test.ts b/apps/api/test/evaluator.test.ts index 84d1f42..aec73aa 100644 --- a/apps/api/test/evaluator.test.ts +++ b/apps/api/test/evaluator.test.ts @@ -164,8 +164,9 @@ describe('POST /api/evaluations', () => { const p = fakeProvider((req) => genericAnswer(req, (r) => { if (r[0]) r[0].evidence = [{ messageIndex: 99 }]; })); const { app } = setup(p); const { job } = await run(app, { conversationIds: [conv.id], checklistVersionId: 'checklist-original-v1' }); - expect(p.calls).toHaveLength(3); - expect(job.status).toBe('failed'); + expect(p.calls).toHaveLength(6); // Two bounded attempts, each with a validated repair. + expect(job).toMatchObject({ status: 'failed', succeeded: 0, failed: 1, completed: 1 }); + expect(job.evaluationIds).toHaveLength(2); const ev = (await app.inject({ url: `/api/evaluations/${job.evaluationIds[0]}` })).json(); expect(ev).toMatchObject({ status: 'failed', originalResults: [], originalTotal: null }); expect(ev.error).toMatch(/failed validation/); @@ -182,7 +183,8 @@ describe('POST /api/evaluations', () => { const { job } = await run(app, { conversationIds: [conv.id, other.id], checklistVersionId: 'checklist-original-v1' }); expect(job).toMatchObject({ status: 'completed', completed: 2, total: 2 }); const statuses = await Promise.all(job.evaluationIds.map(async (id: string) => (await app.inject({ url: `/api/evaluations/${id}` })).json().status)); - expect(statuses.sort()).toEqual(['completed', 'failed']); + expect(statuses.sort()).toEqual(['completed', 'completed', 'failed']); // Failure remains audited after recovery. + expect(job).toMatchObject({ succeeded: 2, failed: 0 }); }); it('resume after a restart evaluates only conversations without a recorded evaluation', async () => { diff --git a/apps/api/test/migration.test.ts b/apps/api/test/migration.test.ts index 123d5f3..2f51d69 100644 --- a/apps/api/test/migration.test.ts +++ b/apps/api/test/migration.test.ts @@ -15,7 +15,9 @@ it('upgrades a legacy database idempotently without losing prior evaluations or legacy.exec(` ALTER TABLE evaluations DROP COLUMN cache_context; ALTER TABLE evaluations DROP COLUMN decision_facts; + ALTER TABLE evaluations DROP COLUMN diagnostics; ALTER TABLE jobs DROP COLUMN force; + ALTER TABLE jobs DROP COLUMN max_attempts; INSERT INTO evaluations VALUES ('old', 'c', 'v', 'completed', '[]', 0, '[]', 0, 0, NULL, NULL, 'then'); INSERT INTO jobs VALUES ('j', 'v', '["c"]', '["old"]', 'completed', 1, 1, 'then'); `); @@ -25,6 +27,8 @@ it('upgrades a legacy database idempotently without losing prior evaluations or expect(upgraded.$client.prepare('SELECT cache_context FROM evaluations WHERE id = ?').get('old')).toEqual({cache_context:null}); expect(upgraded.$client.prepare('SELECT decision_facts FROM evaluations WHERE id = ?').get('old')).toEqual({decision_facts:null}); expect(upgraded.$client.prepare('SELECT force FROM jobs WHERE id = ?').get('j')).toEqual({force:0}); + expect(upgraded.$client.prepare('SELECT diagnostics FROM evaluations WHERE id = ?').get('old')).toEqual({diagnostics:null}); + expect(upgraded.$client.prepare('SELECT max_attempts FROM jobs WHERE id = ?').get('j')).toEqual({max_attempts:1}); upgraded.$client.close(); } } finally { rmSync(dir, {recursive:true,force:true}); } diff --git a/apps/api/test/recovery.test.ts b/apps/api/test/recovery.test.ts new file mode 100644 index 0000000..14f9bd5 --- /dev/null +++ b/apps/api/test/recovery.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest'; +import { openDb } from '../src/db/index.js'; +import { conversations, checklistVersions, evaluations, jobs } from '../src/db/schema.js'; +import { JobRunner } from '../src/services/evaluation/jobs.js'; +import type { LlmProvider, ProviderRequest } from '../src/services/evaluation/provider.js'; + +const log = { info() {}, error() {} }; +const make = () => { + const db = openDb(':memory:'); + db.insert(checklistVersions).values({ id: 'custom', version: 1, title: 'Custom', createdAt: 'now', criteria: [{ id: 'custom', title: 'Thanks', instructions: 'Did operator thank the client?', kind: 'boolean', allowedValues: [true, false], weight: 10, allowNA: false }] }).run(); + for (const id of ['a', 'b']) db.insert(conversations).values({ id, datasetGroupId: 'fictional', language: 'EN', channel: 'agent chat', audioUrl: null, importedAt: 'now', transcript: [{ index: 0, timestamp: '00:00', speaker: 'client', text: 'Help please.' }, { index: 1, timestamp: '00:01', speaker: 'operator', text: 'Thanks for contacting us.' }] }).run(); + return db; +}; +const answer = { results: [{ criterionId: 'custom', value: true, isNA: false, explanation: 'Thanked client.', evidence: [{ messageIndex: 1, quote: 'Thanks' }] }] }; +const provider = (respond: (req: ProviderRequest, n: number) => unknown): LlmProvider => { + let n = 0; return { name: 'test', model: 'test', async complete(req) { return { output: respond(req, ++n), usage: { inputTokens: 10, outputTokens: 5 } }; } }; +}; +const input = { conversationIds: ['a', 'b'], checklistVersionId: 'custom' }; + +describe('durable evaluation recovery', () => { + it('retries failed work only, retaining failed usage and successful results', async () => { + const db = make(); const p = provider((req, n) => JSON.parse(req.user).conversation.transcript.length && n <= 2 ? {} : answer); + const runner = new JobRunner(db, p, log, 1, { retryDelayMs: 0 }); + const job = runner.start(input); await runner.idle(); + expect(runner.getJob(job.id)).toMatchObject({ status: 'completed', succeeded: 2, failed: 0, completed: 2, total: 2 }); + const all = db.select().from(evaluations).all(); + expect(all.filter(e => e.conversationId === 'b')).toHaveLength(1); + expect(all.filter(e => e.status === 'failed')).toHaveLength(1); + expect(all.find(e => e.status === 'failed')?.provenance).toMatchObject({ usage: { inputTokens: 20, outputTokens: 10 } }); + expect(all.find(e => e.status === 'failed')?.diagnostics).toMatchObject({ calls: expect.arrayContaining([expect.objectContaining({ problems: expect.any(Array) })]) }); + }); + it('reports a partial batch after bounded exhaustion and permits failed-only retry', async () => { + const db = make(); + const runner = new JobRunner(db, provider(() => ({})), log, 1, { retryDelayMs: 0 }); + // One success is already committed to this job, as after a restart. + const seed = new JobRunner(db, provider(() => answer), log, 1, { retryDelayMs: 0 }); + const first = seed.start({ ...input, conversationIds: ['b'] }); await seed.idle(); + db.insert(jobs).values({ id: 'resume', checklistVersionId: 'custom', conversationIds: ['a','b'], evaluationIds: seed.getJob(first.id)!.evaluationIds, total: 2, completed: 1, status: 'running', createdAt: 'now', maxAttempts: 2 }).run(); + runner.resume(); runner.resume(); await runner.idle(); + expect(runner.getJob('resume')).toMatchObject({ status: 'partial', succeeded: 1, failed: 1, completed: 2 }); + expect(db.select().from(evaluations).all().filter(e => e.conversationId === 'b')).toHaveLength(1); + const good = new JobRunner(db, provider(() => answer), log, 1, { retryDelayMs: 0 }); + const retry = good.start({ ...input, retryFailedOnly: true }); await good.idle(); + expect(good.getJob(retry.id)).toMatchObject({ total: 1, succeeded: 1, failed: 0 }); + expect(db.select().from(evaluations).all().filter(e => e.conversationId === 'b')).toHaveLength(1); + }); + it('resumes an interrupted retry without resetting its budget or touching successful chats', async () => { + const db = make(); + const first = new JobRunner(db, provider(() => ({})), log, 1, { maxAttempts: 1, retryDelayMs: 0 }); + const j = first.start({ ...input, conversationIds: ['a'] }); await first.idle(); + db.insert(jobs).values({ id: 'interrupted', checklistVersionId: 'custom', conversationIds: ['a'], evaluationIds: first.getJob(j.id)!.evaluationIds, total: 1, completed: 0, status: 'running', createdAt: 'now', maxAttempts: 2 }).run(); + const resumed = new JobRunner(db, provider(() => answer), log, 1, { retryDelayMs: 0 }); + resumed.resume(); resumed.resume(); await resumed.idle(); + expect(resumed.getJob('interrupted')).toMatchObject({ status: 'completed', succeeded: 1 }); + expect(db.select().from(evaluations).all()).toHaveLength(2); + }); + it('counts interrupted in-flight work against the budget and waits when provider configuration is absent', async () => { + const db = make(); + db.insert(evaluations).values({ id: 'inflight', conversationId: 'a', checklistVersionId: 'custom', status: 'running', originalResults: [], finalResults: [], originalTotal: null, finalTotal: null, seriousViolation: false, createdAt: '2020-01-01', diagnostics: { jobId: 'crashed', attempt: 1, calls: [] } }).run(); + db.insert(jobs).values({ id: 'crashed', checklistVersionId: 'custom', conversationIds: ['a'], evaluationIds: ['inflight'], total: 1, completed: 0, status: 'running', createdAt: 'now', maxAttempts: 2 }).run(); + const missing = new JobRunner(db, undefined, log, 1, { retryDelayMs: 0 }); + missing.resume(); await missing.idle(); + expect(missing.getJob('crashed')).toMatchObject({ status: 'pending', retrying: 1 }); + expect(db.select().from(evaluations).all()).toHaveLength(1); + const resumed = new JobRunner(db, provider(() => ({})), log, 1, { retryDelayMs: 0 }); + resumed.resume(); await resumed.idle(); + expect(resumed.getJob('crashed')).toMatchObject({ status: 'failed', failed: 1 }); + expect(db.select().from(evaluations).all()).toHaveLength(2); + resumed.resume(); await resumed.idle(); + expect(db.select().from(evaluations).all()).toHaveLength(2); + }); + it('reattaches duplicate starts and does not launch the same active job twice', async () => { + const db = make(); let release!: () => void; let n = 0; + const p: LlmProvider = { name: 'test', model: 'test', async complete() { n++; await new Promise(r => { release = r; }); return { output: answer }; } }; + const runner = new JobRunner(db, p, log, 1, { retryDelayMs: 0 }); + const j = runner.start({ ...input, conversationIds: ['a'] }); + expect(runner.start({ ...input, conversationIds: ['a'] }).id).toBe(j.id); + runner.resume(); + expect(n).toBe(1); + expect(() => runner.start(input)).toThrow(/already running/); + release(); await runner.idle(); + expect(runner.getJob(j.id)).toMatchObject({ succeeded: 1, failed: 0 }); + }); + +}); diff --git a/apps/api/test/semantic-facts.test.ts b/apps/api/test/semantic-facts.test.ts index 9a811df..379b2a8 100644 --- a/apps/api/test/semantic-facts.test.ts +++ b/apps/api/test/semantic-facts.test.ts @@ -55,6 +55,16 @@ describe('semantic rubric decisions', () => { expect(decide(consultationDetector, '04', { ...base, incorrectKeyRecommendation: [ref(1)] }).value).toBe(0); expect(decide(consultationDetector, '04', { ...base, requestFormulated: false, requests: [] })).toMatchObject({ value: null, isNA: true }); }); + it('04 repairs later-request anchors and unanswered evidence without weakening validation', () => { + const late = { ...consultation(), requests: [{ ...request('main', 'answered', 'Where is the login?'), clientRequest: ref(2), operatorEvidence: [ref(1)] }] }; + const problems = consultationDetector.validate(input('04'), late).problems.join(); + expect(problems).toMatch(/request #2, operator #1/); + expect(problems).toMatch(/earliest client formulation/); + expect(decide(consultationDetector, '04', { ...late, requests: [{ ...late.requests[0], clientRequest: ref(0) }] }).value).toBe(20); + const absent = { ...consultation(), requests: [{ ...request('main', 'unanswered', 'Where is the login?'), operatorEvidence: [ref(3)] }] }; + expect(consultationDetector.validate(input('04'), absent).problems.join()).toMatch(/operatorEvidence=\[\]/); + expect(decide(consultationDetector, '04', { ...absent, requests: [{ ...absent.requests[0], operatorEvidence: [] }] }).value).toBe(0); + }); it('06 keeps the forced re-ask tier after successful correction', () => { const d = { ...dialogue(), forcedClarifications: [{ operatorWording: ref(1, 'Open the app menu.'), clientReask: ref(2), kind: 'wrong_navigation', reason: 'Wrong navigation forced a re-ask.' }] }; expect(decide(dialogueDetector, '06', d).value).toBe(4); diff --git a/apps/api/test/verification.test.ts b/apps/api/test/verification.test.ts index 441ab1c..ef53f8c 100644 --- a/apps/api/test/verification.test.ts +++ b/apps/api/test/verification.test.ts @@ -186,7 +186,7 @@ describe('verification inside the evaluation pipeline', () => { const bad = { ...good, firstProtectedDisclosure: { messageIndex: 8, quote: 'выдуманная цитата' } }; const { app, calls } = run(() => ({ assisted: [{ criterionId: '03', answers: bad }] })); const ev = await start(app); - expect(calls).toHaveLength(3); + expect(calls).toHaveLength(6); // Both bounded job attempts reject fabricated evidence. expect(ev).toMatchObject({ status: 'failed', originalResults: [] }); expect(ev.error).toMatch(/assisted 03/); }); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 7765188..893b70e 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,4 +1,4 @@ -import { can, type Comment, type Directory, type ErrorOrigin, type Notification, type SaveTimelineEventInput, type Tag as ErrorTag, type Task, type TaxonomyItem, type TimelineEvent, type Appeal, type ChecklistVersion, type Conversation, type DecideAppealInput, type Evaluation, type SaveChecklistInput } from '@cqa/contracts'; +import { evaluationMaps, can, type Comment, type Directory, type ErrorOrigin, type Notification, type SaveTimelineEventInput, type Tag as ErrorTag, type Task, type TaxonomyItem, type TimelineEvent, type Appeal, type ChecklistVersion, type Conversation, type DecideAppealInput, type Evaluation, type Job, type SaveChecklistInput } from '@cqa/contracts'; import { AlertTriangle, ArrowLeft, ChevronLeft, ChevronRight, PanelLeftOpen } from 'lucide-react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { MockCqaApi } from './api'; @@ -90,6 +90,7 @@ export function App() { const [focus, setFocus] = useState(null); const [pane, setPane] = useState('evaluation'); const [starting, setStarting] = useState(false); + const [jobProgress, setJobProgress] = useState(null); const [startError, setStartError] = useState(null); const [searchFocus, setSearchFocus] = useState(0); const [onlyFlagged, setOnlyFlagged] = useState(false); @@ -192,7 +193,7 @@ export function App() { if (load.status === 'ready') for (const e of load.data.evaluations) (m.get(e.conversationId) ?? m.set(e.conversationId, []).get(e.conversationId)!).push(e); return m; }, [load]); - const latest = useMemo(() => new Map([...byConversation].map(([id, list]) => [id, list[list.length - 1]!])), [byConversation]); + const { preferred: latest, attempts: latestAttempts } = useMemo(() => evaluationMaps(load.status === 'ready' ? load.data.evaluations : []), [load]); /** The dialogs the list currently shows: previous/next and J/K walk this queue, not all dialogs. */ /** Serious violations nobody has dealt with yet (not reviewed, not commented, not read): the "was it worked through" filter. */ @@ -258,7 +259,7 @@ export function App() { const evaluationId = (() => { const list = selectedId ? byConversation.get(selectedId) : undefined; - return (list?.find((e) => e.id === pickedEvaluationId) ?? list?.[list.length - 1])?.id ?? null; + return (list?.find((e) => e.id === pickedEvaluationId) ?? (selectedId ? latest.get(selectedId) : undefined))?.id ?? null; })(); /** Results the digit keys 1-9 open: the rows exactly as the panel lists them (sections, attention filter). */ @@ -333,11 +334,12 @@ export function App() { } /** Starts a job and waits for it; the job decides what is recomputed (rules and unchanged criteria are reused server-side). */ - const runJob = async (ids: string[], checklistVersionId: string) => { - const { jobId } = await api.startEvaluation({ conversationIds: ids, checklistVersionId }); + const runJob = async (ids: string[], checklistVersionId: string, retryFailedOnly = false) => { + const { jobId } = await api.startEvaluation({ conversationIds: ids, checklistVersionId, retryFailedOnly }); for (;;) { const job = await api.getJob(jobId); - if (job.status === 'completed' || job.status === 'failed') break; + setJobProgress(job); + if (job.status !== 'pending' && job.status !== 'running') break; await new Promise((r) => setTimeout(r, 1000)); } await reload(); @@ -357,6 +359,18 @@ export function App() { } }; + const retryFailed = async (onlyId?: string) => { + const failed = [...latestAttempts.values()].filter(e => e.status === 'failed' && (!onlyId || e.conversationId === onlyId)); + const groups = new Map(); + for (const e of failed) groups.set(e.checklistVersionId, [...(groups.get(e.checklistVersionId) ?? []), e.conversationId]); + setStarting(true); setStartError(null); + try { for (const [checklistId, ids] of groups) await runJob(ids, checklistId, true); } + catch (e) { setStartError(e); } + finally { setStarting(false); } + }; + const failedCount = [...latestAttempts.values()].filter(e => e.status === 'failed').length; + const progressText = jobProgress ? `Готово: ${jobProgress.succeeded ?? jobProgress.completed} из ${jobProgress.total}; ошибок: ${jobProgress.failed ?? 0}; повторяются: ${jobProgress.retrying ?? 0}` : null; + const saveChecklist = async (input: SaveChecklistInput) => { const v = await api.saveChecklistVersion(input); await reload(); @@ -520,7 +534,7 @@ export function App() { ) : route.name === 'list' ? (
- go({ name: 'dialog', id })} identity={identity} people={data.directory.people} onAssign={assign} followUpOpen={followUpOpen} onTasks={can(identity, 'task') ? async (ids, kind) => { await api.createTasks({ conversationIds: ids, kind }); await reload(); } : undefined} focusSignal={searchFocus} /> + retryFailed() : undefined} retrying={starting} progress={progressText} retryError={startError} attempts={latestAttempts} conversations={data.conversations} latest={latest} checklists={data.checklists} filters={filters} onFilters={setFilters} onOpen={(id) => go({ name: 'dialog', id })} identity={identity} people={data.directory.people} onAssign={assign} followUpOpen={followUpOpen} onTasks={can(identity, 'task') ? async (ids, kind) => { await api.createTasks({ conversationIds: ids, kind }); await reload(); } : undefined} focusSignal={searchFocus} />
) : !conversation ? (
@@ -577,6 +591,9 @@ export function App() { onSelectCriterion={(id) => setCriterionId((cur) => (cur === id ? null : id))} onJump={jump} onStart={start} + latestAttempt={latestAttempts.get(conversation.id)} + onRetry={() => retryFailed(conversation.id)} + progress={starting ? progressText : null} starting={starting} startError={startError} appeals={data.appeals.filter((a) => a.evaluationId === evaluationId)} @@ -597,7 +614,7 @@ export function App() { onlyFlagged={onlyFlagged} onOnlyFlagged={setOnlyFlagged} demoMode={mode === 'mock'} - versions={list.map((ev, i) => ({ id: ev.id, label: `Версия ${versionOf(ev) ?? '?'}${i === list.length - 1 ? ' (последняя)' : ''}` }))} + versions={list.map((ev, i) => ({ id: ev.id, label: `Версия ${versionOf(ev) ?? '?'} · ${ev.status === 'failed' ? 'ошибка' : ev.provenance?.promptVersion ?? ev.status}${i === list.length - 1 ? ' (последняя попытка)' : ''}` }))} onPickEvaluation={(id) => { setPickedEvaluationId(id); setCriterionId(null); diff --git a/apps/web/src/api/MockCqaApi.ts b/apps/web/src/api/MockCqaApi.ts index d743385..3945c1d 100644 --- a/apps/web/src/api/MockCqaApi.ts +++ b/apps/web/src/api/MockCqaApi.ts @@ -197,7 +197,7 @@ export class MockCqaApi implements CqaApi { delete conv.review; this.log('review.set', 'Диалог возвращён в новые', conversationId, { status: 'new' }); } else { - const latest = [...this.evaluations].reverse().find((e) => e.conversationId === conversationId); + const latest = [...this.evaluations].reverse().find((e) => e.conversationId === conversationId && e.status === 'completed'); if (!latest) throw new CqaApiError('conflict', 'Диалог ещё не оценён: проверять пока нечего'); const a = this.actor(); conv.review = { status: parsed.data.status, evaluationId: latest.id, by: a.name, at: new Date().toISOString() }; @@ -431,7 +431,9 @@ export class MockCqaApi implements CqaApi { const checklist = this.checklists.find((c) => c.id === parsed.data.checklistVersionId); if (!checklist) throw new CqaApiError('not_found', `checklist ${parsed.data.checklistVersionId} not found`); const created: Evaluation[] = []; - for (const conversationId of parsed.data.conversationIds) { + const ids = [...new Set(parsed.data.conversationIds)].filter(id => !parsed.data.retryFailedOnly || [...this.evaluations].reverse().find(e => e.conversationId === id && e.checklistVersionId === checklist.id)?.status === 'failed'); + if (!ids.length) throw new CqaApiError('conflict', 'no failed conversations on this checklist to retry'); + for (const conversationId of ids) { const conv = this.conversations.find((c) => c.id === conversationId); if (!conv) throw new CqaApiError('not_found', `conversation ${conversationId} not found`); const results = checklist.criteria.map((c) => placeholderResult(c, conv.transcript.length - 1)); @@ -452,7 +454,7 @@ export class MockCqaApi implements CqaApi { } this.evaluations.push(...created); const jobId = this.nextId('job-mock'); - this.jobs.set(jobId, { id: jobId, status: 'completed', completed: created.length, total: created.length, evaluationIds: created.map((e) => e.id) }); + this.jobs.set(jobId, { id: jobId, status: 'completed', succeeded: created.length, failed: 0, retrying: 0, completed: created.length, total: created.length, evaluationIds: created.map((e) => e.id) }); return later({ jobId }); } diff --git a/apps/web/src/features/DialogsPage.tsx b/apps/web/src/features/DialogsPage.tsx index 27d4c51..ea6ae94 100644 --- a/apps/web/src/features/DialogsPage.tsx +++ b/apps/web/src/features/DialogsPage.tsx @@ -9,9 +9,16 @@ import { cn } from '@/lib/utils'; import { downloadText, queueCsv } from '@/lib/export'; import { formatScore, REVIEW_LABEL } from '@/lib/present'; import { DEFAULT_FILTERS, NO_OPERATOR, counts, hasViolation, matches, reviewCount, reviewOf, sortConversations, violationReasons, type Filters, type Quick, type ReviewState, type Sort, type SortKey } from '@/lib/queue'; +import { ErrorNote } from '@/components/ui/error-note'; import { AssignOperator } from './AssignOperator'; type Props = { + failedCount?: number; + onRetryFailed?: () => Promise; + retrying?: boolean; + progress?: string | null; + retryError?: unknown; + attempts?: Map; conversations: Conversation[]; latest: Map; checklists: ChecklistVersion[]; @@ -61,7 +68,7 @@ function ReviewChip({ c, e }: { c: Conversation; e: Evaluation | undefined }) { } /** The queue: every dialog with its score, the reason for a serious violation and what needs a human look. */ -export function DialogsPage({ conversations, latest, checklists, filters, onFilters, onOpen, identity, people, onAssign, onTasks, followUpOpen, focusSignal = 0 }: Props) { +export function DialogsPage({ failedCount = 0, onRetryFailed, retrying, progress, retryError, attempts, conversations, latest, checklists, filters, onFilters, onOpen, identity, people, onAssign, onTasks, followUpOpen, focusSignal = 0 }: Props) { const search = useRef(null); useEffect(() => { if (focusSignal > 0) search.current?.focus(); @@ -113,6 +120,11 @@ export function DialogsPage({ conversations, latest, checklists, filters, onFilt

{staff ? 'Диалоги' : 'Мои диалоги'}

+ {(failedCount > 0 || progress) &&
+ {progress ?? `Последняя оценка не получилась: ${failedCount}. Предыдущие успешные оценки сохранены.`} + {failedCount > 0 && onRetryFailed && } +
} +

{staff ? 'Очередь проверки: сверху то, что ещё никто не смотрел. Откройте диалог, чтобы увидеть оценку и её обоснование.' : 'Ваши диалоги с оценками. Откройте диалог, чтобы увидеть обоснование; если не согласны с оценкой, её можно оспорить.'}

@@ -236,7 +248,7 @@ export function DialogsPage({ conversations, latest, checklists, filters, onFilt
- + {staff && e && } {review > 0 && Проверить: {review}}
diff --git a/apps/web/src/features/EvaluationPanel.tsx b/apps/web/src/features/EvaluationPanel.tsx index 43706a8..00b1c89 100644 --- a/apps/web/src/features/EvaluationPanel.tsx +++ b/apps/web/src/features/EvaluationPanel.tsx @@ -20,6 +20,9 @@ import { CriterionTags, DialogComments } from './DialogNotes'; type Props = { conversation: Conversation; evaluation: Evaluation | undefined; + latestAttempt?: Evaluation; + onRetry?: () => void; + progress?: string | null; checklist: ChecklistVersion | undefined; selectedCriterionId: string | null; onSelectCriterion: (id: string) => void; @@ -263,7 +266,7 @@ function CriterionRow({ tags, taxonomy, onAddTag, identity, criterion, result, o ); } -export function EvaluationPanel({ comments, tags, taxonomy, onAddComment, onAckComment, onAddTag, identity, conversation, evaluation, checklist, selectedCriterionId, onSelectCriterion, onJump, onStart, starting, startError, appeals, onCreateAppeal, onDecideAppeal, onCorrect, onlyFlagged, onOnlyFlagged, demoMode, versions, onPickEvaluation, newerChecklistVersion }: Props) { +export function EvaluationPanel({ latestAttempt, onRetry, progress, comments, tags, taxonomy, onAddComment, onAckComment, onAddTag, identity, conversation, evaluation, checklist, selectedCriterionId, onSelectCriterion, onJump, onStart, starting, startError, appeals, onCreateAppeal, onDecideAppeal, onCorrect, onlyFlagged, onOnlyFlagged, demoMode, versions, onPickEvaluation, newerChecklistVersion }: Props) { /** An opened criterion (digit key, tag on a message, link) is brought into view with its form. */ useEffect(() => { if (!selectedCriterionId || !evaluation) return; @@ -295,7 +298,7 @@ export function EvaluationPanel({ comments, tags, taxonomy, onAddComment, onAckC

Оценка не получилась

- {can(identity, 'evaluate') && } + {can(identity, 'evaluate') && }
); @@ -329,6 +332,12 @@ export function EvaluationPanel({ comments, tags, taxonomy, onAddComment, onAckC when there are any. Where points went is the list below (colored rows with reasons), so it is not repeated here; how the total is made is the score's tooltip. The checklist version is the bar under the banner. */} + {latestAttempt?.status === 'failed' && latestAttempt.id !== evaluation.id &&
+

Последняя попытка завершилась ошибкой. Показана предыдущая успешная оценка по версии {checklist?.version ?? '?'}.

+

{latestAttempt.error}

+ {can(identity, 'evaluate') && } +
} + {progress &&

{progress}

}

Оценка диалога

@@ -377,7 +386,7 @@ export function EvaluationPanel({ comments, tags, taxonomy, onAddComment, onAckC {versions.map((v) => )} ) : ( - {checklist ? `Чек-лист, версия ${checklist.version}` : 'Чек-лист не найден'} + {checklist ? `Чек-лист, версия ${checklist.version}` : 'Чек-лист не найден'} · {evaluation.provenance?.promptVersion ?? 'версия оценщика не записана'} )} {newerChecklistVersion !== null && can(identity, 'evaluate') && ( diff --git a/apps/web/src/features/StatsPage.tsx b/apps/web/src/features/StatsPage.tsx index 04ae20d..b28bfa8 100644 --- a/apps/web/src/features/StatsPage.tsx +++ b/apps/web/src/features/StatsPage.tsx @@ -79,7 +79,7 @@ export function StatsPage({ conversations, evaluations, checklists, appeals, ide ) : ( <>
- + diff --git a/apps/web/src/lib/analytics.ts b/apps/web/src/lib/analytics.ts index d78aab4..4a0a088 100644 --- a/apps/web/src/lib/analytics.ts +++ b/apps/web/src/lib/analytics.ts @@ -1,3 +1,4 @@ +import { evaluationMaps } from '@cqa/contracts'; import type { Appeal, AuditEvent, ChecklistVersion, Comment, Conversation, Crosscheck, Directory, Evaluation, Person, Tag, Task, TimelineEvent } from '@cqa/contracts'; import { earnedPoints, sameResult } from './present'; import { reviewOf } from './queue'; @@ -20,9 +21,7 @@ const median = (xs: number[]) => { /** The current evaluation of each dialog (the API lists evaluations in creation order). */ export function latestOf(evaluations: Evaluation[]): Map { - const m = new Map(); - for (const e of evaluations) m.set(e.conversationId, e); - return m; + return evaluationMaps(evaluations).preferred; } const done = (e: Evaluation | undefined): e is Evaluation => e?.status === 'completed'; const total = (e: Evaluation) => (e.finalTotal === null ? [] : [e.finalTotal]); diff --git a/apps/web/src/lib/stats.ts b/apps/web/src/lib/stats.ts index 549a879..de4d00c 100644 --- a/apps/web/src/lib/stats.ts +++ b/apps/web/src/lib/stats.ts @@ -1,3 +1,4 @@ +import { evaluationMaps } from '@cqa/contracts'; import type { Appeal, ChecklistVersion, Conversation, Criterion, Evaluation, Language } from '@cqa/contracts'; import { earnedPoints, needsReview, sameResult } from './present'; import { reviewOf } from './queue'; @@ -61,8 +62,7 @@ export type Stats = { const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null); export function computeStats({ conversations, evaluations, checklists, appeals, language, checklistId }: StatsInput): Stats { - const latest = new Map(); - for (const e of evaluations) latest.set(e.conversationId, e); + const { preferred: latest, attempts } = evaluationMaps(evaluations); const inScope = conversations.filter((c) => language === 'all' || c.language === language); const current = inScope.map((c) => latest.get(c.id)).filter((e): e is Evaluation => !!e); @@ -164,7 +164,7 @@ export function computeStats({ conversations, evaluations, checklists, appeals, byOperator, dialogs: inScope.length, evaluated: done.length, - failed: current.filter((e) => e.status === 'failed').length, + failed: inScope.filter(c => attempts.get(c.id)?.status === 'failed').length, notEvaluated: inScope.length - current.length, averageTotal: mean(done.flatMap((e) => (e.finalTotal === null ? [] : [e.finalTotal]))), seriousViolations: done.filter((e) => e.seriousViolation).length, diff --git a/apps/web/test/recovery.test.tsx b/apps/web/test/recovery.test.tsx new file mode 100644 index 0000000..5600161 --- /dev/null +++ b/apps/web/test/recovery.test.tsx @@ -0,0 +1,30 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { afterEach, beforeAll, expect, it, vi } from 'vitest'; +import { DemoBundleSchema } from '@cqa/contracts'; +import demo from '../../../fixtures/demo.json'; +import { ApiProvider } from '../src/ApiContext'; +import { App } from '../src/App'; +import { MockCqaApi } from '../src/api'; +import { asRole } from './roles'; +beforeAll(() => { Element.prototype.scrollIntoView = vi.fn(); }); +afterEach(() => { cleanup(); window.location.hash = ''; window.localStorage.clear(); }); +it('shows the previous valid score and failed-attempt notice, then retries only failed work through the mock', async () => { + asRole('lead'); + const bundle = DemoBundleSchema.parse(structuredClone(demo)); + const original = bundle.evaluations[0]!; + bundle.evaluations.push({ ...original, id: 'failed-recovery-demo', status: 'failed', originalResults: [], finalResults: [], originalTotal: null, finalTotal: null }); + const api = new MockCqaApi(bundle); + const spy = vi.spyOn(api, 'startEvaluation'); + window.location.hash = '#/dialog/demo-ru-001'; + render(); + const panel = within(await screen.findByRole('region', { name: 'Оценка' })); + expect(await panel.findByText('94,12')).toBeTruthy(); + expect(panel.getByText(/Показана предыдущая успешная оценка/)).toBeTruthy(); + fireEvent.click(panel.getByRole('button', { name: 'Повторить неудавшуюся оценку' })); + await vi.waitFor(() => expect(spy).toHaveBeenCalledWith(expect.objectContaining({ conversationIds: ['demo-ru-001'], retryFailedOnly: true }))); + await vi.waitFor(() => expect(panel.queryByText(/Показана предыдущая успешная оценка/)).toBeNull()); + const all = await api.listEvaluations({ conversationId: 'demo-ru-001' }); + expect(all).toHaveLength(3); + expect(all[0]!.originalResults).toEqual(original.originalResults); +}); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 647b139..dadab90 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -247,3 +247,12 @@ Bumping either invalidates cached results; legacy rows without a cache context a - Voice transcripts are speech-recognition output; absence claims inside recording pauses are capped at medium confidence and flagged for human review. - Rounding of halfway cases is provisional (§5.3). No authentication: the role is a demo switch that any client can spoof. - Cost reporting is per-evaluation token usage in provenance; price conversion is done by the evaluation tool (`--price-in/--price-out`). + + +## Evaluation recovery + +New jobs allow at most two durable evaluation attempts per conversation, each retaining the evaluator's existing one-repair policy. Running attempts are reserved in SQLite before provider calls. Restart marks unfinished reservations interrupted and consumes their original budget; completed conversations are never rerun. Missing provider configuration leaves resumed work pending. Exact duplicate active starts reattach; overlapping starts are rejected. Run one API process per database. + +`POST /api/evaluations` accepts additive `retryFailedOnly: true`, selecting only latest failures on the requested checklist and bypassing result reuse. Job status adds terminal `partial`; `succeeded`, `failed`, `retrying` describe conversations, while `evaluationIds` includes all append-only attempts. `completed` counts terminal conversations, not attempts. The API checks conversation scope before starting/retrying or returning job details. + +Failed attempts retain known token usage, prompt provenance, elapsed time, validation diagnostics and accepted partial facts internally; partial facts never become a score. Unknown spend after interruption/network loss is not fabricated. Web scores, analytics and review state prefer the latest successful evaluation, while failed latest attempts remain visible and retryable. Checklist and prompt versions are displayed; a failed run on a new checklist never silently relabels an older result. diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index d2712b5..67c8ae7 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -43,3 +43,10 @@ Export from the evaluation snapshot **before rehearsing critical-flag correction ## Dynamics 365 (HTML web resource) The guide asks for a UI that can later be adapted as a Dynamics 365 HTML component. Prepared, not exercised in a real Dynamics org: the build uses relative asset URLs (`base: './'`), routing is hash-based (no server rewrites), and the API origin is configurable. To embed: build with `VITE_API_BASE_URL=https://`, upload `apps/web/dist/index.html` and `dist/assets/*` as web resources keeping the `assets/` folder layout, and start the API with `CORS_ORIGIN=https://.crm.dynamics.com`. The API must be reachable over HTTPS from the browser. + + +## Recovering failed evaluations + +Use **Повторить неудавшиеся** on the dialogs page, or the retry action above a preserved previous successful evaluation. Only failed conversations are submitted, grouped by their original checklist. Each job has a bounded automatic retry and reports ready/error/retrying counts; `partial` means some conversations exhausted retries. Old successes and failure history remain intact. Interrupted jobs resume on API restart; restore missing provider configuration before restarting pending work. Do not run two API processes against the same database. + +Failed usage is retained for new attempts when the provider returned counters; historical failures and interrupted calls can still have unknown spend. The historical cost report remains unchanged. diff --git a/docs/superpowers/plans/2026-11-08-evaluation-recovery.md b/docs/superpowers/plans/2026-11-08-evaluation-recovery.md new file mode 100644 index 0000000..4a13503 --- /dev/null +++ b/docs/superpowers/plans/2026-11-08-evaluation-recovery.md @@ -0,0 +1,13 @@ +# Evaluation recovery implementation plan + +Goal: every conversation keeps its valid evaluation available while failed work can be retried safely, with observable outcomes and spend. + +Architecture: keep append-only evaluation attempts in SQLite. A job owns a bounded set of attempts per conversation and derives success/failure/retry counts from its own attempt IDs. Resume uses persisted attempts and timestamps, never reevaluating completed conversations. The web distinguishes its displayed successful result from the newest attempt and warns about checklist/version differences. + +Constraints: retain strict evidence validation, original results and transcript order; no model switching, invented grades or reference-label changes. One isolated branch for #83. Existing mock and HTTP adapters remain compatible. Execute inline; no coding delegation. + +1. Reproduce consultation contradictions with fictional transcripts. Strengthen the extraction question and repair feedback with exact request/evidence indices; keep contradictory facts rejected. Verify semantic and evaluator tests before live retry. +2. Extend shared job contract with outcome counts and a partial terminal state. Add optional evaluation attempt diagnostics. Add only nullable/defaulted SQLite columns. Implement append-only bounded attempts, restart-safe retry delay, duplicate launch protection and retry-failed endpoint scoped to permitted conversations. Verify restart, failure/success, exhausted retry, authorization and unchanged successful results. +3. Retain accumulated usage, latency, provider version and validation diagnostics on every failure; count provider responses without tool calls/refusals/truncation as well. Store accepted partial facts internally without treating them as a completed score. Verify exact token totals on mixed successful/failed request slices. +4. Add a shared successful-result selector, separate latest-attempt state, visible failure/staleness notices and a retry-failed action using the existing evaluation-start adapter. Make queue/statistics/review state consistently use valid results while reporting failed newest attempts separately. Verify mock interactions, checklist changes, immutable originals and polling of partial jobs. +5. Run typecheck, all tests and build; inspect the diff, update architecture/runbook and document residual limits. Open PR with self-review, pass both CI platforms, merge. Back up live SQLite using SQLite backup, retry only affected conversations with the checked build and verify 75 usable evaluations plus their provenance. Preserve prior attempts and report new cost separately from the historical measurement. diff --git a/packages/contracts/src/api.ts b/packages/contracts/src/api.ts index 5c06b41..f8ff4e3 100644 --- a/packages/contracts/src/api.ts +++ b/packages/contracts/src/api.ts @@ -16,12 +16,17 @@ export const StartEvaluationInputSchema = z.object({ force: z.boolean().optional(), /** Compatibility alias used by the stability runner. Same behavior as force. */ fresh: z.boolean().optional(), + /** Select only conversations whose latest attempt on this checklist failed. */ + retryFailedOnly: z.boolean().optional(), }); export type StartEvaluationInput = z.infer; export const JobSchema = z.object({ id: z.string().min(1), - status: EvaluationStatusSchema, + status: z.enum(['pending', 'running', 'completed', 'partial', 'failed']), + succeeded: z.number().int().nonnegative().optional(), + failed: z.number().int().nonnegative().optional(), + retrying: z.number().int().nonnegative().optional(), completed: z.number().int().nonnegative(), total: z.number().int().nonnegative(), /** v0.1 addition: how to get from a job to its evaluations. Filled as they are created. */ diff --git a/packages/contracts/src/domain.ts b/packages/contracts/src/domain.ts index cd3e426..a4b3505 100644 --- a/packages/contracts/src/domain.ts +++ b/packages/contracts/src/domain.ts @@ -229,6 +229,12 @@ export const EvaluationSchema = z.object({ createdAt: z.string().optional(), provenance: ProvenanceSchema.optional(), error: z.string().optional(), + diagnostics: z.object({ + jobId: z.string().optional(), + attempt: z.number().int().positive().optional(), + retryable: z.boolean().optional(), + calls: z.array(z.object({ criteria: z.array(z.string()), attempt: z.number().int().positive(), problems: z.array(z.string()) })), + }).optional(), }); export type Evaluation = z.infer; diff --git a/packages/contracts/src/evaluation-selection.ts b/packages/contracts/src/evaluation-selection.ts new file mode 100644 index 0000000..b0c907a --- /dev/null +++ b/packages/contracts/src/evaluation-selection.ts @@ -0,0 +1,14 @@ +import type { Evaluation } from './domain.js'; + +/** Input is in creation order, as returned by listEvaluations. Failed attempts never replace valid scores. */ +export function evaluationMaps(evaluations: readonly Evaluation[]) { + const attempts = new Map(); + const successful = new Map(); + for (const e of evaluations) { + attempts.set(e.conversationId, e); + if (e.status === 'completed') successful.set(e.conversationId, e); + } + const preferred = new Map(attempts); + for (const [id, e] of successful) preferred.set(id, e); + return { attempts, successful, preferred }; +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index b289d6b..4b6353e 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -6,3 +6,4 @@ export * from './bundle.js'; export * from './checklist.js'; export * from './roles.js'; export * from './team.js'; +export * from './evaluation-selection.js'; diff --git a/packages/contracts/test/evaluation-selection.test.ts b/packages/contracts/test/evaluation-selection.test.ts new file mode 100644 index 0000000..722c0d8 --- /dev/null +++ b/packages/contracts/test/evaluation-selection.test.ts @@ -0,0 +1,13 @@ +import { expect, it } from 'vitest'; +import { evaluationMaps, type Evaluation } from '../src/index.js'; +const original: Evaluation = { id: 'good', conversationId: 'a', checklistVersionId: 'v1', status: 'completed', originalResults: [], finalResults: [], originalTotal: 50, finalTotal: 60, seriousViolation: false }; +it('keeps successful scores, human changes and originals visible after a failed rerun or changed checklist', () => { + const failure: Evaluation = { ...original, id: 'failed', checklistVersionId: 'v2', status: 'failed', originalResults: [], finalResults: [], originalTotal: null, finalTotal: null }; + const maps = evaluationMaps([original, failure]); + expect(maps.attempts.get('a')).toBe(failure); + expect(maps.preferred.get('a')).toBe(original); + expect(maps.preferred.get('a')).toMatchObject({ originalTotal: 50, finalTotal: 60, checklistVersionId: 'v1' }); + const recovered = { ...original, id: 'recovered', checklistVersionId: 'v2' }; + expect(evaluationMaps([original, failure, recovered]).preferred.get('a')).toBe(recovered); + expect(evaluationMaps([failure]).preferred.get('a')).toBe(failure); +});