Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 56 additions & 7 deletions layers/registry/server/utils/repository-purpose-effect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { getRawFile, getRepoSummary, getTree } from './github-client'
import {
classifyRepositoryPurpose,
decideRepositoryPurposeAdmission,
parseAiGatewayUserInputError,
REPOSITORY_PURPOSE_MODEL,
REPOSITORY_PURPOSE_PROMPT_VERSION,
REPOSITORY_PURPOSE_REFRESH_SECONDS,
Expand All @@ -14,14 +15,18 @@ import { markRepoMissing } from './sync-repo'
export type RepositoryPurposeJudge = (state: RepositoryPurposeEvidence) => Promise<unknown>
export interface RepositoryIdentity { owner: string, repo: string }
export interface RepositoryPurposeSourceMissing { _tag: 'source_missing', status: 404 | 410 }
export type RepositoryPurposeRefresh = RepositoryPurposeFinding | RepositoryPurposeSourceMissing
export interface RepositoryPurposeInputRejected { _tag: 'input_rejected', reason: string }
export type RepositoryPurposeRefresh = RepositoryPurposeFinding | RepositoryPurposeSourceMissing | RepositoryPurposeInputRejected

export async function listRepositoryPurposeCandidates(db: D1Database, now: number): Promise<RepositoryIdentity[]> {
// Completed jobs are retained in `jobs` forever, so a correlated read over
// that table walks every finished classification for every candidate. Active
// jobs are bounded by in-flight work and reachable through the partial
// idx_jobs_active index, and terminal failures are moved to `failed_jobs`,
// where the one day retry wait is a failed_at index seek.
// where the one day retry wait is a failed_at index seek. A gateway user
// input error never clears by retrying the same evidence, so its recorded
// rejection in `repository_purpose_input_errors` blocks until the source
// pushes, the prompt changes, or the model changes.
const blocking = await db.prepare(`
SELECT json_extract(payload,'$.owner') AS owner, json_extract(payload,'$.repo') AS repo
FROM jobs INDEXED BY idx_jobs_active
Expand All @@ -38,6 +43,12 @@ export async function listRepositoryPurposeCandidates(db: D1Database, now: numbe
WHERE r.broken_since IS NULL AND r.repo_skill_count>0
AND (p.owner IS NULL OR p.prompt_version!=?1 OR p.model_id!=?3 OR p.evaluated_at<?2 OR r.pushed_at>p.evaluated_at)
AND NOT EXISTS (SELECT 1 FROM json_each(?4) AS b WHERE b.value=r.owner||'/'||r.repo)
AND NOT EXISTS (
SELECT 1 FROM repository_purpose_input_errors e
WHERE e.owner=r.owner AND e.repo=r.repo
AND e.prompt_version=?1 AND e.model_id=?3
AND COALESCE(r.pushed_at,0)<=e.failed_at
)
ORDER BY r.tree_truncated_at IS NOT NULL DESC, r.repo_skill_count>100 DESC,
EXISTS(SELECT 1 FROM skills s WHERE s.owner=r.owner AND s.repo=r.repo) DESC,
COALESCE(p.evaluated_at,0),r.owner,r.repo LIMIT 25
Expand Down Expand Up @@ -97,6 +108,31 @@ export async function persistRepositoryPurpose(db: D1Database, finding: Reposito
evaluated_at=excluded.evaluated_at
WHERE excluded.evaluated_at >= repository_purpose.evaluated_at
`).bind(finding.evidence.owner, finding.evidence.repo, finding.purpose, finding.probability, finding.reason, finding.model, REPOSITORY_PURPOSE_MODEL, finding.sourceCommit, finding.promptVersion, JSON.stringify(finding.evidence), JSON.stringify(finding.answer), now).run()
// A recorded gateway rejection describes evidence the next finding replaced,
// so the classification succeeding clears it instead of leaving a stale block.
await db.prepare('DELETE FROM repository_purpose_input_errors WHERE owner=? AND repo=?')
.bind(finding.evidence.owner, finding.evidence.repo)
.run()
}

/**
* A recorded gateway rejection outlives the failed job row, which retention
* prunes after thirty days. It blocks scheduling until the repository pushes,
* the prompt changes, or the model changes.
*/
export async function persistRepositoryPurposeInputError(
db: D1Database,
input: RepositoryIdentity,
outcome: { code: number, reason: string },
now: number,
): Promise<void> {
await db.prepare(`
INSERT INTO repository_purpose_input_errors (owner,repo,code,reason,prompt_version,model_id,failed_at)
VALUES (?,?,?,?,?,?,?)
ON CONFLICT(owner,repo) DO UPDATE SET
code=excluded.code,reason=excluded.reason,prompt_version=excluded.prompt_version,
model_id=excluded.model_id,failed_at=excluded.failed_at
`).bind(input.owner, input.repo, outcome.code, outcome.reason, REPOSITORY_PURPOSE_PROMPT_VERSION, REPOSITORY_PURPOSE_MODEL, now).run()
}

export async function refreshRepositoryPurpose(deps: {
Expand All @@ -120,11 +156,22 @@ export async function refreshRepositoryPurpose(deps: {
if (cached) {
return { _tag: 'classified', purpose: cached.purpose, probability: cached.probability, reason: cached.reason, model: cached.model, sourceCommit: cached.source_commit, promptVersion: cached.prompt_version, evidence: JSON.parse(cached.evidence), answer: JSON.parse(cached.answer) }
}
const result = await classifyRepositoryPurpose(evidence, deps.judge)
if (result._tag === 'rejected')
throw new Error(`Repository purpose classification failed: ${result.reason}`)
await persistRepositoryPurpose(deps.db, result, now)
return result
let classified: RepositoryPurposeFinding | { _tag: 'rejected', reason: 'invalid_answer' }
try {
classified = await classifyRepositoryPurpose(evidence, deps.judge)
}
catch (error) {
const rejected = parseAiGatewayUserInputError(error)
if (!rejected)
throw error
const reason = `ai gateway ${rejected.code}: user input error`
await persistRepositoryPurposeInputError(deps.db, input, { code: rejected.code, reason }, now)
return { _tag: 'input_rejected', reason }
}
if (classified._tag === 'rejected')
throw new Error(`Repository purpose classification failed: ${classified.reason}`)
await persistRepositoryPurpose(deps.db, classified, now)
return classified
}

export async function checkRepositoryPurposeAdmission(
Expand All @@ -144,5 +191,7 @@ export async function checkRepositoryPurposeAdmission(
const finding = await classify()
if (finding._tag === 'source_missing')
return { _tag: 'held' as const, reason: `repo fetch ${finding.status}` }
if (finding._tag === 'input_rejected')
return { _tag: 'held' as const, reason: finding.reason }
return decideRepositoryPurposeAdmission({ purpose: finding.purpose, hasStoredSkills: false, humanEligible: false, ownerVerified: false })
}
16 changes: 16 additions & 0 deletions layers/registry/server/utils/repository-purpose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ const providerResponseSchema = z.union([
z.object({ state: z.literal('Completed'), result: responseSchema }).transform(response => response.result),
])

/**
* The AI gateway names a deterministic rejection `User Input Error`: the same
* input reproduces it on every attempt, so retrying the identical evidence
* burns the job's attempts for nothing. Measured in production:
* `AiGatewayError: 7003: User Input Error`. A push, a prompt change, or a
* model change produces different input, and only those are worth a retry.
* Everything else, such as the 7005 billing error, stays retryable.
*/
const GATEWAY_USER_INPUT_ERROR = /(?:AiGatewayError:|\[AI\] API error)\s*(\d+):\s*User Input Error/

export function parseAiGatewayUserInputError(error: unknown): { code: number } | null {
const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error)
const match = text.match(GATEWAY_USER_INPUT_ERROR)
return match ? { code: Number(match[1]) } : null
}

export interface RepositoryPurposeFinding {
_tag: 'classified'
purpose: RepositoryPurpose
Expand Down
16 changes: 16 additions & 0 deletions migrations/0166_repository_purpose_input_errors.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- A purpose classification the AI gateway rejects as a user input error
-- reproduces for the same evidence, so re-enqueueing it daily only burned the
-- job's five attempts (boshi-xixixi/traeskill, seven consecutive days). The
-- recorded rejection blocks scheduling until the repository pushes, the
-- prompt changes, or the model changes. Transient gateway errors, such as the
-- 7005 billing error, never write a row and keep their normal retry clock.
CREATE TABLE repository_purpose_input_errors (
owner TEXT NOT NULL,
repo TEXT NOT NULL,
code INTEGER NOT NULL,
reason TEXT NOT NULL CHECK (length(trim(reason)) > 0),
prompt_version TEXT NOT NULL,
model_id TEXT NOT NULL,
failed_at INTEGER NOT NULL,
PRIMARY KEY (owner, repo)
);
7 changes: 7 additions & 0 deletions server/jobs/registry/repository-purpose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ export default defineJob({
await ctx.fail(`repo fetch ${result.status}`)
return
}
if (result._tag === 'input_rejected') {
// The gateway rejects this evidence on every attempt, and the recorded
// rejection stops the scheduler re-enqueueing it until the source
// pushes, the prompt changes, or the model changes.
await ctx.fail(result.reason)
return
}
emitOperationalEvent(createWideEvent({ operation: 'repository-purpose', outcome: result.purpose, repo: `${input.owner}/${input.repo}` }))
ctx.reportStats?.({ rowsFetched: 1, rowsInserted: 1 })
},
Expand Down
67 changes: 66 additions & 1 deletion test/unit/repository-purpose-effect.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { SqliteD1 } from './helpers/d1-sqlite'
import { describe, expect, it, vi } from 'vitest'
import { classifyRepositoryPurpose, REPOSITORY_PURPOSE_REFRESH_SECONDS } from '../../layers/registry/server/utils/repository-purpose'
import { classifyRepositoryPurpose, REPOSITORY_PURPOSE_MODEL, REPOSITORY_PURPOSE_PROMPT_VERSION, REPOSITORY_PURPOSE_REFRESH_SECONDS } from '../../layers/registry/server/utils/repository-purpose'
import { checkRepositoryPurposeAdmission, listRepositoryPurposeCandidates, persistRepositoryPurpose, refreshRepositoryPurpose } from '../../layers/registry/server/utils/repository-purpose-effect'
import { allMigrations, createSqliteD1 } from './helpers/d1-sqlite'

Expand Down Expand Up @@ -48,6 +48,71 @@ describe('purpose records', () => {
finally { sqlite.close() }
})

/**
* The gateway rejects the same evidence with 7003 on every attempt, so the
* daily scheduler re-enqueued the job and dead-lettered its five attempts
* each day. The recorded rejection must outlast the one day failed_jobs
* wait and lift when the source pushes new evidence.
*/
it('records a permanent gateway input rejection and stops scheduling its purpose', async () => {
const sqlite = createSqliteD1(allMigrations())
const judgeMock = vi.fn(() => {
throw new Error('AiGatewayError: 7003: User Input Error')
})
const deps = { db: sqlite.db, readEvidence: async () => evidence, judge: judgeMock }
try {
sqlite.raw.exec(`
INSERT INTO repos(owner,repo,repo_skill_count) VALUES ('org','directory',3);
INSERT INTO skills(owner,repo,name,slug,display_name) VALUES ('org','directory','review','org/review','Review');
`)
await expect(refreshRepositoryPurpose(deps, evidence, 1000))
.resolves
.toEqual({ _tag: 'input_rejected', reason: 'ai gateway 7003: user input error' })
expect(judgeMock).toHaveBeenCalledTimes(1)
expect(sqlite.raw.prepare(`SELECT code,reason,prompt_version,model_id,failed_at FROM repository_purpose_input_errors WHERE owner='org' AND repo='directory'`).get())
.toEqual({ code: 7003, reason: 'ai gateway 7003: user input error', prompt_version: REPOSITORY_PURPOSE_PROMPT_VERSION, model_id: REPOSITORY_PURPOSE_MODEL, failed_at: 1000 })
expect(sqlite.raw.prepare('SELECT broken_since FROM repos').get()).toEqual({ broken_since: null })
expect(sqlite.raw.prepare('SELECT sync_status FROM skills').get()).toEqual({ sync_status: null })
expect(await listRepositoryPurposeCandidates(sqlite.db, 200000)).toEqual([])

// A push means new evidence, so the repository becomes a candidate
// again, and a successful classification clears the rejection.
sqlite.raw.exec('UPDATE repos SET pushed_at=2000')
expect(await listRepositoryPurposeCandidates(sqlite.db, 100000)).toEqual([{ owner: 'org', repo: 'directory' }])
await expect(refreshRepositoryPurpose({ ...deps, judge }, evidence, 3000))
.resolves
.toMatchObject({ _tag: 'classified', purpose: 'directory' })
expect(sqlite.raw.prepare(`SELECT COUNT(*) AS n FROM repository_purpose_input_errors WHERE owner='org' AND repo='directory'`).get())
.toEqual({ n: 0 })
}
finally { sqlite.close() }
})

it('keeps a transient gateway error retryable without recording a rejection', async () => {
const sqlite = createSqliteD1(allMigrations())
const deps = {
db: sqlite.db,
readEvidence: async () => evidence,
judge: () => { throw new Error('AiGatewayError: 7005: Billing Error') },
}
try {
sqlite.raw.exec('INSERT INTO repos(owner,repo,repo_skill_count) VALUES (\'org\',\'directory\',3)')
await expect(refreshRepositoryPurpose(deps, evidence, 1000)).rejects.toThrow('AiGatewayError: 7005: Billing Error')
expect(sqlite.raw.prepare('SELECT COUNT(*) AS n FROM repository_purpose_input_errors').get()).toEqual({ n: 0 })
expect(await listRepositoryPurposeCandidates(sqlite.db, 200000)).toEqual([{ owner: 'org', repo: 'directory' }])
}
finally { sqlite.close() }
})

it('holds an admission while the gateway rejects the classification input', async () => {
const sqlite = createSqliteD1(allMigrations())
try {
expect(await checkRepositoryPurposeAdmission(sqlite.db, { ...evidence, ownerVerified: false }, async () => ({ _tag: 'input_rejected', reason: 'ai gateway 7003: user input error' })))
.toEqual({ _tag: 'held', reason: 'ai gateway 7003: user input error' })
}
finally { sqlite.close() }
})

it.each(['official', 'trusted-author', 'trusted-curator'])('retains a named %s decision for an organization', async (tier) => {
const sqlite = createSqliteD1(allMigrations())
const classify = vi.fn()
Expand Down
59 changes: 59 additions & 0 deletions test/unit/repository-purpose-job.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,40 @@ import { allMigrations, createSqliteD1 } from './helpers/d1-sqlite'

vi.hoisted(() => vi.stubGlobal('defineJob', <T>(definition: T) => definition))

const headCommitSha = 'c'.repeat(40)
const headTreeSha = 'd'.repeat(40)

/**
* GitHub answers for one repository with a README, so the purpose evidence
* read succeeds and the failure can only come from the AI call.
*/
function stubGithubSource(): void {
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
const url = String(input)
if (url.startsWith('https://api.github.com/graphql')) {
return Response.json({ data: { repository: {
databaseId: 1,
name: 'gone',
nameWithOwner: 'org/gone',
url: 'https://github.com/org/gone',
owner: { login: 'org' },
description: 'A repository of skills',
stargazerCount: 1,
forkCount: 0,
pushedAt: '2026-01-01T00:00:00Z',
createdAt: '2026-01-01T00:00:00Z',
isArchived: false,
isFork: false,
isPrivate: false,
defaultBranchRef: { name: 'main', target: { oid: headCommitSha, tree: { oid: headTreeSha } } },
} } })
}
if (url.includes('/git/trees/'))
return Response.json({ sha: headTreeSha, tree: [{ path: 'README.md', type: 'blob', sha: 'e'.repeat(40) }], truncated: false })
return new Response('A repository of skills.', { status: 200 })
}))
}

describe('repository purpose job', () => {
afterEach(() => vi.unstubAllGlobals())

Expand Down Expand Up @@ -40,4 +74,29 @@ describe('repository purpose job', () => {
}
finally { sqlite.close() }
})

/**
* The gateway rejects the classification input deterministically, so the
* job must end on its first attempt and its recorded rejection must stop
* the scheduler re-enqueueing it the next hour.
*/
it('ends a permanent gateway input rejection on its first attempt and stops scheduling it', async () => {
const sqlite = createSqliteD1(allMigrations())
const fail = vi.fn()
stubGithubSource()
const run = vi.fn(() => {
throw new Error('AiGatewayError: 7003: User Input Error')
})
try {
sqlite.raw.exec('INSERT INTO repos(owner,repo,repo_skill_count) VALUES (\'org\',\'gone\',3)')
const ctx = { db: sqlite.db, env: { AI: { run } }, fail } as unknown as Parameters<typeof job.handle>[1]
await job.handle({ owner: 'org', repo: 'gone' }, ctx)
expect(fail).toHaveBeenCalledExactlyOnceWith('ai gateway 7003: user input error')
expect(run).toHaveBeenCalledTimes(1)
expect(sqlite.raw.prepare(`SELECT code FROM repository_purpose_input_errors WHERE owner='org' AND repo='gone'`).get())
.toEqual({ code: 7003 })
expect(await listRepositoryPurposeCandidates(sqlite.db, Math.floor(Date.now() / 1000) + 2 * 86400)).toEqual([])
}
finally { sqlite.close() }
})
})
Loading