From 9ddddd2a0fd05b0f05ab444f01f7587cd96d2438 Mon Sep 17 00:00:00 2001 From: Tom Beckenham <34339192+tombeckenham@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:50:57 +1100 Subject: [PATCH 1/2] Probe facts in the Worker and record them in D1, served after two agreeing runs Moves live fact probing (#717) from committed record files and the weekly PR job into an hourly Worker cron that appends probe_observations rows. A value is served only when the two newest decided observations from separate runs agree. Removes records/groq.ts, the weekly workflow and the script's --write; the script is now a read-only dry run. The hand-written OpenCode Go route records stay as a marked legacy path. --- .changeset/probes-in-d1.md | 5 + .source/workflows/probe.ts | 89 - CLAUDE.md | 34 +- drizzle/0022_probe_observations.sql | 15 + drizzle/meta/0022_snapshot.json | 2215 +++++++++++++++++ drizzle/meta/_journal.json | 7 + openapi.json | 67 +- packages/client/src/generated/index.ts | 6 + packages/client/src/generated/sdk.gen.ts | 25 + packages/client/src/generated/types.gen.ts | 44 +- scripts/probe.ts | 234 +- src/db/schema.ts | 33 + src/lib/agent-auth.worker.test.ts | 1 + src/lib/auth.ts | 1 + src/routeTree.gen.ts | 21 + src/routes/v1/admin/probes.$provider.ts | 42 + src/server/ingest/poll-models.ts | 8 +- src/server/ingest/poll-models.worker.test.ts | 49 +- src/server/ingest/probe-facts.ts | 458 ++++ src/server/ingest/probe-facts.worker.test.ts | 257 ++ src/server/openapi.ts | 31 +- .../providers/probes/chat-completions.test.ts | 127 +- .../providers/probes/chat-completions.ts | 104 +- src/server/providers/probes/compare.ts | 13 - src/server/providers/probes/groq.ts | 13 - src/server/providers/probes/index.ts | 175 +- src/server/providers/probes/opencode-go.ts | 9 + src/server/providers/probes/probes.test.ts | 29 +- src/server/providers/probes/records/groq.ts | 197 -- src/server/providers/probes/types.ts | 36 +- src/server/status.ts | 15 +- src/worker.ts | 11 + wrangler.jsonc | 3 + 33 files changed, 3621 insertions(+), 753 deletions(-) create mode 100644 .changeset/probes-in-d1.md delete mode 100644 .source/workflows/probe.ts create mode 100644 drizzle/0022_probe_observations.sql create mode 100644 drizzle/meta/0022_snapshot.json create mode 100644 src/routes/v1/admin/probes.$provider.ts create mode 100644 src/server/ingest/probe-facts.ts create mode 100644 src/server/ingest/probe-facts.worker.test.ts delete mode 100644 src/server/providers/probes/groq.ts delete mode 100644 src/server/providers/probes/records/groq.ts diff --git a/.changeset/probes-in-d1.md b/.changeset/probes-in-d1.md new file mode 100644 index 00000000..3457d59f --- /dev/null +++ b/.changeset/probes-in-d1.md @@ -0,0 +1,5 @@ +--- +'@modelschemas/client': patch +--- + +Adds `listProbeObservations` (`GET /v1/admin/probes/{provider}`, admin only, read-only): the Worker's live probe observations with their evidence and whether each is served. The `staleProbes` and schema `probe-verified` descriptions now say probed facts are re-verified by the Worker, not by a committed record. diff --git a/.source/workflows/probe.ts b/.source/workflows/probe.ts deleted file mode 100644 index 0efd258b..00000000 --- a/.source/workflows/probe.ts +++ /dev/null @@ -1,89 +0,0 @@ -// Weekly live probes (issue #717). Runs `pnpm run probe -- -// --write` for each chat probe provider, and opens a pull request on -// `probe/weekly` when a record file changed. A person reviews and merges -// it; nothing here merges. No change, no pull request. -// -// Each provider's key is an optional secret: with none, the probe script -// prints `skip : is not set` and the run goes on. The -// script caps its own requests (MAX_PROBE_REQUESTS) and never prints a key. -// -// Admin setup (people only), one per provider below: -// src secret set GROQ_API_KEY --env development --host api.groq.com --header Authorization < groq-key.txt -// -// Opt a provider in: add it to `chatProbes` in -// src/server/providers/probes/index.ts, then add its id to PROVIDERS, its -// key to `secrets` and its API host to `egress` here. -import { - defineWorkflow, - forge, - manual, - schedule, - setup, -} from '@tanstack-source/ci' - -const PROVIDERS = ['groq'] -const BRANCH = 'probe/weekly' -const RECORDS = 'src/server/providers/probes/records' - -export default defineWorkflow('probe', { - // Mondays 03:17 UTC. - on: [schedule('17 3 * * 1'), manual()], -}).job('probe', { - secrets: { GROQ_API_KEY: { optional: true } }, - egress: ['registry.npmjs.org', 'api.groq.com'], - permissions: { push: [BRANCH], pulls: 'create' }, - timeoutMinutes: 15, - steps: [ - setup.node(), - setup.pnpm(), - { name: 'Install', run: 'pnpm install --frozen-lockfile' }, - { - name: 'Probe', - do: async (ctx) => { - for (const provider of PROVIDERS) { - await ctx.sh`pnpm run probe -- ${provider} --write --skip-missing-key` - } - }, - }, - { - name: 'Open the pull request', - do: async (ctx) => { - // Only main feeds the weekly pull request: a manual run on another - // ref would push that ref's commits into it. - const ref = ctx.env.TANSTACK_SOURCE_REF ?? '' - if (ref !== 'main' && ref !== 'refs/heads/main') { - ctx.summary( - `Run on ${ref || 'an unknown ref'}, not main: records left unpushed, no pull request.`, - ) - return - } - // A git failure fails the job; it never reads as "no change". - const status = await ctx.sh - .nothrow`git status --porcelain -- ${RECORDS}` - if (status.code !== 0) { - throw new Error(`git status failed: ${status.stderr}`) - } - if (status.stdout.trim() === '') { - ctx.summary('No probe record changed: no pull request.') - return - } - await ctx.sh`git switch -C ${BRANCH}` - await ctx.sh`git add -- ${RECORDS}` - await ctx.sh`git -c user.name=modelschemas-probe -c user.email=probe@modelschemas.invalid commit -m ${'Refresh probe records'}` - await ctx.sh`git push --force origin ${`HEAD:refs/heads/${BRANCH}`}` - const client = forge(ctx) - const [open] = await client.pulls.list({ head: BRANCH, state: 'open' }) - if (open) { - ctx.summary(`Updated the open probe pull request #${open.number}.`) - return - } - await client.pulls.create({ - title: 'Refresh probe records', - head: BRANCH, - base: 'main', - body: 'The weekly probe run (.source/workflows/probe.ts) changed a record under src/server/providers/probes/records/. Each record holds the status and error message that stated its value. Review the evidence, then merge.', - }) - }, - }, - ], -}) diff --git a/CLAUDE.md b/CLAUDE.md index 0389769f..2c7d4bd1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -240,23 +240,31 @@ ones). entry. A stored row's first `releasedAt`, `providerMetadata` or `maker` is written with no `model.updated`. Migration `0014` is a drizzle custom migration that converted the stored lists. A fact the provider's docs do not state can - still come from a live API check: one file per provider under - `src/server/providers/probes/`, derivation `probe-verified`, dated - `verifiedAt`. The adapter binds that fact only for the exact model and - route the record names. A record older than 90 days stays served; - `GET /v1/status` counts it on `staleProbes`. Re-run with - `pnpm run probe -- [--write]` (not the 15-minute - poll). The script reads the provider key from the environment or Doppler - and never prints it. The generic `chat/completions` probe - (`probes/chat-completions.ts`, #717) states `maxOutput`, + still come from a live API check, derivation `probe-verified`, dated + `verifiedAt`, bound only to the exact model and route observed. Probed + facts live in D1, never in source (#717): the Worker's own probe cron + (`PROBE_CRON`, hourly at :07, `src/server/ingest/probe-facts.ts`) + appends one `probe_observations` row per request it sent (value null + when the response stated nothing). It probes a chat row of an enabled + provider (`chatProbes` in `probes/index.ts`) once when a probeable fact + is empty and unobserved, re-probes an unconfirmed value next run, and + re-verifies anything `REVERIFY_AFTER_DAYS` (7) old, under + `PROBE_REQUEST_BUDGET` (12) and `PROBE_PROVIDER_BUDGET` (4) per + invocation. A value is served only when the two newest decided + observations, from separate runs, agree; the poll fills only empty facts + from them (`loadServedProbeFacts` → `withProbedFacts`). A missing key is + a logged skip; a `gateway` entry is never probed. Audit with + `GET /v1/admin/probes/{provider}[?model=]`. A served fact older than 90 + days stays served; `GET /v1/status` counts it on `staleProbes`. + `pnpm run probe -- ` is a read-only local dry run. + The classifier (`probes/chat-completions.ts`) states `maxOutput`, `replayReasoningContent` and `reasoning.mandatory` only from a 400/422 whose message a rule reads (fixtures of real bodies); a 2xx, auth, 429, 5xx or unread message records nothing. `reasoning.mandatory` needs the provider's `mandatoryRule` opt-in (per-model level list, no other - reasoning control). No rule writes `contextWindow` yet. `--write` writes - `probes/records/.ts` (never by hand); the poller fills only - empty facts from it (`withProbedFacts`). `.source/workflows/probe.ts` - runs it weekly and opens a PR on `probe/weekly` when a record changed. + reasoning control). No rule writes `contextWindow` yet. LEGACY: the + hand-written OpenCode Go route records (`probes/opencode-go.ts`) still + bind two routes; nothing re-dates them. - **sameAs links** (issues #199, #719, `src/server/ingest/model-identity.ts`): a row links to the row at another provider it is the same model as; never a copied fact. A stated link wins: adapters state the upstream diff --git a/drizzle/0022_probe_observations.sql b/drizzle/0022_probe_observations.sql new file mode 100644 index 00000000..32d0239a --- /dev/null +++ b/drizzle/0022_probe_observations.sql @@ -0,0 +1,15 @@ +CREATE TABLE `probe_observations` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `run_id` text NOT NULL, + `provider_id` text NOT NULL, + `raw_id` text NOT NULL, + `route` text NOT NULL, + `fact` text NOT NULL, + `value` text, + `status` integer NOT NULL, + `message` text NOT NULL, + `observed_at` integer NOT NULL, + FOREIGN KEY (`provider_id`) REFERENCES `providers`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `probe_observations_provider_model_idx` ON `probe_observations` (`provider_id`,`raw_id`,`fact`); \ No newline at end of file diff --git a/drizzle/meta/0022_snapshot.json b/drizzle/meta/0022_snapshot.json new file mode 100644 index 00000000..627739d2 --- /dev/null +++ b/drizzle/meta/0022_snapshot.json @@ -0,0 +1,2215 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "8ac08f33-d515-43f0-83cc-2c6920d458c1", + "prevId": "fe1dbfde-54a5-43e3-980f-d5c42eaca6bc", + "tables": { + "account": { + "name": "account", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "account_userId_idx": { + "name": "account_userId_idx", + "columns": ["user_id"], + "isUnique": false + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "agent": { + "name": "agent", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "mode": { + "name": "mode", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'delegated'" + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kid": { + "name": "kid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "jwks_url": { + "name": "jwks_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "agent_userId_idx": { + "name": "agent_userId_idx", + "columns": ["user_id"], + "isUnique": false + }, + "agent_hostId_idx": { + "name": "agent_hostId_idx", + "columns": ["host_id"], + "isUnique": false + }, + "agent_status_idx": { + "name": "agent_status_idx", + "columns": ["status"], + "isUnique": false + }, + "agent_kid_idx": { + "name": "agent_kid_idx", + "columns": ["kid"], + "isUnique": false + } + }, + "foreignKeys": { + "agent_user_id_user_id_fk": { + "name": "agent_user_id_user_id_fk", + "tableFrom": "agent", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "agent_host_id_agent_host_id_fk": { + "name": "agent_host_id_agent_host_id_fk", + "tableFrom": "agent", + "tableTo": "agent_host", + "columnsFrom": ["host_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "agent_capability_grant": { + "name": "agent_capability_grant", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "capability": { + "name": "capability", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "denied_by": { + "name": "denied_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "granted_by": { + "name": "granted_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "constraints": { + "name": "constraints", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "agentCapabilityGrant_agentId_idx": { + "name": "agentCapabilityGrant_agentId_idx", + "columns": ["agent_id"], + "isUnique": false + }, + "agentCapabilityGrant_capability_idx": { + "name": "agentCapabilityGrant_capability_idx", + "columns": ["capability"], + "isUnique": false + }, + "agentCapabilityGrant_grantedBy_idx": { + "name": "agentCapabilityGrant_grantedBy_idx", + "columns": ["granted_by"], + "isUnique": false + }, + "agentCapabilityGrant_status_idx": { + "name": "agentCapabilityGrant_status_idx", + "columns": ["status"], + "isUnique": false + } + }, + "foreignKeys": { + "agent_capability_grant_agent_id_agent_id_fk": { + "name": "agent_capability_grant_agent_id_agent_id_fk", + "tableFrom": "agent_capability_grant", + "tableTo": "agent", + "columnsFrom": ["agent_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "agent_capability_grant_denied_by_user_id_fk": { + "name": "agent_capability_grant_denied_by_user_id_fk", + "tableFrom": "agent_capability_grant", + "tableTo": "user", + "columnsFrom": ["denied_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "agent_capability_grant_granted_by_user_id_fk": { + "name": "agent_capability_grant_granted_by_user_id_fk", + "tableFrom": "agent_capability_grant", + "tableTo": "user", + "columnsFrom": ["granted_by"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "agent_host": { + "name": "agent_host", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_capabilities": { + "name": "default_capabilities", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kid": { + "name": "kid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "jwks_url": { + "name": "jwks_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enrollment_token_hash": { + "name": "enrollment_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enrollment_token_expires_at": { + "name": "enrollment_token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "agentHost_userId_idx": { + "name": "agentHost_userId_idx", + "columns": ["user_id"], + "isUnique": false + }, + "agentHost_kid_idx": { + "name": "agentHost_kid_idx", + "columns": ["kid"], + "isUnique": false + }, + "agentHost_enrollmentTokenHash_idx": { + "name": "agentHost_enrollmentTokenHash_idx", + "columns": ["enrollment_token_hash"], + "isUnique": false + }, + "agentHost_status_idx": { + "name": "agentHost_status_idx", + "columns": ["status"], + "isUnique": false + } + }, + "foreignKeys": { + "agent_host_user_id_user_id_fk": { + "name": "agent_host_user_id_user_id_fk", + "tableFrom": "agent_host", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "apikey": { + "name": "apikey", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "config_id": { + "name": "config_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'default'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "start": { + "name": "start", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refill_interval": { + "name": "refill_interval", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refill_amount": { + "name": "refill_amount", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_refill_at": { + "name": "last_refill_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "rate_limit_enabled": { + "name": "rate_limit_enabled", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": true + }, + "rate_limit_time_window": { + "name": "rate_limit_time_window", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 86400000 + }, + "rate_limit_max": { + "name": "rate_limit_max", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 10 + }, + "request_count": { + "name": "request_count", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": 0 + }, + "remaining": { + "name": "remaining", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_request": { + "name": "last_request", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "permissions": { + "name": "permissions", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "apikey_configId_idx": { + "name": "apikey_configId_idx", + "columns": ["config_id"], + "isUnique": false + }, + "apikey_referenceId_idx": { + "name": "apikey_referenceId_idx", + "columns": ["reference_id"], + "isUnique": false + }, + "apikey_key_idx": { + "name": "apikey_key_idx", + "columns": ["key"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "approval_request": { + "name": "approval_request", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_id": { + "name": "host_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capabilities": { + "name": "capabilities", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "user_code_hash": { + "name": "user_code_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "login_hint": { + "name": "login_hint", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "binding_message": { + "name": "binding_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "client_notification_token": { + "name": "client_notification_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "client_notification_endpoint": { + "name": "client_notification_endpoint", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "delivery_mode": { + "name": "delivery_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "interval": { + "name": "interval", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_polled_at": { + "name": "last_polled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "approvalRequest_agentId_idx": { + "name": "approvalRequest_agentId_idx", + "columns": ["agent_id"], + "isUnique": false + }, + "approvalRequest_hostId_idx": { + "name": "approvalRequest_hostId_idx", + "columns": ["host_id"], + "isUnique": false + }, + "approvalRequest_userId_idx": { + "name": "approvalRequest_userId_idx", + "columns": ["user_id"], + "isUnique": false + }, + "approvalRequest_status_idx": { + "name": "approvalRequest_status_idx", + "columns": ["status"], + "isUnique": false + } + }, + "foreignKeys": { + "approval_request_agent_id_agent_id_fk": { + "name": "approval_request_agent_id_agent_id_fk", + "tableFrom": "approval_request", + "tableTo": "agent", + "columnsFrom": ["agent_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "approval_request_host_id_agent_host_id_fk": { + "name": "approval_request_host_id_agent_host_id_fk", + "tableFrom": "approval_request", + "tableTo": "agent_host", + "columnsFrom": ["host_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "approval_request_user_id_user_id_fk": { + "name": "approval_request_user_id_user_id_fk", + "tableFrom": "approval_request", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "cache_meta": { + "name": "cache_meta", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "fetched_at": { + "name": "fetched_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stale_time": { + "name": "stale_time", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refreshing": { + "name": "refreshing", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "changes": { + "name": "changes", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subject_id": { + "name": "subject_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "changes_createdAt_idx": { + "name": "changes_createdAt_idx", + "columns": ["created_at"], + "isUnique": false + }, + "changes_providerId_idx": { + "name": "changes_providerId_idx", + "columns": ["provider_id"], + "isUnique": false + } + }, + "foreignKeys": { + "changes_provider_id_providers_id_fk": { + "name": "changes_provider_id_providers_id_fk", + "tableFrom": "changes", + "tableTo": "providers", + "columnsFrom": ["provider_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoints": { + "name": "endpoints", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "activity": { + "name": "activity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "request_content_type": { + "name": "request_content_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "response_content_types": { + "name": "response_content_types", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "endpoints_providerId_idx": { + "name": "endpoints_providerId_idx", + "columns": ["provider_id"], + "isUnique": false + } + }, + "foreignKeys": { + "endpoints_provider_id_providers_id_fk": { + "name": "endpoints_provider_id_providers_id_fk", + "tableFrom": "endpoints", + "tableTo": "providers", + "columnsFrom": ["provider_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "models": { + "name": "models", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "raw_id": { + "name": "raw_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "activity": { + "name": "activity", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "context_window": { + "name": "context_window", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "max_output": { + "name": "max_output", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "modalities": { + "name": "modalities", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pricing": { + "name": "pricing", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pricing_range": { + "name": "pricing_range", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "capabilities": { + "name": "capabilities", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "provider_metadata": { + "name": "provider_metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reasoning": { + "name": "reasoning", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "server_tools": { + "name": "server_tools", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "request_map": { + "name": "request_map", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "aliases": { + "name": "aliases", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "alias_of": { + "name": "alias_of", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upstream_provider": { + "name": "upstream_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upstream_raw_id": { + "name": "upstream_raw_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upstream_source": { + "name": "upstream_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "same_as_model_id": { + "name": "same_as_model_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "root_model_id": { + "name": "root_model_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "same_as_inference": { + "name": "same_as_inference", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fact_sources": { + "name": "fact_sources", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schema_endpoint_id": { + "name": "schema_endpoint_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "released_at": { + "name": "released_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "knowledge_cutoff": { + "name": "knowledge_cutoff", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "open_weights": { + "name": "open_weights", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "weights_url": { + "name": "weights_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "maker": { + "name": "maker", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "trains_on_request_data": { + "name": "trains_on_request_data", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "deprecated_at": { + "name": "deprecated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deprecation": { + "name": "deprecation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "models_providerId_idx": { + "name": "models_providerId_idx", + "columns": ["provider_id"], + "isUnique": false + }, + "models_providerId_rawId_idx": { + "name": "models_providerId_rawId_idx", + "columns": ["provider_id", "raw_id"], + "isUnique": false + }, + "models_activity_idx": { + "name": "models_activity_idx", + "columns": ["activity"], + "isUnique": false + }, + "models_sameAsModelId_idx": { + "name": "models_sameAsModelId_idx", + "columns": ["same_as_model_id"], + "isUnique": false + }, + "models_rootModelId_idx": { + "name": "models_rootModelId_idx", + "columns": ["root_model_id"], + "isUnique": false + }, + "models_maker_providerId_idx": { + "name": "models_maker_providerId_idx", + "columns": ["maker", "provider_id"], + "isUnique": false + } + }, + "foreignKeys": { + "models_provider_id_providers_id_fk": { + "name": "models_provider_id_providers_id_fk", + "tableFrom": "models", + "tableTo": "providers", + "columnsFrom": ["provider_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "models_same_as_model_id_models_id_fk": { + "name": "models_same_as_model_id_models_id_fk", + "tableFrom": "models", + "tableTo": "models", + "columnsFrom": ["same_as_model_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + }, + "models_root_model_id_models_id_fk": { + "name": "models_root_model_id_models_id_fk", + "tableFrom": "models", + "tableTo": "models", + "columnsFrom": ["root_model_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": { + "models_upstream_identity_pair": { + "name": "models_upstream_identity_pair", + "value": "(\"models\".\"upstream_provider\" IS NULL) = (\"models\".\"upstream_raw_id\" IS NULL)\n AND (\"models\".\"upstream_provider\" IS NULL) = (\"models\".\"upstream_source\" IS NULL)" + }, + "models_sameAs_not_self": { + "name": "models_sameAs_not_self", + "value": "\"models\".\"same_as_model_id\" != \"models\".\"id\"" + }, + "models_root_not_self": { + "name": "models_root_not_self", + "value": "\"models\".\"root_model_id\" != \"models\".\"id\"" + } + } + }, + "probe_observations": { + "name": "probe_observations", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "run_id": { + "name": "run_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "raw_id": { + "name": "raw_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "route": { + "name": "route", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fact": { + "name": "fact", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "observed_at": { + "name": "observed_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "probe_observations_provider_model_idx": { + "name": "probe_observations_provider_model_idx", + "columns": ["provider_id", "raw_id", "fact"], + "isUnique": false + } + }, + "foreignKeys": { + "probe_observations_provider_id_providers_id_fk": { + "name": "probe_observations_provider_id_providers_id_fk", + "tableFrom": "probe_observations", + "tableTo": "providers", + "columnsFrom": ["provider_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "provider_model_namespaces": { + "name": "provider_model_namespaces", + "columns": { + "namespace": { + "name": "namespace", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "provider_model_namespaces_providerId_idx": { + "name": "provider_model_namespaces_providerId_idx", + "columns": ["provider_id"], + "isUnique": false + } + }, + "foreignKeys": { + "provider_model_namespaces_provider_id_providers_id_fk": { + "name": "provider_model_namespaces_provider_id_providers_id_fk", + "tableFrom": "provider_model_namespaces", + "tableTo": "providers", + "columnsFrom": ["provider_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "provider_model_namespaces_namespace_provider_id_pk": { + "columns": ["namespace", "provider_id"], + "name": "provider_model_namespaces_namespace_provider_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "providers": { + "name": "providers", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "spec_source_url": { + "name": "spec_source_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "models_endpoint": { + "name": "models_endpoint", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "auth_env_var": { + "name": "auth_env_var", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_polled_at": { + "name": "last_polled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "makes_own_models": { + "name": "makes_own_models", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "schema_versions": { + "name": "schema_versions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "endpoint_id": { + "name": "endpoint_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content_hash": { + "name": "content_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schema": { + "name": "schema", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "spec_revision": { + "name": "spec_revision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_url": { + "name": "source_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "extractor_version": { + "name": "extractor_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "derivation": { + "name": "derivation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verified_at": { + "name": "verified_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "schema_versions_endpointId_kind_idx": { + "name": "schema_versions_endpointId_kind_idx", + "columns": ["endpoint_id", "kind"], + "isUnique": false + }, + "schema_versions_contentHash_idx": { + "name": "schema_versions_contentHash_idx", + "columns": ["content_hash"], + "isUnique": false + } + }, + "foreignKeys": { + "schema_versions_endpoint_id_endpoints_id_fk": { + "name": "schema_versions_endpoint_id_endpoints_id_fk", + "tableFrom": "schema_versions", + "tableTo": "endpoints", + "columnsFrom": ["endpoint_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "session": { + "name": "session", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "session_token_unique": { + "name": "session_token_unique", + "columns": ["token"], + "isUnique": true + }, + "session_userId_idx": { + "name": "session_userId_idx", + "columns": ["user_id"], + "isUnique": false + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_filter": { + "name": "provider_filter", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "active": { + "name": "active", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "subscriptions_agentId_idx": { + "name": "subscriptions_agentId_idx", + "columns": ["agent_id"], + "isUnique": false + } + }, + "foreignKeys": { + "subscriptions_agent_id_user_id_fk": { + "name": "subscriptions_agent_id_user_id_fk", + "tableFrom": "subscriptions", + "tableTo": "user", + "columnsFrom": ["agent_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscriptions_provider_filter_providers_id_fk": { + "name": "subscriptions_provider_filter_providers_id_fk", + "tableFrom": "subscriptions", + "tableTo": "providers", + "columnsFrom": ["provider_filter"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "user": { + "name": "user", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email_verified": { + "name": "email_verified", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "user_email_unique": { + "name": "user_email_unique", + "columns": ["email"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "verification": { + "name": "verification", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": ["identifier"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "webhook_deliveries": { + "name": "webhook_deliveries", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "change_id": { + "name": "change_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "last_response_code": { + "name": "last_response_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "webhook_deliveries_status_nextAttemptAt_idx": { + "name": "webhook_deliveries_status_nextAttemptAt_idx", + "columns": ["status", "next_attempt_at"], + "isUnique": false + }, + "webhook_deliveries_subscriptionId_idx": { + "name": "webhook_deliveries_subscriptionId_idx", + "columns": ["subscription_id"], + "isUnique": false + } + }, + "foreignKeys": { + "webhook_deliveries_subscription_id_subscriptions_id_fk": { + "name": "webhook_deliveries_subscription_id_subscriptions_id_fk", + "tableFrom": "webhook_deliveries", + "tableTo": "subscriptions", + "columnsFrom": ["subscription_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "webhook_deliveries_change_id_changes_id_fk": { + "name": "webhook_deliveries_change_id_changes_id_fk", + "tableFrom": "webhook_deliveries", + "tableTo": "changes", + "columnsFrom": ["change_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index f0d70f43..67cafba4 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -155,6 +155,13 @@ "when": 1795234603732, "tag": "0021_root_and_first_party", "breakpoints": true + }, + { + "idx": 22, + "version": "6", + "when": 1795243260242, + "tag": "0022_probe_observations", + "breakpoints": true } ] } diff --git a/openapi.json b/openapi.json index 7766c2da..9d9d6671 100644 --- a/openapi.json +++ b/openapi.json @@ -518,7 +518,7 @@ ], "responses": { "200": { - "description": "Self-contained JSON Schema ($defs-bundled) — or, with format=types, a TypeScript module — served with ETag. JSON responses carry `provenance` (upstream sourceUrl, sourceHash, fetchedAt, extractorVersion) so derivations are independently verifiable. `provenance.derivation` grades how the content was arrived at — `upstream-spec` and `generated` are re-derived every sync and self-heal. `probe-verified` is a live API call recorded in `src/server/providers/probes/.ts` on `provenance.verifiedAt` (`YYYY-MM-DD`). Re-run it with `pnpm run probe -- [--write]`. A record older than 90 days is still served; `GET /v1/status` counts those on `staleProbes`. `docs-derived` was never confirmed against the API. Both are point-in-time claims that can go stale.", + "description": "Self-contained JSON Schema ($defs-bundled) — or, with format=types, a TypeScript module — served with ETag. JSON responses carry `provenance` (upstream sourceUrl, sourceHash, fetchedAt, extractorVersion) so derivations are independently verifiable. `provenance.derivation` grades how the content was arrived at — `upstream-spec` and `generated` are re-derived every sync and self-heal. `probe-verified` is a live API call dated `provenance.verifiedAt` (`YYYY-MM-DD`): a route record in `src/server/providers/probes/.ts`, or, for a model fact, two agreeing observations the Worker recorded from its own requests. A probe older than 90 days is still served; `GET /v1/status` counts those on `staleProbes`. `docs-derived` was never confirmed against the API. Both are point-in-time claims that can go stale.", "content": { "application/json": { "schema": { @@ -895,6 +895,69 @@ } } }, + "/v1/admin/probes/{provider}": { + "get": { + "operationId": "listProbeObservations", + "summary": "Audit the live probe observations for a provider (admin only, read-only)", + "description": "Every `probe_observations` row the probe cron appended for this provider, newest first: model, route, fact, value (null when the response stated nothing), status, the provider message that is the evidence, observedAt, runId, and `served` (true for the two agreeing observations behind a served value). `?model=` narrows to one raw id.", + "parameters": [ + { + "name": "provider", + "in": "path", + "required": true, + "description": "Provider slug (see GET /v1/providers).", + "schema": { + "type": "string" + } + }, + { + "name": "model", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ], + "security": [ + { + "adminKey": [] + } + ], + "responses": { + "200": { + "description": "Observations.", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "401": { + "description": "Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/v1/admin/extract/fal": { "post": { "operationId": "extractFalPricing", @@ -1268,7 +1331,7 @@ }, "staleProbes": { "type": "integer", - "description": "Present only when this provider has probe records older than 90 days. The probed facts stay served. Does not change status. Re-run with `pnpm run probe -- --write`." + "description": "Present only when this provider has probed facts last verified more than 90 days ago. The probed facts stay served. Does not change status. The Worker re-verifies probed facts weekly." }, "priceClearsRefused": { "type": "object", diff --git a/packages/client/src/generated/index.ts b/packages/client/src/generated/index.ts index c53298b7..40534689 100644 --- a/packages/client/src/generated/index.ts +++ b/packages/client/src/generated/index.ts @@ -14,6 +14,7 @@ export { listAllSchemas, listChanges, listModels, + listProbeObservations, listProviderModels, listProviders, listProviderSchemas, @@ -95,6 +96,11 @@ export type { ListModelsData, ListModelsResponse, ListModelsResponses, + ListProbeObservationsData, + ListProbeObservationsError, + ListProbeObservationsErrors, + ListProbeObservationsResponse, + ListProbeObservationsResponses, ListProviderModelsData, ListProviderModelsError, ListProviderModelsErrors, diff --git a/packages/client/src/generated/sdk.gen.ts b/packages/client/src/generated/sdk.gen.ts index 5cac2f76..b8a99b5f 100644 --- a/packages/client/src/generated/sdk.gen.ts +++ b/packages/client/src/generated/sdk.gen.ts @@ -43,6 +43,9 @@ import type { ListChangesResponses, ListModelsData, ListModelsResponses, + ListProbeObservationsData, + ListProbeObservationsErrors, + ListProbeObservationsResponses, ListProviderModelsData, ListProviderModelsErrors, ListProviderModelsResponses, @@ -314,6 +317,28 @@ export const syncProvider = ( ...options, }) +/** + * Audit the live probe observations for a provider (admin only, read-only) + * + * Every `probe_observations` row the probe cron appended for this provider, newest first: model, route, fact, value (null when the response stated nothing), status, the provider message that is the evidence, observedAt, runId, and `served` (true for the two agreeing observations behind a served value). `?model=` narrows to one raw id. + */ +export const listProbeObservations = ( + options: Options, +): RequestResult< + ListProbeObservationsResponses, + ListProbeObservationsErrors, + ThrowOnError +> => + (options.client ?? client).get< + ListProbeObservationsResponses, + ListProbeObservationsErrors, + ThrowOnError + >({ + security: [{ name: 'X-Admin-Key', type: 'apiKey' }], + url: '/v1/admin/probes/{provider}', + ...options, + }) + /** * Manually trigger the FAL llms.txt rate-card extract (admin only). Spec sync stays on POST /v1/admin/sync/fal. */ diff --git a/packages/client/src/generated/types.gen.ts b/packages/client/src/generated/types.gen.ts index e396f080..7e6eb5ea 100644 --- a/packages/client/src/generated/types.gen.ts +++ b/packages/client/src/generated/types.gen.ts @@ -83,7 +83,7 @@ export type ServiceStatus = { live: number } /** - * Present only when this provider has probe records older than 90 days. The probed facts stay served. Does not change status. Re-run with `pnpm run probe -- --write`. + * Present only when this provider has probed facts last verified more than 90 days ago. The probed facts stay served. Does not change status. The Worker re-verifies probed facts weekly. */ staleProbes?: number /** @@ -1567,7 +1567,7 @@ export type GetSchemaError = GetSchemaErrors[keyof GetSchemaErrors] export type GetSchemaResponses = { /** - * Self-contained JSON Schema ($defs-bundled) — or, with format=types, a TypeScript module — served with ETag. JSON responses carry `provenance` (upstream sourceUrl, sourceHash, fetchedAt, extractorVersion) so derivations are independently verifiable. `provenance.derivation` grades how the content was arrived at — `upstream-spec` and `generated` are re-derived every sync and self-heal. `probe-verified` is a live API call recorded in `src/server/providers/probes/.ts` on `provenance.verifiedAt` (`YYYY-MM-DD`). Re-run it with `pnpm run probe -- [--write]`. A record older than 90 days is still served; `GET /v1/status` counts those on `staleProbes`. `docs-derived` was never confirmed against the API. Both are point-in-time claims that can go stale. + * Self-contained JSON Schema ($defs-bundled) — or, with format=types, a TypeScript module — served with ETag. JSON responses carry `provenance` (upstream sourceUrl, sourceHash, fetchedAt, extractorVersion) so derivations are independently verifiable. `provenance.derivation` grades how the content was arrived at — `upstream-spec` and `generated` are re-derived every sync and self-heal. `probe-verified` is a live API call dated `provenance.verifiedAt` (`YYYY-MM-DD`): a route record in `src/server/providers/probes/.ts`, or, for a model fact, two agreeing observations the Worker recorded from its own requests. A probe older than 90 days is still served; `GET /v1/status` counts those on `staleProbes`. `docs-derived` was never confirmed against the API. Both are point-in-time claims that can go stale. */ 200: { [key: string]: unknown @@ -1781,6 +1781,46 @@ export type SyncProviderResponses = { export type SyncProviderResponse = SyncProviderResponses[keyof SyncProviderResponses] +export type ListProbeObservationsData = { + body?: never + path: { + /** + * Provider slug (see GET /v1/providers). + */ + provider: string + } + query?: { + model?: string + } + url: '/v1/admin/probes/{provider}' +} + +export type ListProbeObservationsErrors = { + /** + * Error + */ + 401: Error + /** + * Error + */ + 404: Error +} + +export type ListProbeObservationsError = + ListProbeObservationsErrors[keyof ListProbeObservationsErrors] + +export type ListProbeObservationsResponses = { + /** + * Observations. + */ + 200: { + [key: string]: unknown + } +} + +export type ListProbeObservationsResponse = + ListProbeObservationsResponses[keyof ListProbeObservationsResponses] + export type ExtractFalPricingData = { body?: never path?: never diff --git a/scripts/probe.ts b/scripts/probe.ts index d97f0b8f..f1d504ac 100644 --- a/scripts/probe.ts +++ b/scripts/probe.ts @@ -1,216 +1,112 @@ -// Run one provider's live probes. Spends a key and calls the provider. -// Never prints the key. +// Read-only local dry run of the live probes. Spends a key and calls the +// provider; writes nothing (no file, no D1). Never prints the key. // -// pnpm run probe -- [--write] [--skip-missing-key] +// pnpm run probe -- [rawId...] chat probe (#717) +// pnpm run probe -- opencode-go legacy route records // -// Route records (opencode-go): `--write` sets `verifiedAt` to today on -// records that still match; a mismatch exits 1 and leaves the file alone. -// -// Chat probes (`chatProbes`, issue #717): every model gets each check in -// `probeChecks(probe)`. A response that states a fact is printed; `--write` -// stores it in records/.ts. An undecided check prints why and -// keeps the stored record as it was (printed as not reconfirmed). More than MAX_PROBE_REQUESTS planned -// requests aborts before the first. `--skip-missing-key` (the weekly CI -// job) reports a missing key and exits 0. +// Chat probe: prints what each check would observe, decided or not. The +// Worker's probe cron is what records observations (probe_observations); +// nothing here can. Route records: prints whether each still matches. import { spawnSync } from 'node:child_process' -import { readFileSync, writeFileSync } from 'node:fs' -import { userInfo } from 'node:os' import { - MAX_PROBE_REQUESTS, classifyProbeResponse, - mergeProbedRecords, probeBody, probeChecks, + redactKey, + sendProbe, } from '../src/server/providers/probes/chat-completions.ts' import type { ChatCompletionsProbe } from '../src/server/providers/probes/chat-completions.ts' +import { observationMatches } from '../src/server/providers/probes/compare.ts' import { - bumpVerifiedAt, - observationMatches, -} from '../src/server/providers/probes/compare.ts' -import { + chatProbeFor, chatProbes, - probedFactFile, - probedFactRecords, - probeRecords, probesFor, } from '../src/server/providers/probes/index.ts' -import { OPENCODE_GO_PROBE_SOURCE } from '../src/server/providers/probes/opencode-go.ts' -import type { - ProbedFactRecord, - ProbeRecord, -} from '../src/server/providers/probes/types.ts' +import type { ProbeRecord } from '../src/server/providers/probes/types.ts' -const ROUTE_PROBES: Record< - string, - { file: string; origin: string; keyEnv: string } -> = { +/** Local cap: a dry run never sends more than this many requests. */ +const MAX_DRY_RUN_REQUESTS = 12 + +const ROUTE_PROBES: Record = { 'opencode-go': { - file: OPENCODE_GO_PROBE_SOURCE, origin: 'https://opencode.ai', keyEnv: 'OPENCODE_GO_API_KEY', }, } // pnpm 11 passes the `--` through. -const providerId = process.argv.slice(2).find((arg) => arg !== '--') -const write = process.argv.includes('--write') -const skipMissingKey = process.argv.includes('--skip-missing-key') -const chat = chatProbes.find((probe) => probe.provider === providerId) +const args = process.argv.slice(2).filter((arg) => arg !== '--') +const [providerId, ...modelIds] = args +const chat = providerId ? chatProbeFor(providerId) : null const known = [ - ...new Set([ - ...probeRecords.map((record) => record.provider), - ...chatProbes.map((probe) => probe.provider), - ]), + ...Object.keys(ROUTE_PROBES), + ...chatProbes.filter((probe) => !probe.gateway).map((p) => p.provider), ] if (!providerId || !known.includes(providerId)) { console.error( - `usage: pnpm run probe -- [--write] [--skip-missing-key]\nproviders: ${known.join(', ')}`, + `usage: pnpm run probe -- [rawId...]\nproviders: ${known.join(', ')}`, ) process.exit(1) } -const today = new Date().toISOString().slice(0, 10) -if (chat) await runChatProbe(chat) -else await runRouteProbes() +if (chat) await dryRunChat(chat, modelIds) +else await checkRouteRecords() -async function runRouteProbes(): Promise { - const config = ROUTE_PROBES[providerId!] - if (!config) throw new Error(`probe: ${providerId} has no route config`) - const records = probesFor(providerId!) - const apiKey = readKey(config.keyEnv) - const mismatches: Array = [] - for (const record of records) { - const mismatch = await runRecord(record, config, apiKey) - if (mismatch) mismatches.push(`${record.id}: ${mismatch}`) - else console.log(`${record.id}: match`) - } - if (mismatches.length > 0) { - for (const line of mismatches) console.error(line) +async function dryRunChat( + probe: ChatCompletionsProbe, + ids: Array, +): Promise { + const checks = probeChecks(probe) + if (ids.length === 0) { + console.error('name at least one raw model id to probe') process.exit(1) } - if (write) { - const next = records.reduce( - (source, record) => bumpVerifiedAt(source, record.id, today), - readFileSync(config.file, 'utf8'), - ) - writeFileSync(config.file, next) - console.log(`wrote verifiedAt ${today} in ${config.file}`) - } -} - -async function runChatProbe(probe: ChatCompletionsProbe): Promise { - const checks = probeChecks(probe) - const planned = probe.models.length * checks.length - if (planned > MAX_PROBE_REQUESTS) { + if (ids.length * checks.length > MAX_DRY_RUN_REQUESTS) { console.error( - `probe: ${probe.provider} plans ${planned} requests, over the per-run cap of ${MAX_PROBE_REQUESTS}. Shorten its model list.`, + `would send ${ids.length * checks.length} requests, over the cap of ${MAX_DRY_RUN_REQUESTS}`, ) process.exit(1) } - const apiKey = readKey(probe.keyEnv) - const ranBy = - process.env.TANSTACK_SOURCE_JOB_ID || process.env.CI - ? 'weekly-probe' - : userInfo().username - const found: Array = [] - let sent = 0 - for (const model of probe.models) { + const key = readKey(probe.keyEnv) + for (const model of ids) { for (const check of checks) { - // Belt and braces: the plan above already bounds this. - if (++sent > MAX_PROBE_REQUESTS) throw new Error('probe: request cap hit') - const body = probeBody(check, model) - const { status, text } = await send(probe.url, body, apiKey) + const { status, text } = await sendProbe( + probe.url, + probeBody(check, model), + key, + ) const outcome = classifyProbeResponse( check, status, text, probe.mandatoryRule, ) - const label = `${model} ${check}` - if ('undecided' in outcome) { - console.log( - `${label}: undecided (${redact(outcome.undecided, apiKey)})`, - ) - continue - } - console.log(`${label}: ${outcome.fact} = ${String(outcome.value)}`) - found.push({ - id: `${model}:${outcome.fact}`, - provider: probe.provider, - model, - fact: outcome.fact, - value: outcome.value, - route: probe.route, - verifiedAt: today, - ranBy, - request: { url: probe.url, body }, - evidence: { status, message: redact(outcome.message, apiKey) }, - }) + const said = + 'undecided' in outcome + ? `undecided (${outcome.undecided})` + : `${outcome.fact} = ${String(outcome.value)} (${outcome.message})` + console.log(`${model} ${check}: ${redactKey(said, key)}`) } } - const { records, unconfirmed } = mergeProbedRecords( - probe.provider, - probedFactRecords, - found, - new Date(), - ) - // Kept, never overwritten by an undecided check, but visible. - for (const record of unconfirmed) { - console.log(`stored record not reconfirmed: ${record.model} ${record.fact}`) - } - if (!write) return - const file = probedFactFile(probe.provider) - writeFileSync( - file, - `// Written by \`pnpm run probe -- ${probe.provider} --write\`. Do not edit by hand.\nimport type { ProbedFactRecord } from '../types.ts'\n\nexport const records: Array = ${JSON.stringify(records, null, 2)}\n`, - ) - const format = spawnSync('pnpm', ['exec', 'oxfmt', file], { - stdio: 'inherit', - }) - if (format.status !== 0) throw new Error(`probe: oxfmt failed on ${file}`) - console.log(`wrote ${records.length} records to ${file}`) + console.log('dry run: nothing written') } -/** A 2xx body is cancelled unread: it states nothing, and it bills. */ -async function send( - url: string, - body: Record, - secret: string, -): Promise<{ status: number; text: string }> { - try { - const response = await fetch(url, { - method: 'POST', - headers: { - authorization: `Bearer ${secret}`, - 'content-type': 'application/json', - 'user-agent': 'modelschemas-probe/1', - }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(30_000), - }) - if (response.ok) { - await response.body?.cancel() - return { status: response.status, text: '' } - } - return { status: response.status, text: await response.text() } - } catch { - // The error can quote the request; report only that it failed. - return { status: 0, text: '' } +async function checkRouteRecords(): Promise { + const config = ROUTE_PROBES[providerId!]! + const key = readKey(config.keyEnv) + let failed = false + for (const record of probesFor(providerId!)) { + const mismatch = await runRecord(record, config, key) + if (mismatch) failed = true + console.log(`${record.id}: ${mismatch ?? 'match'}`) } -} - -function redact(text: string, secret: string): string { - return secret ? text.replaceAll(secret, '[key]') : text + if (failed) process.exit(1) } function readKey(keyEnv: string): string { const fromEnv = process.env[keyEnv]?.trim() if (fromEnv) return fromEnv - if (skipMissingKey) { - console.log(`skip ${providerId}: ${keyEnv} is not set`) - process.exit(0) - } const result = spawnSync( 'doppler', [ @@ -230,33 +126,23 @@ function readKey(keyEnv: string): string { console.error( `${keyEnv} is missing from the environment and from Doppler dev.`, ) - const detail = result.error ? result.error.message : result.stderr.trim() - if (detail) console.error(detail) process.exit(1) } return value } -function headersFor( - record: ProbeRecord, - keyEnv: string, - secret: string, -): Record { - const headers: Record = {} - for (const [name, value] of Object.entries(record.request.headers)) { - headers[name] = value.replaceAll(`$${keyEnv}`, secret) - } - return headers -} - async function runRecord( record: ProbeRecord, config: { origin: string; keyEnv: string }, secret: string, ): Promise { + const headers: Record = {} + for (const [name, value] of Object.entries(record.request.headers)) { + headers[name] = value.replaceAll(`$${config.keyEnv}`, secret) + } const response = await fetch(`${config.origin}${record.request.path}`, { method: record.request.method, - headers: headersFor(record, config.keyEnv, secret), + headers, body: JSON.stringify(record.request.body), }) const text = await response.text() diff --git a/src/db/schema.ts b/src/db/schema.ts index ffaf6a66..e52fc2d7 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -668,6 +668,39 @@ export const cacheMeta = sqliteTable('cache_meta', { .default(false), }) +// --------------------------------------------------------------------------- +// Live probe observations (issue #717). Append-only: the Worker inserts one +// row per probe request it sent and never updates or deletes one. `value` +// is the JSON fact the response stated, null when it stated nothing (the +// row is then only the attempt, with the reason in `message`). Which value +// is served is computed from these rows (`servedProbeFacts`). +// --------------------------------------------------------------------------- + +export const probeObservations = sqliteTable( + 'probe_observations', + { + id: integer('id').primaryKey({ autoIncrement: true }), + runId: text('run_id').notNull(), + providerId: text('provider_id') + .notNull() + .references(() => providers.id, { onDelete: 'cascade' }), + rawId: text('raw_id').notNull(), + route: text('route').notNull(), + fact: text('fact').notNull(), + value: text('value', { mode: 'json' }).$type(), + status: integer('status').notNull(), + message: text('message').notNull(), + observedAt: integer('observed_at').notNull(), + }, + (table) => [ + index('probe_observations_provider_model_idx').on( + table.providerId, + table.rawId, + table.fact, + ), + ], +) + export const subscriptions = sqliteTable( 'subscriptions', { diff --git a/src/lib/agent-auth.worker.test.ts b/src/lib/agent-auth.worker.test.ts index 988074cb..2d4b8f98 100644 --- a/src/lib/agent-auth.worker.test.ts +++ b/src/lib/agent-auth.worker.test.ts @@ -68,6 +68,7 @@ describe('agent-auth provider surface', () => { 'syncProvider', 'extractFalPricing', 'exportCatalog', + 'listProbeObservations', ]), ) for (const op of adminOps) expect(names).not.toContain(op) diff --git a/src/lib/auth.ts b/src/lib/auth.ts index a9fa1cb2..97582f15 100644 --- a/src/lib/auth.ts +++ b/src/lib/auth.ts @@ -16,6 +16,7 @@ const EXCLUDED_CAPABILITIES = new Set([ 'syncProvider', 'extractFalPricing', 'exportCatalog', + 'listProbeObservations', ]) /** diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index c3d2addc..1729b73f 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -50,6 +50,7 @@ import { Route as V1SubscriptionsIdRouteImport } from './routes/v1/subscriptions import { Route as ModelsProviderModelIdPricingRouteImport } from './routes/models/$provider.$modelId_.pricing' import { Route as SchemasProviderActivitySplatRouteImport } from './routes/schemas/$provider.$activity.$' import { Route as V1AdminExtractFalRouteImport } from './routes/v1/admin/extract.fal' +import { Route as V1AdminProbesProviderRouteImport } from './routes/v1/admin/probes.$provider' import { Route as V1AdminSyncProviderRouteImport } from './routes/v1/admin/sync.$provider' import { Route as V1ModelsProviderModelIdRouteImport } from './routes/v1/models/$provider.$modelId' import { Route as V1ProvidersProviderModelsRouteImport } from './routes/v1/providers/$provider.models' @@ -269,6 +270,11 @@ const V1AdminExtractFalRoute = V1AdminExtractFalRouteImport.update({ path: '/v1/admin/extract/fal', getParentRoute: () => rootRouteImport, } as any) +const V1AdminProbesProviderRoute = V1AdminProbesProviderRouteImport.update({ + id: '/v1/admin/probes/$provider', + path: '/v1/admin/probes/$provider', + getParentRoute: () => rootRouteImport, +} as any) const V1AdminSyncProviderRoute = V1AdminSyncProviderRouteImport.update({ id: '/v1/admin/sync/$provider', path: '/v1/admin/sync/$provider', @@ -345,6 +351,7 @@ export interface FileRoutesByFullPath { '/models/$provider/$modelId/pricing': typeof ModelsProviderModelIdPricingRoute '/schemas/$provider/$activity/$': typeof SchemasProviderActivitySplatRoute '/v1/admin/extract/fal': typeof V1AdminExtractFalRoute + '/v1/admin/probes/$provider': typeof V1AdminProbesProviderRoute '/v1/admin/sync/$provider': typeof V1AdminSyncProviderRoute '/v1/models/$provider/$modelId': typeof V1ModelsProviderModelIdRoute '/v1/providers/$provider/models': typeof V1ProvidersProviderModelsRoute @@ -394,6 +401,7 @@ export interface FileRoutesByTo { '/models/$provider/$modelId/pricing': typeof ModelsProviderModelIdPricingRoute '/schemas/$provider/$activity/$': typeof SchemasProviderActivitySplatRoute '/v1/admin/extract/fal': typeof V1AdminExtractFalRoute + '/v1/admin/probes/$provider': typeof V1AdminProbesProviderRoute '/v1/admin/sync/$provider': typeof V1AdminSyncProviderRoute '/v1/models/$provider/$modelId': typeof V1ModelsProviderModelIdRoute '/v1/providers/$provider/models': typeof V1ProvidersProviderModelsRoute @@ -444,6 +452,7 @@ export interface FileRoutesById { '/models/$provider/$modelId_/pricing': typeof ModelsProviderModelIdPricingRoute '/schemas/$provider/$activity/$': typeof SchemasProviderActivitySplatRoute '/v1/admin/extract/fal': typeof V1AdminExtractFalRoute + '/v1/admin/probes/$provider': typeof V1AdminProbesProviderRoute '/v1/admin/sync/$provider': typeof V1AdminSyncProviderRoute '/v1/models/$provider/$modelId': typeof V1ModelsProviderModelIdRoute '/v1/providers/$provider/models': typeof V1ProvidersProviderModelsRoute @@ -495,6 +504,7 @@ export interface FileRouteTypes { | '/models/$provider/$modelId/pricing' | '/schemas/$provider/$activity/$' | '/v1/admin/extract/fal' + | '/v1/admin/probes/$provider' | '/v1/admin/sync/$provider' | '/v1/models/$provider/$modelId' | '/v1/providers/$provider/models' @@ -544,6 +554,7 @@ export interface FileRouteTypes { | '/models/$provider/$modelId/pricing' | '/schemas/$provider/$activity/$' | '/v1/admin/extract/fal' + | '/v1/admin/probes/$provider' | '/v1/admin/sync/$provider' | '/v1/models/$provider/$modelId' | '/v1/providers/$provider/models' @@ -593,6 +604,7 @@ export interface FileRouteTypes { | '/models/$provider/$modelId_/pricing' | '/schemas/$provider/$activity/$' | '/v1/admin/extract/fal' + | '/v1/admin/probes/$provider' | '/v1/admin/sync/$provider' | '/v1/models/$provider/$modelId' | '/v1/providers/$provider/models' @@ -643,6 +655,7 @@ export interface RootRouteChildren { ModelsProviderModelIdPricingRoute: typeof ModelsProviderModelIdPricingRoute SchemasProviderActivitySplatRoute: typeof SchemasProviderActivitySplatRoute V1AdminExtractFalRoute: typeof V1AdminExtractFalRoute + V1AdminProbesProviderRoute: typeof V1AdminProbesProviderRoute V1AdminSyncProviderRoute: typeof V1AdminSyncProviderRoute V1ModelsProviderModelIdRoute: typeof V1ModelsProviderModelIdRoute V1SchemasProviderIndexRoute: typeof V1SchemasProviderIndexRoute @@ -939,6 +952,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof V1AdminExtractFalRouteImport parentRoute: typeof rootRouteImport } + '/v1/admin/probes/$provider': { + id: '/v1/admin/probes/$provider' + path: '/v1/admin/probes/$provider' + fullPath: '/v1/admin/probes/$provider' + preLoaderRoute: typeof V1AdminProbesProviderRouteImport + parentRoute: typeof rootRouteImport + } '/v1/admin/sync/$provider': { id: '/v1/admin/sync/$provider' path: '/v1/admin/sync/$provider' @@ -1040,6 +1060,7 @@ const rootRouteChildren: RootRouteChildren = { ModelsProviderModelIdPricingRoute: ModelsProviderModelIdPricingRoute, SchemasProviderActivitySplatRoute: SchemasProviderActivitySplatRoute, V1AdminExtractFalRoute: V1AdminExtractFalRoute, + V1AdminProbesProviderRoute: V1AdminProbesProviderRoute, V1AdminSyncProviderRoute: V1AdminSyncProviderRoute, V1ModelsProviderModelIdRoute: V1ModelsProviderModelIdRoute, V1SchemasProviderIndexRoute: V1SchemasProviderIndexRoute, diff --git a/src/routes/v1/admin/probes.$provider.ts b/src/routes/v1/admin/probes.$provider.ts new file mode 100644 index 00000000..fc79228e --- /dev/null +++ b/src/routes/v1/admin/probes.$provider.ts @@ -0,0 +1,42 @@ +import { createFileRoute } from '@tanstack/react-router' +import { env } from 'cloudflare:workers' + +import { getDb } from '#/db/index.ts' +import { isAdminRequest, jsonError } from '#/server/admin.ts' +import { readProbeObservations } from '#/server/ingest/probe-facts.ts' +import { getProvider } from '#/server/providers/index.ts' + +/** Read-only audit of the probe observations (issue #717). No write path. */ +export const Route = createFileRoute('/v1/admin/probes/$provider')({ + server: { + handlers: { + GET: async ({ request, params }) => { + if (!isAdminRequest(request, env.ADMIN_KEY)) { + return jsonError( + 401, + 'unauthorized', + 'Provide the admin key via X-Admin-Key or Authorization: Bearer.', + ) + } + if (!getProvider(params.provider)) { + return jsonError( + 404, + 'unknown_provider', + `Unknown provider '${params.provider}'. GET /v1/providers lists them.`, + ) + } + const model = + new URL(request.url).searchParams.get('model') ?? undefined + const observations = await readProbeObservations( + getDb(env), + params.provider, + model, + ) + return Response.json( + { provider: params.provider, observations }, + { headers: { 'Cache-Control': 'no-store' } }, + ) + }, + }, + }, +}) diff --git a/src/server/ingest/poll-models.ts b/src/server/ingest/poll-models.ts index 7c4e5b33..148f4db8 100644 --- a/src/server/ingest/poll-models.ts +++ b/src/server/ingest/poll-models.ts @@ -30,6 +30,7 @@ import { import type { SchemaWalk } from '#/server/providers/fact-sources.ts' import { keepValidReasoning } from '#/server/providers/reasoning-config.ts' import { withProbedFacts } from '#/server/providers/probes/index.ts' +import type { ServedProbeFact } from '#/server/providers/probes/types.ts' import { KNOWLEDGE_CUTOFF } from '#/server/providers/types.ts' import { chatRequestMap } from '#/server/providers/request-map.ts' import { @@ -80,6 +81,7 @@ import { nullModelsDevRateCards, storedCardIsPrior, } from './retire-models-dev.ts' +import { loadServedProbeFacts } from './probe-facts.ts' import { ensureProviderRow } from './sync.ts' import type { SyncDeps } from './sync.ts' import { @@ -169,17 +171,19 @@ function requestMapFor(providerId: string, info: ModelInfo) { : chatRequestMap(providerId, info.rawId, info.activity ?? null) } -/** Probe records fill the gaps a row still has (issue #717). */ +/** Served probe facts fill the gaps a row still has (issue #717). */ function probed( info: ModelInfo, providerId: string, bound: string | null, + served: Array, ): ModelInfo { return withProbedFacts( info, providerId, bound, requestMapFor(providerId, info), + served, ) } @@ -778,6 +782,7 @@ export async function pollProviderModels( .select() .from(models) .where(eq(models.providerId, provider.id)) + const servedProbes = await loadServedProbeFacts(db, provider.id) const existingById = new Map(existingRows.map((m) => [m.id, m])) // Row id → deprecations page entry; the first spelling of an id wins. let deprecationIndex: Map | null = null @@ -919,6 +924,7 @@ export async function pollProviderModels( { ...enriched, pricing: card, factSources: factSources ?? undefined }, provider.id, bound, + servedProbes, ), existing, ), diff --git a/src/server/ingest/poll-models.worker.test.ts b/src/server/ingest/poll-models.worker.test.ts index 77bed5df..c28dabd6 100644 --- a/src/server/ingest/poll-models.worker.test.ts +++ b/src/server/ingest/poll-models.worker.test.ts @@ -12,6 +12,7 @@ import { changes, endpoints, models, + probeObservations, providers, schemaVersions, } from '../../db/schema.ts' @@ -99,25 +100,45 @@ const haiku: ModelInfo = { } describe('pollProviderModels', () => { - it('fills a gap from a probe record, dated and probe-verified (#717)', async () => { + it('fills a gap from served probe observations, dated and probe-verified (#717)', async () => { const id = 'groq' const deps = await freshDeps(id) const rawId = 'openai/gpt-oss-safeguard-20b' - await pollProviderModels( - deps, - stubProvider(id, [ - { - rawId, - activity: 'chat', - schemaEndpointId: 'openai/v1/chat/completions', - reasoning: { - mode: 'effort', - mandatory: null, - efforts: ['low', 'medium', 'high'], - }, + const listing = stubProvider(id, [ + { + rawId, + activity: 'chat', + schemaEndpointId: 'openai/v1/chat/completions', + reasoning: { + mode: 'effort', + mandatory: null, + efforts: ['low', 'medium', 'high'], }, - ]), + }, + ]) + await pollProviderModels(deps, listing) + // Two runs that agree, as the probe cron would append them. + const facts: Array<[string, number | boolean]> = [ + ['maxOutput', 65536], + ['reasoning.mandatory', true], + ['replayReasoningContent', false], + ] + await deps.db.insert(probeObservations).values( + ['run-1', 'run-2'].flatMap((runId, i) => + facts.map(([fact, value]) => ({ + runId, + providerId: id, + rawId, + route: 'openai/v1/chat/completions', + fact, + value, + status: 400, + message: 'test', + observedAt: 1_795_000_000 + i * 3_600, + })), + ), ) + await pollProviderModels(deps, listing) const [row] = await deps.db .select() .from(models) diff --git a/src/server/ingest/probe-facts.ts b/src/server/ingest/probe-facts.ts new file mode 100644 index 00000000..e07d5923 --- /dev/null +++ b/src/server/ingest/probe-facts.ts @@ -0,0 +1,458 @@ +/** + * Live probes in the Worker (issue #717). The probe cron picks chat rows of + * probe-enabled providers, sends one minimal request per check, reads the + * response with the pure `classifyProbeResponse`, and appends what it saw + * to `probe_observations`. Nothing else writes that table, and nothing + * updates or deletes a row. + * + * Serving: a value is served only once the two newest decided + * observations, from separate runs, agree. The models poll reads the + * served facts (`loadServedProbeFacts`) and fills only empty facts on the + * exact model and route observed (`withProbedFacts`). + */ +import { and, eq, inArray, isNotNull, isNull } from 'drizzle-orm' + +import type { Db } from '#/db/index.ts' +import { models, probeObservations } from '#/db/schema.ts' +import { + CHECK_FACT, + classifyProbeResponse, + probeBody, + probeChecks, + redactKey, + sendProbe, +} from '#/server/providers/probes/chat-completions.ts' +import type { + ChatCompletionsProbe, + ProbeCheck, +} from '#/server/providers/probes/chat-completions.ts' +import { chatProbeFor, chatProbes } from '#/server/providers/probes/index.ts' +import { probeIsStale } from '#/server/providers/probes/types.ts' +import type { + ProbedFact, + ServedProbeFact, +} from '#/server/providers/probes/types.ts' +import { resolveSchemaEndpointId } from '#/server/schema-binding.ts' +import type { Activity } from '#/db/schema.ts' + +/** Hourly at :07, its own invocation, after the :00 models poll. */ +export const PROBE_CRON = '7 * * * *' +/** Hard cap on provider requests per cron invocation (all providers). */ +export const PROBE_REQUEST_BUDGET = 12 +/** Hard cap on requests to one provider per cron invocation. */ +export const PROBE_PROVIDER_BUDGET = 4 +/** The slow cycle: a fact whose last attempt is this old is probed again. */ +export const REVERIFY_AFTER_DAYS = 7 + +const MESSAGE_MAX = 1_000 +const DAY_SECONDS = 86_400 + +type Observation = typeof probeObservations.$inferSelect + +type ObservationKey = Pick< + Observation, + 'providerId' | 'rawId' | 'route' | 'fact' +> + +function keyOf(row: ObservationKey): string { + return [row.providerId, row.rawId, row.route, row.fact].join('\u0000') +} + +function day(seconds: number): string { + return new Date(seconds * 1000).toISOString().slice(0, 10) +} + +function newestFirst(a: Observation, b: Observation): number { + return b.observedAt - a.observedAt || b.id - a.id +} + +/** + * The two observations that decide a fact: the newest decided one and the + * newest decided one from another run. Served when both exist and agree. + */ +function decidingPair( + history: Array, +): [Observation, Observation | undefined] | null { + const decided = history.filter((row) => row.value !== null).sort(newestFirst) + const newest = decided[0] + if (!newest) return null + return [newest, decided.find((row) => row.runId !== newest.runId)] +} + +function groupByKey(rows: Array): Map> { + const groups = new Map>() + for (const row of rows) { + const key = keyOf(row) + groups.set(key, [...(groups.get(key) ?? []), row]) + } + return groups +} + +/** + * The facts the catalog serves, and the ids of the observations behind + * them. A provider no longer on the probe list serves nothing. + */ +export function servedProbeFacts(rows: Array): { + served: Array + servingIds: Set +} { + const served: Array = [] + const servingIds = new Set() + for (const history of groupByKey(rows).values()) { + const pair = decidingPair(history) + const probe = pair && chatProbeFor(pair[0].providerId) + if (!pair || !probe || !pair[1]) continue + const [newest, previous] = pair + if (newest.value !== previous.value) continue + const value = newest.value + if (typeof value !== 'number' && typeof value !== 'boolean') continue + served.push({ + provider: newest.providerId, + model: newest.rawId, + route: newest.route, + fact: newest.fact as ProbedFact, + value, + verifiedAt: day(newest.observedAt), + sourceUrl: probe.url, + }) + servingIds.add(newest.id).add(previous.id) + } + return { served, servingIds } +} + +/** One provider's served facts, for the models poll. */ +export async function loadServedProbeFacts( + db: Db, + providerId: string, +): Promise> { + if (!chatProbeFor(providerId)) return [] + const rows = await db + .select() + .from(probeObservations) + .where( + and( + eq(probeObservations.providerId, providerId), + isNotNull(probeObservations.value), + ), + ) + return servedProbeFacts(rows).served +} + +/** Served facts older than `PROBE_STALE_DAYS`, per provider. */ +export async function staleProbeCounts( + db: Db, + now: Date, +): Promise> { + const rows = await db + .select() + .from(probeObservations) + .where(isNotNull(probeObservations.value)) + const counts = new Map() + for (const fact of servedProbeFacts(rows).served) { + if (!probeIsStale(fact.verifiedAt, now)) continue + counts.set(fact.provider, (counts.get(fact.provider) ?? 0) + 1) + } + return counts +} + +/** Admin audit: every observation, newest first, marked when it is served. */ +export async function readProbeObservations( + db: Db, + providerId: string, + rawId?: string, +): Promise & { id: number; served: boolean }>> { + const all = await db + .select() + .from(probeObservations) + .where(eq(probeObservations.providerId, providerId)) + const { servingIds } = servedProbeFacts(all) + return all + .filter((row) => rawId === undefined || row.rawId === rawId) + .sort(newestFirst) + .map((row) => ({ ...row, served: servingIds.has(row.id) })) +} + +interface ProbeRow { + providerId: string + rawId: string + activity: Activity | null + capabilities: unknown + schemaEndpointId: string | null + maxOutput: number | null + reasoning: unknown + requestMap: unknown +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +/** True when the stored row has nothing for the fact a check can state. */ +function factIsEmpty(row: ProbeRow, fact: ProbedFact): boolean { + if (fact === 'maxOutput') return row.maxOutput === null + if (fact === 'replayReasoningContent') { + return ( + !isRecord(row.requestMap) || row.requestMap.replayReasoningContent == null + ) + } + if (fact === 'reasoning.mandatory') { + return ( + isRecord(row.reasoning) && + row.reasoning.mode === 'effort' && + row.reasoning.mandatory === null + ) + } + return false +} + +export type ProbeReason = 'new' | 'confirm' | 'reverify' + +export interface PlannedProbe { + probe: ChatCompletionsProbe + rawId: string + check: ProbeCheck + reason: ProbeReason + /** The newest decided value before this run, for the disagreement log. */ + prior: number | boolean | null +} + +/** + * Which probes this invocation sends, in order, under both caps: + * - `new`: the row's fact is empty and it has no observation at all; + * - `confirm`: the newest attempt was decided but is not served yet; + * - `reverify`: the newest attempt is `REVERIFY_AFTER_DAYS` old, oldest + * first (an undecided fact only while the row still lacks it). + * New and confirm interleave providers so one provider cannot starve the + * rest. The rest is the backlog for the next invocation. + */ +export function planProbes( + rows: Array, + observations: Array, + probes: Array, + now: number, +): { planned: Array; backlog: number } { + const byProvider = new Map(probes.map((probe) => [probe.provider, probe])) + const history = groupByKey(observations) + const candidates: Array = [] + const rank = new Map() + const nextRank = (reason: ProbeReason, provider: string) => { + const key = `${reason}\u0000${provider}` + const value = rank.get(key) ?? 0 + rank.set(key, value + 1) + return value + } + for (const row of rows) { + const probe = byProvider.get(row.providerId) + if (!probe) continue + const route = resolveSchemaEndpointId({ + providerId: row.providerId, + rawId: row.rawId, + activity: row.activity, + capabilities: row.capabilities, + schemaEndpointId: row.schemaEndpointId, + }) + // Exact route only: a fact observed on another route binds nothing. + if (route !== probe.route) continue + for (const check of probeChecks(probe)) { + const fact = CHECK_FACT[check] + const seen = history.get( + keyOf({ providerId: row.providerId, rawId: row.rawId, route, fact }), + ) + const base = { probe, rawId: row.rawId, check } + if (!seen) { + if (!factIsEmpty(row, fact)) continue + candidates.push({ + ...base, + reason: 'new', + prior: null, + order: nextRank('new', probe.provider), + }) + continue + } + const latest = [...seen].sort(newestFirst)[0]! + const pair = decidingPair(seen) + const prior = pair ? (pair[0].value as number | boolean) : null + const servedNow = + pair !== null && + pair[1] !== undefined && + pair[0].value === pair[1].value + if (latest.value !== null && !servedNow) { + candidates.push({ + ...base, + reason: 'confirm', + prior, + order: nextRank('confirm', probe.provider), + }) + continue + } + if (latest.observedAt > now - REVERIFY_AFTER_DAYS * DAY_SECONDS) continue + if (pair === null && !factIsEmpty(row, fact)) continue + candidates.push({ + ...base, + reason: 'reverify', + prior, + order: latest.observedAt, + }) + } + } + const tier: Record = { new: 0, confirm: 1, reverify: 2 } + candidates.sort( + (a, b) => tier[a.reason] - tier[b.reason] || a.order - b.order, + ) + const planned: Array = [] + const perProvider = new Map() + for (const { order: _order, ...candidate } of candidates) { + if (planned.length >= PROBE_REQUEST_BUDGET) break + const used = perProvider.get(candidate.probe.provider) ?? 0 + if (used >= PROBE_PROVIDER_BUDGET) continue + perProvider.set(candidate.probe.provider, used + 1) + planned.push(candidate) + } + return { planned, backlog: candidates.length - planned.length } +} + +export interface ProbeDeps { + db: Db + secrets: object + now?: () => number + fetch?: typeof fetch + probes?: Array +} + +export interface ProbeRunOutcome { + runId: string + sent: number + decided: number + undecided: number + disagreed: number + backlog: number + skipped: Array<{ provider: string; reason: string }> +} + +function log(entry: Record): void { + console.log(JSON.stringify({ job: 'probe', ...entry })) +} + +/** One cron invocation: plan under the caps, send, append observations. */ +export async function runProbes(deps: ProbeDeps): Promise { + const now = deps.now?.() ?? Math.floor(Date.now() / 1000) + const fetcher = deps.fetch ?? fetch + const outcome: ProbeRunOutcome = { + runId: crypto.randomUUID(), + sent: 0, + decided: 0, + undecided: 0, + disagreed: 0, + backlog: 0, + skipped: [], + } + const keys = new Map() + const active: Array = [] + for (const probe of deps.probes ?? chatProbes) { + if (probe.gateway) { + outcome.skipped.push({ + provider: probe.provider, + reason: 'gateway: no captured response shows its own wording', + }) + continue + } + const raw = (deps.secrets as Record)[probe.keyEnv] + const key = typeof raw === 'string' ? raw.trim() : '' + if (!key) { + outcome.skipped.push({ + provider: probe.provider, + reason: `${probe.keyEnv} is not set`, + }) + continue + } + keys.set(probe.provider, key) + active.push(probe) + } + for (const skip of outcome.skipped) + log({ skip: skip.provider, reason: skip.reason }) + if (active.length === 0) return outcome + + const providerIds = active.map((probe) => probe.provider) + const [rows, observations] = await Promise.all([ + deps.db + .select({ + providerId: models.providerId, + rawId: models.rawId, + activity: models.activity, + capabilities: models.capabilities, + schemaEndpointId: models.schemaEndpointId, + maxOutput: models.maxOutput, + reasoning: models.reasoning, + requestMap: models.requestMap, + }) + .from(models) + .where( + and( + inArray(models.providerId, providerIds), + eq(models.activity, 'chat'), + isNull(models.deprecatedAt), + ), + ), + deps.db + .select() + .from(probeObservations) + .where(inArray(probeObservations.providerId, providerIds)), + ]) + const { planned, backlog } = planProbes(rows, observations, active, now) + outcome.backlog = backlog + + for (const { probe, rawId, check, reason, prior } of planned) { + const key = keys.get(probe.provider)! + const body = probeBody(check, rawId) + outcome.sent++ + const { status, text } = await sendProbe(probe.url, body, key, fetcher) + const result = classifyProbeResponse( + check, + status, + text, + probe.mandatoryRule, + ) + const decided = 'fact' in result + const message = redactKey( + decided ? result.message : result.undecided, + key, + ).slice(0, MESSAGE_MAX) + await deps.db.insert(probeObservations).values({ + runId: outcome.runId, + providerId: probe.provider, + rawId, + route: probe.route, + fact: CHECK_FACT[check], + value: decided ? result.value : null, + status, + message, + observedAt: now, + }) + const entry = { + provider: probe.provider, + model: rawId, + check, + reason, + status, + } + if (!decided) { + outcome.undecided++ + log({ ...entry, undecided: message }) + continue + } + outcome.decided++ + if (prior !== null && prior !== result.value) { + outcome.disagreed++ + console.warn( + JSON.stringify({ + job: 'probe', + ...entry, + disagreement: `observed ${String(result.value)}, previous ${String(prior)}; not served until two newer observations agree`, + }), + ) + continue + } + log({ ...entry, fact: result.fact, value: result.value }) + } + return outcome +} diff --git a/src/server/ingest/probe-facts.worker.test.ts b/src/server/ingest/probe-facts.worker.test.ts new file mode 100644 index 00000000..dc28a56f --- /dev/null +++ b/src/server/ingest/probe-facts.worker.test.ts @@ -0,0 +1,257 @@ +import { describe, expect, it } from 'vitest' +import { env } from 'cloudflare:test' +import { and, eq } from 'drizzle-orm' + +import { getDb } from '#/db/index.ts' +import { models } from '#/db/schema.ts' +import { pollProviderModels } from '#/server/ingest/poll-models.ts' +import { + PROBE_PROVIDER_BUDGET, + PROBE_REQUEST_BUDGET, + REVERIFY_AFTER_DAYS, + loadServedProbeFacts, + planProbes, + readProbeObservations, + runProbes, + staleProbeCounts, +} from '#/server/ingest/probe-facts.ts' +import type { SyncDeps } from '#/server/ingest/sync.ts' +import { provider as groq } from '#/server/providers/adapters/groq.ts' +import type { ChatCompletionsProbe } from '#/server/providers/probes/chat-completions.ts' +import { chatProbeFor } from '#/server/providers/probes/index.ts' +import type { ModelInfo } from '#/server/providers/types.ts' + +const KEY = 'gsk_test_0123456789abcdefKEYEND' +const DAY = 86_400 +const T0 = 1_795_000_000 + +const groqProbe = chatProbeFor('groq')! + +function pollDeps(now: number): SyncDeps { + return { db: getDb(env), kv: env.SCHEMA_CACHE, secrets: {}, now: () => now } +} + +function poll(now: number, listed: Array) { + return pollProviderModels(pollDeps(now), { + ...groq, + listModels: async () => ({ models: listed }), + }) +} + +/** A Groq-worded 400 per check; `limit` is the cap the limits check states. */ +function groqStub(limit: number, sent: Array>) { + return async (_url: RequestInfo | URL, init?: RequestInit) => { + const body = JSON.parse(init?.body as string) as Record + sent.push(body) + const message = + body.max_tokens === 1 + ? `'messages.1' : for 'role:assistant' the following must be satisfied[('messages.1' : property 'reasoning_content' is unsupported)] key=${KEY}` + : `\`max_tokens\` must be less than or equal to \`${limit}\`, the maximum value for \`max_tokens\` is less than the \`context_window\` for this model` + return Response.json({ error: { message } }, { status: 400 }) + } +} + +function run(now: number, limit: number, sent: Array>) { + return runProbes({ + db: getDb(env), + secrets: { GROQ_API_KEY: KEY }, + now: () => now, + fetch: groqStub(limit, sent), + probes: [groqProbe], + }) +} + +async function storedMaxOutput(rawId: string) { + const [row] = await getDb(env) + .select({ maxOutput: models.maxOutput, factSources: models.factSources }) + .from(models) + .where(and(eq(models.providerId, 'groq'), eq(models.rawId, rawId))) + return row! +} + +describe('probe cron (#717)', () => { + it('probes new rows, serves only after two agreeing runs, un-serves on disagreement', async () => { + const listed: Array = [ + { rawId: 'lab/fresh', activity: 'chat' }, + { rawId: 'lab/stated', activity: 'chat', maxOutput: 8192 }, + { rawId: 'lab/embed', activity: 'embeddings' }, + ] + await poll(T0, listed) + + // Run 1: first appearance. Only the row with an empty fact is probed. + const sent: Array> = [] + const first = await run(T0 + 60, 65536, sent) + const limits = sent.filter((body) => body.max_tokens === 10_000_000) + expect(limits.map((body) => body.model)).toEqual(['lab/fresh']) + expect(sent.some((body) => body.model === 'lab/embed')).toBe(false) + expect(first.decided).toBe(sent.length) + const stored = await readProbeObservations(getDb(env), 'groq', 'lab/fresh') + expect(stored.every((row) => !row.message.includes(KEY))).toBe(true) + expect(stored.every((row) => !row.served)).toBe(true) + // One observation is stored, not served. + expect(await loadServedProbeFacts(getDb(env), 'groq')).toEqual([]) + await poll(T0 + 120, listed) + expect((await storedMaxOutput('lab/fresh')).maxOutput).toBeNull() + + // Run 2, a separate run: confirms, so the value is served. + const confirm: Array> = [] + await run(T0 + 3_600, 65536, confirm) + expect(confirm.length).toBeGreaterThan(0) + const served = await loadServedProbeFacts(getDb(env), 'groq') + expect(served).toContainEqual({ + provider: 'groq', + model: 'lab/fresh', + route: 'openai/v1/chat/completions', + fact: 'maxOutput', + value: 65536, + verifiedAt: new Date((T0 + 3_600) * 1000).toISOString().slice(0, 10), + sourceUrl: groqProbe.url, + }) + await poll(T0 + 3_700, listed) + const filled = await storedMaxOutput('lab/fresh') + expect(filled.maxOutput).toBe(65536) + expect(filled.factSources).toMatchObject({ + maxOutput: { derivation: 'probe-verified', sourceUrl: groqProbe.url }, + }) + // Stated value kept; the probe never touched that row. + expect((await storedMaxOutput('lab/stated')).maxOutput).toBe(8192) + + // Docs win: a listing that states the fact replaces nothing with the probe. + await poll(T0 + 3_800, [{ ...listed[0]!, maxOutput: 4096 }, listed[1]!]) + expect((await storedMaxOutput('lab/fresh')).maxOutput).toBe(4096) + + // Served facts are not re-probed until the slow cycle. + const quiet: Array> = [] + await run(T0 + 7_200, 65536, quiet) + expect(quiet).toEqual([]) + + // Re-verify after REVERIFY_AFTER_DAYS: a disagreeing value un-serves. + const later = T0 + (REVERIFY_AFTER_DAYS + 1) * DAY + const reverify: Array> = [] + const disagree = await run(later, 32768, reverify) + expect(reverify.some((body) => body.max_tokens === 10_000_000)).toBe(true) + expect(disagree.disagreed).toBe(1) + const after = await loadServedProbeFacts(getDb(env), 'groq') + expect(after.find((fact) => fact.fact === 'maxOutput')).toBeUndefined() + + // Two newer agreeing observations serve the new value. + await run(later + 3_600, 32768, []) + const again = await loadServedProbeFacts(getDb(env), 'groq') + expect(again.find((fact) => fact.fact === 'maxOutput')?.value).toBe(32768) + + // Stale count: served facts older than 90 days, from the table. + const stale = await staleProbeCounts( + getDb(env), + new Date((later + 3_600 + 91 * DAY) * 1000), + ) + expect(stale.get('groq')).toBe(again.length) + expect( + (await staleProbeCounts(getDb(env), new Date(later * 1000))).get('groq'), + ).toBeUndefined() + }) + + it('skips a missing key and a gateway without sending anything', async () => { + const sent: Array> = [] + const fetch = groqStub(1, sent) + const missing = await runProbes({ + db: getDb(env), + secrets: {}, + fetch, + probes: [groqProbe], + }) + expect(missing.skipped).toEqual([ + { provider: 'groq', reason: 'GROQ_API_KEY is not set' }, + ]) + const gateway = await runProbes({ + db: getDb(env), + secrets: { LLMGATEWAY_API_KEY: KEY }, + fetch, + probes: [chatProbeFor('llmgateway')!], + }) + expect(gateway.skipped[0]?.reason).toMatch(/^gateway/) + expect(sent).toEqual([]) + expect(missing.sent + gateway.sent).toBe(0) + }) +}) + +describe('planProbes', () => { + const probes: Array = ['a', 'b', 'c', 'd', 'e'].map( + (provider) => ({ + provider, + url: `https://${provider}.example/v1/chat/completions`, + route: 'v1/chat/completions', + keyEnv: 'K', + }), + ) + const row = ( + providerId: string, + rawId: string, + route = 'v1/chat/completions', + ) => ({ + providerId, + rawId, + activity: 'chat' as const, + capabilities: null, + schemaEndpointId: route, + maxOutput: null, + reasoning: null, + requestMap: { replayReasoningContent: false }, + }) + + it('caps each invocation and each provider, and interleaves providers', () => { + const rows = probes.flatMap((probe) => + Array.from({ length: 10 }, (_, i) => row(probe.provider, `m${i}`)), + ) + const { planned, backlog } = planProbes(rows, [], probes, T0) + expect(planned).toHaveLength(PROBE_REQUEST_BUDGET) + expect(backlog).toBe(50 - PROBE_REQUEST_BUDGET) + const per = new Map() + for (const p of planned) + per.set(p.probe.provider, (per.get(p.probe.provider) ?? 0) + 1) + for (const n of per.values()) + expect(n).toBeLessThanOrEqual(PROBE_PROVIDER_BUDGET) + // Round robin: the first five are one per provider. + expect(new Set(planned.slice(0, 5).map((p) => p.probe.provider)).size).toBe( + 5, + ) + }) + + it('binds only the exact route', () => { + const { planned } = planProbes( + [row('a', 'm', 'v1/responses')], + [], + probes, + T0, + ) + expect(planned).toEqual([]) + }) + + it('re-verifies the oldest observation first', () => { + const obs = (rawId: string, observedAt: number, id: number) => ({ + id, + runId: `r${id}`, + providerId: 'a', + rawId, + route: 'v1/chat/completions', + fact: 'maxOutput', + value: null, + status: 200, + message: '200: a 2xx states nothing', + observedAt, + }) + const { planned } = planProbes( + [row('a', 'newer'), row('a', 'older'), row('a', 'recent')], + [ + obs('newer', T0 - 10 * DAY, 1), + obs('older', T0 - 30 * DAY, 2), + obs('recent', T0 - DAY, 3), + ], + probes, + T0, + ) + expect(planned.map((p) => [p.rawId, p.reason])).toEqual([ + ['older', 'reverify'], + ['newer', 'reverify'], + ]) + }) +}) diff --git a/src/server/openapi.ts b/src/server/openapi.ts index 3b19f58c..6cc7f774 100644 --- a/src/server/openapi.ts +++ b/src/server/openapi.ts @@ -605,7 +605,7 @@ export const openApiDocument = { description: 'Self-contained JSON Schema ($defs-bundled) — or, with format=types, a TypeScript module — served with ETag. ' + 'JSON responses carry `provenance` (upstream sourceUrl, sourceHash, fetchedAt, extractorVersion) so derivations are independently verifiable. ' + - '`provenance.derivation` grades how the content was arrived at — `upstream-spec` and `generated` are re-derived every sync and self-heal. `probe-verified` is a live API call recorded in `src/server/providers/probes/.ts` on `provenance.verifiedAt` (`YYYY-MM-DD`). Re-run it with `pnpm run probe -- [--write]`. A record older than 90 days is still served; `GET /v1/status` counts those on `staleProbes`. `docs-derived` was never confirmed against the API. Both are point-in-time claims that can go stale.', + '`provenance.derivation` grades how the content was arrived at — `upstream-spec` and `generated` are re-derived every sync and self-heal. `probe-verified` is a live API call dated `provenance.verifiedAt` (`YYYY-MM-DD`): a route record in `src/server/providers/probes/.ts`, or, for a model fact, two agreeing observations the Worker recorded from its own requests. A probe older than 90 days is still served; `GET /v1/status` counts those on `staleProbes`. `docs-derived` was never confirmed against the API. Both are point-in-time claims that can go stale.', content: { 'application/json': { schema: { type: 'object' } }, 'text/typescript': { schema: { type: 'string' } }, @@ -776,6 +776,33 @@ export const openApiDocument = { }, }, }, + '/v1/admin/probes/{provider}': { + get: { + operationId: 'listProbeObservations', + summary: + 'Audit the live probe observations for a provider (admin only, read-only)', + description: + 'Every `probe_observations` row the probe cron appended for this provider, newest first: model, route, fact, value (null when the response stated nothing), status, the provider message that is the evidence, observedAt, runId, and `served` (true for the two agreeing observations behind a served value). `?model=` narrows to one raw id.', + parameters: [ + providerParam, + { + name: 'model', + in: 'query', + required: false, + schema: { type: 'string' }, + }, + ], + security: [{ adminKey: [] }], + responses: { + '200': { + description: 'Observations.', + content: { 'application/json': { schema: { type: 'object' } } }, + }, + '401': errorResponse, + '404': errorResponse, + }, + }, + }, '/v1/admin/extract/fal': { post: { operationId: 'extractFalPricing', @@ -1028,7 +1055,7 @@ export const openApiDocument = { staleProbes: { type: 'integer', description: - 'Present only when this provider has probe records older than 90 days. The probed facts stay served. Does not change status. Re-run with `pnpm run probe -- --write`.', + 'Present only when this provider has probed facts last verified more than 90 days ago. The probed facts stay served. Does not change status. The Worker re-verifies probed facts weekly.', }, priceClearsRefused: { type: 'object', diff --git a/src/server/providers/probes/chat-completions.test.ts b/src/server/providers/probes/chat-completions.test.ts index a103b9d0..a5cbc7b4 100644 --- a/src/server/providers/probes/chat-completions.test.ts +++ b/src/server/providers/probes/chat-completions.test.ts @@ -2,20 +2,14 @@ import { describe, expect, it } from 'vitest' import { classifyProbeResponse, - mergeProbedRecords, probeBody, probeChecks, + redactKey, } from './chat-completions.ts' import type { MandatoryRule, ProbeCheck } from './chat-completions.ts' import responses from './fixtures/probe-responses.json' -import { - chatProbes, - probedFactRecords, - staleProbeCount, - withProbedFacts, -} from './index.ts' -import { records as groqRecords } from './records/groq.ts' -import type { ProbedFactRecord } from './types.ts' +import { chatProbes, withProbedFacts } from './index.ts' +import type { ServedProbeFact } from './types.ts' /** * Real bodies from live probe calls on 2026-11-21 (account ids and a @@ -106,23 +100,27 @@ describe('classifyProbeResponse', () => { expect(probeBody('off', 'm').max_tokens).toBe(1) expect(probeBody('limits', 'm').stream).toBe(true) }) + + it('redacts the key and its leading and trailing fragments', () => { + const key = 'sk-proj-abcdef0123456789xyzXYZ' + expect( + redactKey(`bad key ${key}; also sk-proj-…6789xyzXYZ`, key), + ).not.toMatch(/sk-proj-|xyzXYZ/) + }) }) function record( - fact: ProbedFactRecord['fact'], + fact: ServedProbeFact['fact'], value: number | boolean, -): ProbedFactRecord { +): ServedProbeFact { return { - id: `m:${fact}`, provider: 'p', model: 'm', fact, value, route: 'v1/chat/completions', verifiedAt: '2026-11-21', - ranBy: 'test', - request: { url: 'https://example.com', body: {} }, - evidence: { status: 400, message: 'x' }, + sourceUrl: 'https://example.com/v1/chat/completions', } } @@ -133,10 +131,10 @@ describe('withProbedFacts', () => { record('replayReasoningContent', false), record('reasoning.mandatory', true), ] - const source = (id: string) => ({ + const source = (_fact: string) => ({ derivation: 'probe-verified', verifiedAt: '2026-11-21', - sourceUrl: `src/server/providers/probes/records/p.ts#m:${id}`, + sourceUrl: 'https://example.com/v1/chat/completions', }) it('fills empty facts with a dated probe-verified source', () => { @@ -218,99 +216,4 @@ describe('withProbedFacts', () => { ) expect(withNone.reasoning?.mandatory).toBeNull() }) - - it('counts the committed groq records as current', () => { - expect(staleProbeCount('groq', new Date('2026-11-22T00:00:00Z'))).toBe(0) - expect(staleProbeCount('groq', new Date('2027-03-01T00:00:00Z'))).toBe(6) - }) -}) - -describe('mergeProbedRecords', () => { - const now = new Date('2026-11-28T00:00:00Z') - const groq = (over: Partial): ProbedFactRecord => ({ - ...record('maxOutput', 65536), - provider: 'groq', - id: 'm:maxOutput', - ...over, - }) - - it("never reads or writes another provider's record with the same id", () => { - const together = groq({ provider: 'together', verifiedAt: '2026-11-20' }) - const found = groq({ verifiedAt: '2026-11-28' }) - const { records } = mergeProbedRecords('groq', [together], [found], now) - expect(records).toEqual([found]) - }) - - it('keeps a recent same value, re-dates an old one, replaces a new value', () => { - const recent = groq({ verifiedAt: '2026-11-21' }) - const old = groq({ - id: 'm:contextWindow', - fact: 'contextWindow', - value: 8, - verifiedAt: '2026-08-01', - }) - const changed = groq({ - id: 'm:reasoning.mandatory', - fact: 'reasoning.mandatory', - value: true, - verifiedAt: '2026-11-21', - }) - const found = [ - groq({ verifiedAt: '2026-11-28' }), - { ...old, verifiedAt: '2026-11-28' }, - { ...changed, value: false, verifiedAt: '2026-11-28' }, - ] - const { records } = mergeProbedRecords( - 'groq', - [recent, old, changed], - found, - now, - ) - expect( - records.map((item) => [item.id, item.verifiedAt, item.value]), - ).toEqual([ - ['m:contextWindow', '2026-11-28', 8], - ['m:maxOutput', '2026-11-21', 65536], - ['m:reasoning.mandatory', '2026-11-28', false], - ]) - }) - - it('keeps and lists a stored record the run did not decide', () => { - const stored = groq({}) - const { records, unconfirmed } = mergeProbedRecords( - 'groq', - [stored], - [], - now, - ) - expect(records).toEqual([stored]) - expect(unconfirmed).toEqual([stored]) - }) - - it('rewrites the committed groq records unchanged from their own evidence', () => { - // Re-classify each committed record's evidence, then merge as a run would. - const found = groqRecords.map((item) => { - const check: ProbeCheck = - item.fact === 'maxOutput' - ? 'limits' - : item.fact === 'replayReasoningContent' - ? 'replay' - : 'off' - const outcome = classifyProbeResponse( - check, - item.evidence.status, - JSON.stringify({ error: { message: item.evidence.message } }), - 'groq', - ) - expect(outcome).toMatchObject({ fact: item.fact, value: item.value }) - return item - }) - const { records } = mergeProbedRecords( - 'groq', - probedFactRecords, - found, - new Date('2026-11-21T00:00:00Z'), - ) - expect(records).toEqual(groqRecords) - }) }) diff --git a/src/server/providers/probes/chat-completions.ts b/src/server/providers/probes/chat-completions.ts index d9afb757..73ef1792 100644 --- a/src/server/providers/probes/chat-completions.ts +++ b/src/server/providers/probes/chat-completions.ts @@ -1,10 +1,10 @@ -import { probeAgeDays } from './types.ts' -import type { ProbedFact, ProbedFactRecord } from './types.ts' +import type { ProbedFact } from './types.ts' /** * The generic probe for the OpenAI-style `chat/completions` wire (issue - * #717). A provider opts in with one `ChatCompletionsProbe` and an empty - * records file; `pnpm run probe -- --write` fills the records. + * #717). A provider opts in with one `ChatCompletionsProbe` in + * `probes/index.ts`; the Worker's probe cron (`ingest/probe-facts.ts`) + * picks the models and records each response in `probe_observations`. * * A value is recorded only from a response that states it: a 400 or 422 * whose message gives the limit as a number, or names the field it @@ -17,10 +17,14 @@ export interface ChatCompletionsProbe { url: string /** The endpoint id a catalog row binds (`schemaEndpointId`). */ route: string - /** Env name of the bearer key. The key itself is never in a file. */ + /** Secret name of the bearer key. The key itself is never in a file. */ keyEnv: string - /** Catalog raw ids to probe. Each costs `probeChecks(probe).length` requests. */ - models: Array + /** + * A gateway or reseller. An error it forwards from an upstream states + * nothing about its own row, so the cron never probes one. Clear it only + * after real captured responses show the wording is the gateway's own. + */ + gateway?: true /** * Opt in to the `off` check: whose refusal of `reasoning_effort: "none"` * is read, and only in that provider's own wording. Set it only when @@ -42,14 +46,18 @@ export function probeChecks(probe: ChatCompletionsProbe): Array { : ['limits', 'replay'] } -/** Hard per-provider cap. A run that plans more requests aborts before the first. */ -export const MAX_PROBE_REQUESTS = 30 +/** The fact each check can state. */ +export const CHECK_FACT: Record = { + limits: 'maxOutput', + replay: 'replayReasoningContent', + off: 'reasoning.mandatory', +} /** Far over any model's output cap, so a provider that checks it says so. */ const OVERSIZED_MAX_TOKENS = 10_000_000 /** - * Every body streams and the script cancels a 2xx unread. Cancelling does + * Every body streams and the prober cancels a 2xx unread. Cancelling does * not guarantee the provider stops billing; the real bound is the one-word * prompt (and `max_tokens: 1` on every check but `limits`). */ @@ -235,42 +243,44 @@ export function classifyProbeResponse( return { fact: 'reasoning.mandatory', value: true, message } } -/** Under the 90 stale days, so a weekly run re-dates a record in time. */ -export const REDATE_AFTER_DAYS = 60 +const PROBE_TIMEOUT_MS = 20_000 -/** - * One provider's records after a run. A decided check replaces its stored - * record, or keeps it unchanged when the value is the same and the record - * is at most `REDATE_AFTER_DAYS` old. A stored record the run did not - * decide is kept and listed in `unconfirmed`. Another provider's records - * are never read. - */ -export function mergeProbedRecords( - provider: string, - stored: Array, - found: Array, - now: Date, -): { - records: Array - unconfirmed: Array -} { - const mine = new Map( - stored - .filter((record) => record.provider === provider) - .map((record) => [record.id, record] as const), - ) - const decided = found.map((record) => { - const prior = mine.get(record.id) - return prior && - prior.value === record.value && - probeAgeDays(prior.verifiedAt, now) <= REDATE_AFTER_DAYS - ? prior - : record - }) - const ids = new Set(decided.map((record) => record.id)) - const unconfirmed = [...mine.values()].filter((record) => !ids.has(record.id)) - const records = [...unconfirmed, ...decided].sort((a, b) => - a.id.localeCompare(b.id), - ) - return { records, unconfirmed } +/** Removes the key, and its leading and trailing fragments, from a message. */ +export function redactKey(text: string, key: string): string { + let out = text.replaceAll(key, '[key]') + if (key.length >= 16) { + out = out + .replaceAll(key.slice(0, 8), '[key]') + .replaceAll(key.slice(-6), '[key]') + } + return out +} + +/** A 2xx body is cancelled unread: it states nothing, and it bills. */ +export async function sendProbe( + url: string, + body: Record, + key: string, + fetcher: typeof fetch = fetch, +): Promise<{ status: number; text: string }> { + try { + const response = await fetcher(url, { + method: 'POST', + headers: { + authorization: `Bearer ${key}`, + 'content-type': 'application/json', + 'user-agent': 'modelschemas-probe/1', + }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(PROBE_TIMEOUT_MS), + }) + if (response.ok) { + await response.body?.cancel() + return { status: response.status, text: '' } + } + return { status: response.status, text: await response.text() } + } catch { + // The error can quote the request; report only that it failed. + return { status: 0, text: '' } + } } diff --git a/src/server/providers/probes/compare.ts b/src/server/providers/probes/compare.ts index b4d83a0c..2463eb59 100644 --- a/src/server/providers/probes/compare.ts +++ b/src/server/providers/probes/compare.ts @@ -20,16 +20,3 @@ export function observationMatches( } return null } - -/** Replace one record's verifiedAt. Throws when that id is not in the file. */ -export function bumpVerifiedAt( - source: string, - id: string, - date: string, -): string { - const pattern = new RegExp( - `(id: '${id}'[\\s\\S]*?verifiedAt: ')\\d{4}-\\d{2}-\\d{2}(')`, - ) - if (!pattern.test(source)) throw new Error(`probe: no verifiedAt for ${id}`) - return source.replace(pattern, `$1${date}$2`) -} diff --git a/src/server/providers/probes/groq.ts b/src/server/providers/probes/groq.ts deleted file mode 100644 index f59b6557..00000000 --- a/src/server/providers/probes/groq.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ChatCompletionsProbe } from './chat-completions.ts' - -/** Groq on the generic chat probe (issue #717). */ -export const probe: ChatCompletionsProbe = { - provider: 'groq', - url: 'https://api.groq.com/openai/v1/chat/completions', - route: 'openai/v1/chat/completions', - keyEnv: 'GROQ_API_KEY', - models: ['openai/gpt-oss-20b', 'openai/gpt-oss-safeguard-20b'], - // Groq's level list is per model (qwen3 takes `none`, gpt-oss does - // not), and `reasoning_effort` is the gpt-oss models' only control. - mandatoryRule: 'groq', -} diff --git a/src/server/providers/probes/index.ts b/src/server/providers/probes/index.ts index 6b3d6930..b531e612 100644 --- a/src/server/providers/probes/index.ts +++ b/src/server/providers/probes/index.ts @@ -3,37 +3,144 @@ import type { ChatRequestMap } from '../request-map.ts' import { reasoningViolation } from '../types.ts' import type { FactSource, ModelInfo } from '../types.ts' import type { ChatCompletionsProbe } from './chat-completions.ts' -import { probe as groqProbe } from './groq.ts' import { OPENCODE_GO_PROBE_SOURCE, records as opencodeGo, } from './opencode-go.ts' -import { records as groqRecords } from './records/groq.ts' import { probeIsStale } from './types.ts' -import type { ProbedFactRecord, ProbeRecord } from './types.ts' +import type { ProbeRecord, ServedProbeFact } from './types.ts' const SOURCE: Record = { 'opencode-go': OPENCODE_GO_PROBE_SOURCE, } -/** Every committed probe. Add a provider by importing its module here. */ +/** LEGACY hand-written route records (see `ProbeRecord`). */ export const probeRecords: Array = [...opencodeGo] /** - * Providers on the generic `chat/completions` probe (issue #717). Opt in - * with `probes/.ts` exporting a `ChatCompletionsProbe`, an empty - * `records/.ts`, and one entry in each list below. Set - * `mandatoryRule` only for a provider whose `reasoning_effort` level list - * is per model and is the model's only reasoning control. + * Secret name assumed for the LLM Gateway key (not final). The probe reads + * it from here only; llmgateway stays a disabled gateway either way. */ -export const chatProbes: Array = [groqProbe] +export const LLMGATEWAY_KEY_SECRET = 'LLMGATEWAY_API_KEY' -/** Every committed fact a live response stated. */ -export const probedFactRecords: Array = [...groqRecords] +/** + * Providers on the generic `chat/completions` probe (issue #717). `url` is + * the adapter's API server plus the chat route its rows bind + * (`generationEndpointId`); the probe applies only to rows bound to + * exactly `route`. Set `mandatoryRule` only for a provider whose + * `reasoning_effort` level list is per model and is the model's only + * reasoning control. A missing key is a logged skip. + * + * Not here: perplexity (its rows bind `v1/agent`, not chat/completions), + * opencode-go (the Worker holds no key). Gateways and resellers + * (openrouter, vercel, huggingface, lovable, opencode, cloudflare AI + * Gateway) are not listed; llmgateway is listed only to name its secret + * and stays off as a `gateway`. + */ +export const chatProbes: Array = [ + { + provider: 'openai', + url: 'https://api.openai.com/v1/chat/completions', + route: 'chat/completions', + keyEnv: 'OPENAI_API_KEY', + // "'reasoning_effort' does not support 'none' with this model. + // Supported values are: …" is OpenAI's own per-model list. + mandatoryRule: 'openai', + }, + { + provider: 'groq', + url: 'https://api.groq.com/openai/v1/chat/completions', + route: 'openai/v1/chat/completions', + keyEnv: 'GROQ_API_KEY', + // Groq's level list is per model (qwen3 takes `none`, gpt-oss does + // not), and `reasoning_effort` is the gpt-oss models' only control. + mandatoryRule: 'groq', + }, + { + provider: 'cerebras', + url: 'https://api.cerebras.ai/v1/chat/completions', + route: 'v1/chat/completions', + keyEnv: 'CEREBRAS_API_KEY', + }, + { + provider: 'deepseek', + url: 'https://api.deepseek.com/chat/completions', + route: 'chat/completions', + keyEnv: 'DEEPSEEK_API_KEY', + }, + { + provider: 'fireworks', + url: 'https://api.fireworks.ai/inference/v1/chat/completions', + route: 'v1/chat/completions', + keyEnv: 'FIREWORKS_API_KEY', + }, + { + provider: 'together', + url: 'https://api.together.xyz/v1/chat/completions', + route: 'chat/completions', + keyEnv: 'TOGETHER_API_KEY', + }, + { + provider: 'mistral', + url: 'https://api.mistral.ai/v1/chat/completions', + route: 'v1/chat/completions', + keyEnv: 'MISTRAL_API_KEY', + }, + { + provider: 'moonshot', + url: 'https://api.moonshot.ai/v1/chat/completions', + route: 'v1/chat/completions', + keyEnv: 'MOONSHOT_API_KEY', + }, + { + provider: 'novita', + url: 'https://api.novita.ai/openai/v1/chat/completions', + route: 'chat/completions', + keyEnv: 'NOVITA_API_KEY', + }, + { + provider: 'sambanova', + url: 'https://api.sambanova.ai/v1/chat/completions', + route: 'chat/completions', + keyEnv: 'SAMBANOVA_API_KEY', + }, + { + provider: 'hyperbolic', + url: 'https://api.hyperbolic.xyz/v1/chat/completions', + route: 'chat/completions', + keyEnv: 'HYPERBOLIC_API_KEY', + }, + { + provider: 'grok', + url: 'https://api.x.ai/v1/chat/completions', + route: 'v1/chat/completions', + keyEnv: 'XAI_API_KEY', + }, + { + provider: 'dashscope', + url: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions', + route: 'chat/completions', + keyEnv: 'DASHSCOPE_API_KEY', + }, + { + provider: 'baseten', + url: 'https://inference.baseten.co/v1/chat/completions', + route: 'v1/chat/completions', + keyEnv: 'BASETEN_API_KEY', + }, + { + provider: 'llmgateway', + url: 'https://api.llmgateway.io/v1/chat/completions', + route: 'v1/chat/completions', + keyEnv: LLMGATEWAY_KEY_SECRET, + // No captured response shows a 400 in LLM Gateway's own wording rather + // than one forwarded from the upstream; until one does, it stays off. + gateway: true, + }, +] -/** The generated records file of a chat probe provider. */ -export function probedFactFile(provider: string): string { - return `src/server/providers/probes/records/${provider}.ts` +export function chatProbeFor(provider: string): ChatCompletionsProbe | null { + return chatProbes.find((probe) => probe.provider === provider) ?? null } export function probesFor(provider: string): Array { @@ -76,39 +183,41 @@ export function probeFactSource( } } -/** Records whose `verifiedAt` is older than `PROBE_STALE_DAYS`. */ -export function staleProbeCount(provider: string, now = new Date()): number { - return [ - ...probesFor(provider), - ...probedFactRecords.filter((record) => record.provider === provider), - ].filter((record) => probeIsStale(record.verifiedAt, now)).length +/** LEGACY route records whose `verifiedAt` is older than `PROBE_STALE_DAYS`. */ +export function staleRouteRecordCount( + provider: string, + now = new Date(), +): number { + return probesFor(provider).filter((record) => + probeIsStale(record.verifiedAt, now), + ).length } -function probedSource(record: ProbedFactRecord): FactSource { +function probedSource(fact: ServedProbeFact): FactSource { return { derivation: 'probe-verified', - verifiedAt: record.verifiedAt, - sourceUrl: `${probedFactFile(record.provider)}#${record.id}`, + verifiedAt: fact.verifiedAt, + sourceUrl: fact.sourceUrl, } } /** - * Fills a row's empty facts from probe records naming this exact model - * and the route the row binds. A stated value is never replaced: a probe - * fills a gap. `requestMap` is the map the row would store. + * Fills a row's empty facts from served probe facts naming this exact + * model and the route the row binds. A stated value is never replaced: a + * probe fills a gap. `requestMap` is the map the row would store. */ export function withProbedFacts( info: ModelInfo, provider: string, route: string | null, requestMap: ChatRequestMap | null, - records: Array = probedFactRecords, + served: Array, ): ModelInfo { - const mine = records.filter( - (record) => - record.provider === provider && - record.model === info.rawId && - record.route === route, + const mine = served.filter( + (fact) => + fact.provider === provider && + fact.model === info.rawId && + fact.route === route, ) if (mine.length === 0) return info const next: ModelInfo = { ...info, factSources: { ...info.factSources } } diff --git a/src/server/providers/probes/opencode-go.ts b/src/server/providers/probes/opencode-go.ts index 642fb750..5405e87f 100644 --- a/src/server/providers/probes/opencode-go.ts +++ b/src/server/providers/probes/opencode-go.ts @@ -1,6 +1,15 @@ import type { ProbeRecord } from './types.ts' /** + * LEGACY, hand-written (issue #717 left it untouched): the only probe data + * still kept as source. These records bind the two routes below on + * `gemini-4-argon-contributor` (`opencode-catalog.ts`), let the spec sync + * keep them (`opencode-routes.ts`), and set its `trainsOnRequestData` + * (`opencode-go-facts.ts`). go.mdx names only the base path, so no docs + * read can replace them, and the Worker holds no OPENCODE_GO_API_KEY to + * re-observe them. Nothing re-dates them: from 2027-01-22 `/v1/status` + * counts them on `staleProbes`. Replace with a Worker-observed route probe. + * * OpenCode Go Gemini routes probed 2026-10-23 (issue #461). * * go.mdx lists only the base diff --git a/src/server/providers/probes/probes.test.ts b/src/server/providers/probes/probes.test.ts index 5143d4e1..1a5d34c7 100644 --- a/src/server/providers/probes/probes.test.ts +++ b/src/server/providers/probes/probes.test.ts @@ -1,9 +1,7 @@ -import { readFileSync } from 'node:fs' - import { describe, expect, it } from 'vitest' -import { bumpVerifiedAt, observationMatches } from './compare.ts' -import { probeFactSource, probedRoute, staleProbeCount } from './index.ts' +import { observationMatches } from './compare.ts' +import { probeFactSource, probedRoute, staleRouteRecordCount } from './index.ts' import { probeIsStale } from './types.ts' describe('probe records', () => { @@ -35,25 +33,20 @@ describe('probe records', () => { probeIsStale('2026-10-23', new Date('2027-01-22T00:00:00.000Z')), ).toBe(true) expect( - staleProbeCount('opencode-go', new Date('2026-10-23T12:00:00.000Z')), + staleRouteRecordCount( + 'opencode-go', + new Date('2026-10-23T12:00:00.000Z'), + ), ).toBe(0) expect( - staleProbeCount('opencode-go', new Date('2027-01-22T00:00:00.000Z')), + staleRouteRecordCount( + 'opencode-go', + new Date('2027-01-22T00:00:00.000Z'), + ), ).toBe(2) }) - it('bumps one record date and reports a mismatched body', () => { - const source = readFileSync( - new URL('./opencode-go.ts', import.meta.url), - 'utf8', - ) - const next = bumpVerifiedAt( - source, - 'gemini-4-argon-contributor-stream', - '2026-11-01', - ) - expect(next).toContain("verifiedAt: '2026-11-01'") - expect(next).toContain("verifiedAt: '2026-10-23'") + it('reports a mismatched body', () => { expect( observationMatches( { status: 200, jsonKeys: ['candidates'] }, diff --git a/src/server/providers/probes/records/groq.ts b/src/server/providers/probes/records/groq.ts deleted file mode 100644 index f1583666..00000000 --- a/src/server/providers/probes/records/groq.ts +++ /dev/null @@ -1,197 +0,0 @@ -// Written by `pnpm run probe -- groq --write`. Do not edit by hand. -import type { ProbedFactRecord } from '../types.ts' - -export const records: Array = [ - { - id: 'openai/gpt-oss-20b:maxOutput', - provider: 'groq', - model: 'openai/gpt-oss-20b', - fact: 'maxOutput', - value: 65536, - route: 'openai/v1/chat/completions', - verifiedAt: '2026-11-21', - ranBy: 'tom', - request: { - url: 'https://api.groq.com/openai/v1/chat/completions', - body: { - model: 'openai/gpt-oss-20b', - stream: true, - messages: [ - { - role: 'user', - content: 'hi', - }, - ], - max_tokens: 10000000, - }, - }, - evidence: { - status: 400, - message: - '`max_tokens` must be less than or equal to `65536`, the maximum value for `max_tokens` is less than the `context_window` for this model', - }, - }, - { - id: 'openai/gpt-oss-20b:reasoning.mandatory', - provider: 'groq', - model: 'openai/gpt-oss-20b', - fact: 'reasoning.mandatory', - value: true, - route: 'openai/v1/chat/completions', - verifiedAt: '2026-11-21', - ranBy: 'tom', - request: { - url: 'https://api.groq.com/openai/v1/chat/completions', - body: { - model: 'openai/gpt-oss-20b', - stream: true, - max_tokens: 1, - messages: [ - { - role: 'user', - content: 'hi', - }, - ], - reasoning_effort: 'none', - }, - }, - evidence: { - status: 400, - message: '`reasoning_effort` must be one of `low`, `medium`, or `high`', - }, - }, - { - id: 'openai/gpt-oss-20b:replayReasoningContent', - provider: 'groq', - model: 'openai/gpt-oss-20b', - fact: 'replayReasoningContent', - value: false, - route: 'openai/v1/chat/completions', - verifiedAt: '2026-11-21', - ranBy: 'tom', - request: { - url: 'https://api.groq.com/openai/v1/chat/completions', - body: { - model: 'openai/gpt-oss-20b', - stream: true, - max_tokens: 1, - messages: [ - { - role: 'user', - content: 'hi', - }, - { - role: 'assistant', - content: 'ok', - reasoning_content: 'x', - }, - { - role: 'user', - content: 'hi', - }, - ], - }, - }, - evidence: { - status: 400, - message: - "'messages.1' : for 'role:assistant' the following must be satisfied[('messages.1' : property 'reasoning_content' is unsupported)]", - }, - }, - { - id: 'openai/gpt-oss-safeguard-20b:maxOutput', - provider: 'groq', - model: 'openai/gpt-oss-safeguard-20b', - fact: 'maxOutput', - value: 65536, - route: 'openai/v1/chat/completions', - verifiedAt: '2026-11-21', - ranBy: 'tom', - request: { - url: 'https://api.groq.com/openai/v1/chat/completions', - body: { - model: 'openai/gpt-oss-safeguard-20b', - stream: true, - messages: [ - { - role: 'user', - content: 'hi', - }, - ], - max_tokens: 10000000, - }, - }, - evidence: { - status: 400, - message: - '`max_tokens` must be less than or equal to `65536`, the maximum value for `max_tokens` is less than the `context_window` for this model', - }, - }, - { - id: 'openai/gpt-oss-safeguard-20b:reasoning.mandatory', - provider: 'groq', - model: 'openai/gpt-oss-safeguard-20b', - fact: 'reasoning.mandatory', - value: true, - route: 'openai/v1/chat/completions', - verifiedAt: '2026-11-21', - ranBy: 'tom', - request: { - url: 'https://api.groq.com/openai/v1/chat/completions', - body: { - model: 'openai/gpt-oss-safeguard-20b', - stream: true, - max_tokens: 1, - messages: [ - { - role: 'user', - content: 'hi', - }, - ], - reasoning_effort: 'none', - }, - }, - evidence: { - status: 400, - message: '`reasoning_effort` must be one of `low`, `medium`, or `high`', - }, - }, - { - id: 'openai/gpt-oss-safeguard-20b:replayReasoningContent', - provider: 'groq', - model: 'openai/gpt-oss-safeguard-20b', - fact: 'replayReasoningContent', - value: false, - route: 'openai/v1/chat/completions', - verifiedAt: '2026-11-21', - ranBy: 'tom', - request: { - url: 'https://api.groq.com/openai/v1/chat/completions', - body: { - model: 'openai/gpt-oss-safeguard-20b', - stream: true, - max_tokens: 1, - messages: [ - { - role: 'user', - content: 'hi', - }, - { - role: 'assistant', - content: 'ok', - reasoning_content: 'x', - }, - { - role: 'user', - content: 'hi', - }, - ], - }, - }, - evidence: { - status: 400, - message: - "'messages.1' : for 'role:assistant' the following must be satisfied[('messages.1' : property 'reasoning_content' is unsupported)]", - }, - }, -] diff --git a/src/server/providers/probes/types.ts b/src/server/providers/probes/types.ts index 65f0918a..4ecfc512 100644 --- a/src/server/providers/probes/types.ts +++ b/src/server/providers/probes/types.ts @@ -1,10 +1,6 @@ /** - * A live check against a provider API, kept as data (issue #461). - * One module per provider under this directory. Adapters bind a fact only - * when a record names that exact model and route. A record older than - * `PROBE_STALE_DAYS` is still served; `GET /v1/status` counts those as - * `staleProbes`. Re-run with `pnpm run probe -- [--write]`; - * `.source/workflows/probe.ts` runs it weekly for the chat probes. + * A served probe fact older than `PROBE_STALE_DAYS` is still served; + * `GET /v1/status` counts those as `staleProbes`. */ export const PROBE_STALE_DAYS = 90 @@ -24,6 +20,12 @@ export interface ProbeExpect { sse?: boolean } +/** + * LEGACY (issue #461, kept untouched by #717): the hand-written OpenCode Go + * route records in `opencode-go.ts`. Nothing in the Worker re-observes + * them yet, so they are still source, not D1 data. `pnpm run probe -- + * opencode-go` checks them read-only; nothing re-dates them. + */ export interface ProbeRecord { id: string provider: string @@ -54,26 +56,22 @@ export type ProbedFact = | 'reasoning.mandatory' /** - * One fact a live response stated. Written only by - * `pnpm run probe -- --write` into `records/.ts`; - * never by hand. A run that cannot decide leaves the record as it was. + * A probed fact the catalog may serve: two decided observations from + * separate runs agreed (`servedProbeFacts`). Built from `probe_observations` + * rows the Worker wrote from its own live responses; never typed in. */ -export interface ProbedFactRecord { - id: string +export interface ServedProbeFact { provider: string - /** Catalog raw id. A record never applies to another id in the family. */ + /** Catalog raw id. Never applies to another id in the family. */ model: string fact: ProbedFact value: number | boolean - /** Endpoint id the row must bind for the record to apply. */ + /** Endpoint id the row must bind for the fact to apply. */ route: string - /** `YYYY-MM-DD` of the run whose response stated `value`. */ + /** `YYYY-MM-DD` of the newer agreeing observation. */ verifiedAt: string - ranBy: string - /** What was sent, without headers. */ - request: { url: string; body: Record } - /** The status and the error message that stated the value. */ - evidence: { status: number; message: string } + /** The endpoint the probe called. No secrets. */ + sourceUrl: string } const DAY_MS = 86_400_000 diff --git a/src/server/status.ts b/src/server/status.ts index 12e092f9..e244bb4f 100644 --- a/src/server/status.ts +++ b/src/server/status.ts @@ -18,7 +18,8 @@ import type { UpdateStorm, } from '#/server/ingest/docs-failing.ts' import { providerRegistry } from '#/server/providers/index.ts' -import { staleProbeCount } from '#/server/providers/probes/index.ts' +import { staleRouteRecordCount } from '#/server/providers/probes/index.ts' +import { staleProbeCounts } from '#/server/ingest/probe-facts.ts' import { sourceSilentLedger } from '#/server/source-silent.ts' /** One activity's share of `Completeness`; `score` null = no fact set. */ @@ -285,8 +286,11 @@ async function readCompleteness(db: Db): Promise<{ function staleProbeField( providerId: string, nowSeconds: number, + served: Map, ): { staleProbes?: number } { - const stale = staleProbeCount(providerId, new Date(nowSeconds * 1000)) + const stale = + staleRouteRecordCount(providerId, new Date(nowSeconds * 1000)) + + (served.get(providerId) ?? 0) return stale > 0 ? { staleProbes: stale } : {} } @@ -301,6 +305,7 @@ export async function getServiceStatus( modelCounts, endpointCounts, schemaCounts, + staleServed, ] = await Promise.all([ db.select().from(providers), // One statement for every provider's docs-failing, refused-clears, and update-storm row. @@ -330,6 +335,8 @@ export async function getServiceStatus( .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id)) .where(isNull(schemaVersions.supersededAt)) .groupBy(endpoints.providerId), + // Served probe facts past PROBE_STALE_DAYS (probe_observations). + staleProbeCounts(db, new Date(now * 1000)), ]) const toMap = (rows: Array<{ providerId: string; n: number }>) => @@ -367,7 +374,7 @@ export async function getServiceStatus( lastPolledAt: p.lastPolledAt, lastSyncedAt: p.lastSyncedAt, ...records.get(p.id), - ...staleProbeField(p.id, now), + ...staleProbeField(p.id, now, staleServed), completeness: completeness(p.id), counts: { models: modelsBy.get(p.id)?.models ?? 0, @@ -389,7 +396,7 @@ export async function getServiceStatus( status: 'pending', lastPolledAt: null, lastSyncedAt: null, - ...staleProbeField(config.id, now), + ...staleProbeField(config.id, now, staleServed), completeness: completeness(config.id), counts: { models: 0, diff --git a/src/worker.ts b/src/worker.ts index 886b864a..7715071d 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -33,6 +33,7 @@ import { specSyncShard, syncAllProviders, } from '#/server/ingest/sync.ts' +import { PROBE_CRON, runProbes } from '#/server/ingest/probe-facts.ts' import { recordCompleteness } from '#/server/status.ts' import { recordRowShape } from '#/server/row-shape.ts' import { runWebhookTick } from '#/server/webhooks.ts' @@ -306,6 +307,16 @@ export default { ) return } + // Live fact probes (issue #717): their own hourly firing, so the + // request cap and subrequests never share the 15-minute poll's budget. + if (controller.cron === PROBE_CRON) { + ctx.waitUntil( + runProbes({ db: getDb(env), secrets: env }).then((outcome) => { + console.log(JSON.stringify({ job: 'probe-run', outcome })) + }), + ) + return + } if (controller.cron === VERCEL_PRICING_EXTRACT_CRON) { ctx.waitUntil( extractVercelPricing(syncDeps(env)).then((outcome) => { diff --git a/wrangler.jsonc b/wrangler.jsonc index d53d04f7..ba674f60 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -39,8 +39,11 @@ // FAL spec-sync shard's subrequest/CPU budget. Vercel per-model // /endpoints prices are one daily firing (VERCEL_PRICING_EXTRACT_CRON) // for the same reason: ~60 subrequests must not share the poll budget. + // Live fact probes are hourly at :07 (PROBE_CRON in + // src/server/ingest/probe-facts.ts), capped by PROBE_REQUEST_BUDGET. "crons": [ "*/15 * * * *", + "7 * * * *", "0 4 * * *", "0 5 * * *", "10 5 * * *", From e983b122272c787545d982297c660a743f8984b3 Mon Sep 17 00:00:00 2001 From: Tom Beckenham <34339192+tombeckenham@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:03:56 +1100 Subject: [PATCH 2/2] Confirm before new, send only checks a rule reads, report probe failures, require a cron interval between agreeing runs Review fixes for #742: confirm candidates sort before the new backlog so a value reaches two observations; each provider lists its checks and only openai (limits, off), groq (limits, replay, off) and mistral (replay) are enabled; the probe cron reports a failure as ingest_failed and rethrows; two agreeing observations must be PROBE_RUN_GAP_SECONDS apart. --- CLAUDE.md | 26 ++++-- src/server/ingest/ingest-signals.ts | 1 + src/server/ingest/probe-facts.ts | 54 ++++++++++- src/server/ingest/probe-facts.worker.test.ts | 62 ++++++++++++- .../providers/probes/chat-completions.test.ts | 2 +- .../providers/probes/chat-completions.ts | 15 ++- src/server/providers/probes/index.ts | 91 +++++-------------- src/worker.ts | 12 ++- 8 files changed, 172 insertions(+), 91 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2c7d4bd1..c53b79d2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -245,15 +245,23 @@ ones). facts live in D1, never in source (#717): the Worker's own probe cron (`PROBE_CRON`, hourly at :07, `src/server/ingest/probe-facts.ts`) appends one `probe_observations` row per request it sent (value null - when the response stated nothing). It probes a chat row of an enabled - provider (`chatProbes` in `probes/index.ts`) once when a probeable fact - is empty and unobserved, re-probes an unconfirmed value next run, and - re-verifies anything `REVERIFY_AFTER_DAYS` (7) old, under - `PROBE_REQUEST_BUDGET` (12) and `PROBE_PROVIDER_BUDGET` (4) per - invocation. A value is served only when the two newest decided - observations, from separate runs, agree; the poll fills only empty facts - from them (`loadServedProbeFacts` → `withProbedFacts`). A missing key is - a logged skip; a `gateway` entry is never probed. Audit with + when the response stated nothing). Per invocation, under + `PROBE_REQUEST_BUDGET` (12) and `PROBE_PROVIDER_BUDGET` (4), it first + confirms a decided but unserved value, then probes a chat row of an + enabled provider (`chatProbes` in `probes/index.ts`) whose probeable + fact is empty and unobserved, then re-verifies anything + `REVERIFY_AFTER_DAYS` (7) old. A value is served only when the two + newest decided observations, at least `PROBE_RUN_GAP_SECONDS` (one cron + interval) apart, agree; the poll fills only empty facts from them + (`loadServedProbeFacts` → `withProbedFacts`). A failed run is reported + as `ingest_failed` (job `probe`). A missing key is a logged skip; a + `gateway` entry is never probed. Each provider lists its `checks`: only + checks a rule reads in its own wording (openai `limits`+`off`, groq + `limits`+`replay`+`off`, mistral `replay`), so every request is an + expected 400, never a billed completion. "Probe everything new" means + every new model of a listed provider. Add a provider in its own PR: + capture its responses with the dry run below, add a rule and the + fixture, then list only the checks that decide. Audit with `GET /v1/admin/probes/{provider}[?model=]`. A served fact older than 90 days stays served; `GET /v1/status` counts it on `staleProbes`. `pnpm run probe -- ` is a read-only local dry run. diff --git a/src/server/ingest/ingest-signals.ts b/src/server/ingest/ingest-signals.ts index 08ef2f5d..744953c7 100644 --- a/src/server/ingest/ingest-signals.ts +++ b/src/server/ingest/ingest-signals.ts @@ -18,6 +18,7 @@ export type IngestJob = | 'fal-pricing-extract' | 'vercel-pricing-extract' | 'same-as-reconcile' + | 'probe' export type IngestEvent = | { diff --git a/src/server/ingest/probe-facts.ts b/src/server/ingest/probe-facts.ts index e07d5923..e23d1de9 100644 --- a/src/server/ingest/probe-facts.ts +++ b/src/server/ingest/probe-facts.ts @@ -32,11 +32,23 @@ import type { ProbedFact, ServedProbeFact, } from '#/server/providers/probes/types.ts' +import { errorMessage } from '#/server/errors.ts' import { resolveSchemaEndpointId } from '#/server/schema-binding.ts' +import { + captureIngestEvents, + ingestFailedEvent, + noteIngest, + runIngestScope, +} from './ingest-signals.ts' import type { Activity } from '#/db/schema.ts' /** Hourly at :07, its own invocation, after the :00 models poll. */ export const PROBE_CRON = '7 * * * *' +/** + * One `PROBE_CRON` interval. Two agreeing observations must be at least + * this far apart (`observed_at` is the firing's scheduled time). + */ +export const PROBE_RUN_GAP_SECONDS = 3_600 /** Hard cap on provider requests per cron invocation (all providers). */ export const PROBE_REQUEST_BUDGET = 12 /** Hard cap on requests to one provider per cron invocation. */ @@ -68,7 +80,9 @@ function newestFirst(a: Observation, b: Observation): number { /** * The two observations that decide a fact: the newest decided one and the - * newest decided one from another run. Served when both exist and agree. + * newest decided one at least `PROBE_RUN_GAP_SECONDS` older. Served when + * both exist and agree. The gap, not the run id, keeps two overlapping + * invocations (one moment) from counting as two runs. */ function decidingPair( history: Array, @@ -76,7 +90,12 @@ function decidingPair( const decided = history.filter((row) => row.value !== null).sort(newestFirst) const newest = decided[0] if (!newest) return null - return [newest, decided.find((row) => row.runId !== newest.runId)] + return [ + newest, + decided.find( + (row) => row.observedAt <= newest.observedAt - PROBE_RUN_GAP_SECONDS, + ), + ] } function groupByKey(rows: Array): Map> { @@ -218,8 +237,9 @@ export interface PlannedProbe { /** * Which probes this invocation sends, in order, under both caps: + * - `confirm`: the newest attempt was decided but is not served yet, and + * is at least `PROBE_RUN_GAP_SECONDS` old; * - `new`: the row's fact is empty and it has no observation at all; - * - `confirm`: the newest attempt was decided but is not served yet; * - `reverify`: the newest attempt is `REVERIFY_AFTER_DAYS` old, oldest * first (an undecided fact only while the row still lacks it). * New and confirm interleave providers so one provider cannot starve the @@ -277,6 +297,8 @@ export function planProbes( pair[1] !== undefined && pair[0].value === pair[1].value if (latest.value !== null && !servedNow) { + // Too soon to count as a second run: confirm on a later firing. + if (latest.observedAt > now - PROBE_RUN_GAP_SECONDS) continue candidates.push({ ...base, reason: 'confirm', @@ -295,7 +317,9 @@ export function planProbes( }) } } - const tier: Record = { new: 0, confirm: 1, reverify: 2 } + // Confirm first: it is bounded by the decided, unserved values, and + // behind a long `new` backlog nothing would ever be served. + const tier: Record = { confirm: 0, new: 1, reverify: 2 } candidates.sort( (a, b) => tier[a.reason] - tier[b.reason] || a.order - b.order, ) @@ -456,3 +480,25 @@ export async function runProbes(deps: ProbeDeps): Promise { } return outcome } + +/** + * The cron entry. A failure part way (D1, say) is logged and reported as + * `ingest_failed` (job `probe`), then rethrown so the invocation fails; + * the rest of the plan is the next firing's backlog. + */ +export async function runProbeCron( + deps: ProbeDeps & { posthogKey?: string }, +): Promise { + return runIngestScope(async () => { + try { + return await runProbes(deps) + } catch (error) { + const message = errorMessage(error) + console.error(JSON.stringify({ job: 'probe', error: message })) + noteIngest(ingestFailedEvent('probe', '*', message)) + throw error + } finally { + await captureIngestEvents(deps.posthogKey) + } + }) +} diff --git a/src/server/ingest/probe-facts.worker.test.ts b/src/server/ingest/probe-facts.worker.test.ts index dc28a56f..4b2c0ec7 100644 --- a/src/server/ingest/probe-facts.worker.test.ts +++ b/src/server/ingest/probe-facts.worker.test.ts @@ -7,12 +7,14 @@ import { models } from '#/db/schema.ts' import { pollProviderModels } from '#/server/ingest/poll-models.ts' import { PROBE_PROVIDER_BUDGET, + PROBE_RUN_GAP_SECONDS, PROBE_REQUEST_BUDGET, REVERIFY_AFTER_DAYS, loadServedProbeFacts, planProbes, readProbeObservations, runProbes, + servedProbeFacts, staleProbeCounts, } from '#/server/ingest/probe-facts.ts' import type { SyncDeps } from '#/server/ingest/sync.ts' @@ -80,7 +82,7 @@ describe('probe cron (#717)', () => { // Run 1: first appearance. Only the row with an empty fact is probed. const sent: Array> = [] - const first = await run(T0 + 60, 65536, sent) + const first = await run(T0, 65536, sent) const limits = sent.filter((body) => body.max_tokens === 10_000_000) expect(limits.map((body) => body.model)).toEqual(['lab/fresh']) expect(sent.some((body) => body.model === 'lab/embed')).toBe(false) @@ -90,6 +92,11 @@ describe('probe cron (#717)', () => { expect(stored.every((row) => !row.served)).toBe(true) // One observation is stored, not served. expect(await loadServedProbeFacts(getDb(env), 'groq')).toEqual([]) + // An overlapping invocation a minute later sends nothing: too soon to + // be a second run. + const overlap: Array> = [] + await run(T0 + 60, 65536, overlap) + expect(overlap).toEqual([]) await poll(T0 + 120, listed) expect((await storedMaxOutput('lab/fresh')).maxOutput).toBeNull() @@ -181,6 +188,7 @@ describe('planProbes', () => { url: `https://${provider}.example/v1/chat/completions`, route: 'v1/chat/completions', keyEnv: 'K', + checks: ['limits', 'replay'], }), ) const row = ( @@ -254,4 +262,56 @@ describe('planProbes', () => { ['newer', 'reverify'], ]) }) + + const decided = ( + providerId: string, + rawId: string, + observedAt: number, + id: number, + value: number, + ) => ({ + id, + runId: `run-${id}`, + providerId, + rawId, + route: 'v1/chat/completions', + fact: 'maxOutput', + value, + status: 400, + message: 'stated', + observedAt, + }) + + it('plans a confirm before any new backlog', () => { + const three = probes.slice(0, 3) + const rows = three.flatMap((probe) => + Array.from({ length: 5 }, (_, i) => row(probe.provider, `m${i}`)), + ) + rows.push(row('c', 'waiting')) + const { planned } = planProbes( + rows, + [decided('c', 'waiting', T0 - PROBE_RUN_GAP_SECONDS, 1, 4096)], + three, + T0, + ) + expect(planned[0]).toMatchObject({ + rawId: 'waiting', + reason: 'confirm', + check: 'limits', + }) + }) + + it('serves two agreeing observations only a cron interval apart', () => { + const close = servedProbeFacts([ + decided('groq', 'm', T0, 1, 4096), + decided('groq', 'm', T0 + PROBE_RUN_GAP_SECONDS - 1, 2, 4096), + ]) + expect(close.served).toEqual([]) + const apart = servedProbeFacts([ + decided('groq', 'm', T0, 1, 4096), + decided('groq', 'm', T0 + PROBE_RUN_GAP_SECONDS, 2, 4096), + ]) + expect(apart.served).toHaveLength(1) + expect(apart.servingIds).toEqual(new Set([1, 2])) + }) }) diff --git a/src/server/providers/probes/chat-completions.test.ts b/src/server/providers/probes/chat-completions.test.ts index a5cbc7b4..323d4512 100644 --- a/src/server/providers/probes/chat-completions.test.ts +++ b/src/server/providers/probes/chat-completions.test.ts @@ -81,7 +81,7 @@ describe('classifyProbeResponse', () => { ).toHaveProperty('undecided') expect( probeChecks({ ...chatProbes[0]!, mandatoryRule: undefined }), - ).toEqual(['limits', 'replay']) + ).toEqual(['limits']) }) it('records nothing when the level list has an off value', () => { diff --git a/src/server/providers/probes/chat-completions.ts b/src/server/providers/probes/chat-completions.ts index 73ef1792..f58d76c4 100644 --- a/src/server/providers/probes/chat-completions.ts +++ b/src/server/providers/probes/chat-completions.ts @@ -34,16 +34,23 @@ export interface ChatCompletionsProbe { * no `off` request is sent. */ mandatoryRule?: MandatoryRule + /** + * The checks the cron sends, and only these: each must be one for which + * a rule below reads this provider's own wording, shown by a captured + * fixture. Every request is then an expected 400, never a billed + * completion no rule can read. + */ + checks: Array } export type MandatoryRule = 'groq' | 'openai' export type ProbeCheck = 'limits' | 'replay' | 'off' -/** The checks one provider's run sends per model. */ +/** The checks one provider's run sends per model. `off` needs the opt-in. */ export function probeChecks(probe: ChatCompletionsProbe): Array { - return probe.mandatoryRule - ? ['limits', 'replay', 'off'] - : ['limits', 'replay'] + return probe.checks.filter( + (check) => check !== 'off' || probe.mandatoryRule !== undefined, + ) } /** The fact each check can state. */ diff --git a/src/server/providers/probes/index.ts b/src/server/providers/probes/index.ts index b531e612..a69b35ca 100644 --- a/src/server/providers/probes/index.ts +++ b/src/server/providers/probes/index.ts @@ -31,10 +31,20 @@ export const LLMGATEWAY_KEY_SECRET = 'LLMGATEWAY_API_KEY' * `reasoning_effort` level list is per model and is the model's only * reasoning control. A missing key is a logged skip. * - * Not here: perplexity (its rows bind `v1/agent`, not chat/completions), - * opencode-go (the Worker holds no key). Gateways and resellers - * (openrouter, vercel, huggingface, lovable, opencode, cloudflare AI - * Gateway) are not listed; llmgateway is listed only to name its secret + * `checks` lists only the checks a rule reads in that provider's own + * wording (a captured fixture shows it), so every request is an expected + * 400. "Probe everything new" means every new model of a provider listed + * here. To add a provider: capture its responses with the read-only + * `pnpm run probe -- ` (add its entry first with the + * checks to try), add a rule to `classifyProbeResponse` and the body to + * `fixtures/probe-responses.json`, then list only the checks that decide. + * Never list a check its provider answers with a 2xx: that is a billed + * completion no rule can read. + * + * Not here: providers whose captured responses no rule reads yet (the + * fixtures show Fireworks, Together and xAI answer `limits` with a 200), + * perplexity (rows bind `v1/agent`), opencode-go (no key). Gateways and + * resellers are not listed; llmgateway is listed only to name its secret * and stays off as a `gateway`. */ export const chatProbes: Array = [ @@ -46,6 +56,8 @@ export const chatProbes: Array = [ // "'reasoning_effort' does not support 'none' with this model. // Supported values are: …" is OpenAI's own per-model list. mandatoryRule: 'openai', + // `replay` is a 200 on OpenAI (fixture openai-replay-gpt-4o-mini). + checks: ['limits', 'off'], }, { provider: 'groq', @@ -55,78 +67,16 @@ export const chatProbes: Array = [ // Groq's level list is per model (qwen3 takes `none`, gpt-oss does // not), and `reasoning_effort` is the gpt-oss models' only control. mandatoryRule: 'groq', - }, - { - provider: 'cerebras', - url: 'https://api.cerebras.ai/v1/chat/completions', - route: 'v1/chat/completions', - keyEnv: 'CEREBRAS_API_KEY', - }, - { - provider: 'deepseek', - url: 'https://api.deepseek.com/chat/completions', - route: 'chat/completions', - keyEnv: 'DEEPSEEK_API_KEY', - }, - { - provider: 'fireworks', - url: 'https://api.fireworks.ai/inference/v1/chat/completions', - route: 'v1/chat/completions', - keyEnv: 'FIREWORKS_API_KEY', - }, - { - provider: 'together', - url: 'https://api.together.xyz/v1/chat/completions', - route: 'chat/completions', - keyEnv: 'TOGETHER_API_KEY', + checks: ['limits', 'replay', 'off'], }, { provider: 'mistral', url: 'https://api.mistral.ai/v1/chat/completions', route: 'v1/chat/completions', keyEnv: 'MISTRAL_API_KEY', - }, - { - provider: 'moonshot', - url: 'https://api.moonshot.ai/v1/chat/completions', - route: 'v1/chat/completions', - keyEnv: 'MOONSHOT_API_KEY', - }, - { - provider: 'novita', - url: 'https://api.novita.ai/openai/v1/chat/completions', - route: 'chat/completions', - keyEnv: 'NOVITA_API_KEY', - }, - { - provider: 'sambanova', - url: 'https://api.sambanova.ai/v1/chat/completions', - route: 'chat/completions', - keyEnv: 'SAMBANOVA_API_KEY', - }, - { - provider: 'hyperbolic', - url: 'https://api.hyperbolic.xyz/v1/chat/completions', - route: 'chat/completions', - keyEnv: 'HYPERBOLIC_API_KEY', - }, - { - provider: 'grok', - url: 'https://api.x.ai/v1/chat/completions', - route: 'v1/chat/completions', - keyEnv: 'XAI_API_KEY', - }, - { - provider: 'dashscope', - url: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions', - route: 'chat/completions', - keyEnv: 'DASHSCOPE_API_KEY', - }, - { - provider: 'baseten', - url: 'https://inference.baseten.co/v1/chat/completions', - route: 'v1/chat/completions', - keyEnv: 'BASETEN_API_KEY', + // `limits` is a 200 on Mistral (fixture mistral-limits-codestral-2508); + // `replay` is a pydantic 422 the replay rule reads. + checks: ['replay'], }, { provider: 'llmgateway', @@ -136,6 +86,7 @@ export const chatProbes: Array = [ // No captured response shows a 400 in LLM Gateway's own wording rather // than one forwarded from the upstream; until one does, it stays off. gateway: true, + checks: [], }, ] diff --git a/src/worker.ts b/src/worker.ts index 7715071d..29dde5f3 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -33,7 +33,7 @@ import { specSyncShard, syncAllProviders, } from '#/server/ingest/sync.ts' -import { PROBE_CRON, runProbes } from '#/server/ingest/probe-facts.ts' +import { PROBE_CRON, runProbeCron } from '#/server/ingest/probe-facts.ts' import { recordCompleteness } from '#/server/status.ts' import { recordRowShape } from '#/server/row-shape.ts' import { runWebhookTick } from '#/server/webhooks.ts' @@ -311,7 +311,15 @@ export default { // request cap and subrequests never share the 15-minute poll's budget. if (controller.cron === PROBE_CRON) { ctx.waitUntil( - runProbes({ db: getDb(env), secrets: env }).then((outcome) => { + // `observed_at` is the firing's scheduled time, so two firings are + // exactly PROBE_RUN_GAP_SECONDS apart and an overlap is not. + // runProbeCron reports a failure as ingest_failed and rethrows. + runProbeCron({ + db: getDb(env), + secrets: env, + now: () => Math.floor(controller.scheduledTime / 1000), + posthogKey: env.POSTHOG_PROJECT_KEY, + }).then((outcome) => { console.log(JSON.stringify({ job: 'probe-run', outcome })) }), )