diff --git a/evals/docs/build-docs-033-timeouts/EVAL.ts b/evals/docs/build-docs-033-timeouts/EVAL.ts new file mode 100644 index 00000000..5e2a14fb --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/EVAL.ts @@ -0,0 +1,71 @@ +import { + buildDocsResult, + type CheckResult, + type LocalStackEvalContext, + type LocalStackScorer, +} from '@supabase-evals/core'; +import { + applyPendingMigrations, + checkMigrationsWereApplied, +} from './migrations.js'; +import { + checkCutOff, + checkJobFinishes, + checkQuickFinishes, + checkReloaded, + probeTimeouts, +} from './probes.js'; + +const GUIDE_PATH = 'guides/database/postgres/timeouts'; + +const scorer: LocalStackScorer = async (ctx) => { + try { + // Pending migrations first, so a role setting written into a migration + // and never applied costs one check. One round of calls through the Data + // API then feeds the four checks after it. + const migrations = await applyPendingMigrations(ctx); + const probe = await probeTimeouts(ctx); + + const checks: CheckResult[] = [ + checkMigrationsWereApplied(migrations), + checkReloaded(probe), + checkQuickFinishes(probe), + checkCutOff(probe), + checkJobFinishes(probe), + checkGuideWasRead(ctx), + ]; + + return { passed: checks.every((check) => check.passed), checks }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { + passed: false, + checks: [ + { + name: 'scorer evaluated the query timeouts', + passed: false, + notes: message, + }, + ], + }; + } +}; + +export default scorer; + +function checkGuideWasRead(ctx: LocalStackEvalContext): CheckResult { + const calls = buildDocsResult(ctx.toolCalls).calls.filter((call) => + call.pages?.some((page) => page.url.includes(GUIDE_PATH)) + ); + const withContent = calls.filter((call) => call.hasContent); + return { + name: 'the agent read the timeouts guide the prompt referenced', + passed: withContent.length > 0, + notes: + withContent.length > 0 + ? withContent.map((call) => call.source).join(', ') + : calls.length > 0 + ? `reached the guide via ${calls.map((call) => call.source).join(', ')} but retrieved no page content` + : 'no docs call reached the guide', + }; +} diff --git a/evals/docs/build-docs-033-timeouts/PROMPT.md b/evals/docs/build-docs-033-timeouts/PROMPT.md new file mode 100644 index 00000000..5db47936 --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/PROMPT.md @@ -0,0 +1,38 @@ +--- +stage: build +interface: cli +product: + - data-api + - database +topic: + - sql +services: + - gotrue + - kong + - postgrest +motivation: >- + A runaway query that nobody cuts off keeps a database busy for everyone. This + checks that an agent reading the Timeouts guide limits how long a signed-out + visitor's query may run without touching the server job that legitimately + runs longer. The guide lists the per-role defaults and the reload that the + Data API needs, but not that a change set on a role is invisible to it until + then. The prompt omits the page's vocabulary on purpose, so read README.md + before editing it. +--- + +Brightwater's public report page calls the monthly report, and the report takes +about 4 seconds. When a few visitors open the page at once the whole database +crawls. A signed-out visitor's query should be cut off after one second instead +of being left to run. Visitors only ever need the quick ones. + +The nightly job (app/nightly.mjs) builds the same report with the project's +secret key. It takes its 4 seconds and has always finished, so it must keep +finishing. + +Make that so on my local project. + +Read the guide below before you start and rely on it for how to set this up, +rather than on what you already know. + +REFERENCE +https://supabase.com/docs/guides/database/postgres/timeouts.md diff --git a/evals/docs/build-docs-033-timeouts/README.md b/evals/docs/build-docs-033-timeouts/README.md new file mode 100644 index 00000000..6a7334c2 --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/README.md @@ -0,0 +1,149 @@ +# build-docs-033-timeouts + +## What this eval measures + +The [Timeouts](https://supabase.com/docs/guides/database/postgres/timeouts) guide, not the agent. The prompt is a +product request plus the page's url, and the checks say whether an agent that read the page left a project where a +signed-out visitor's slow query is cancelled and the server's own job still finishes. + +One claim: **a role's statement timeout cancels a slow query.** The page lists four levels, session, function, role +and global, with the defaults for the Data API's roles (`anon` 3s, `authenticated` 8s, `service_role` none, so the +`authenticator` role's 8s, `postgres` none). It says a role's timeout is changed with +`alter role set statement_timeout = '…'`, and that "for Supabase Client API calls, PostgREST must be reloaded for +changes to take effect" with `NOTIFY pgrst, 'reload config';`. + +## Confirming the claim + +The ticket's claim is a reading of the page, so I tried it on a real local stack (CLI 2.117.0, `gotrue`, `kong` and +`postgrest` only) with a function that sleeps, called through the Data API. + +- **Confirmed: the defaults.** `pg_roles.rolconfig` reads `anon` 3s, `authenticated` 8s, `authenticator` 8s, and + `service_role` and `postgres` carry no timeout. A 6 second call as a visitor came back `500` with code `57014` + (`canceling statement due to statement timeout`) after 3.0 seconds. The same call with the secret key finished. +- **Confirmed: a role's setting cancels the call.** After `alter role anon set statement_timeout = '1s'` and a reload, + the visitor call was cancelled after 1.0 seconds, and a 0.3 second call still finished. +- **Confirmed: the reload matters.** Right after the `alter role`, with no reload, the Data API still cancelled at 3.0 + seconds. After `NOTIFY pgrst, 'reload config'` it cancelled at 1.0. Nothing reloads it for an `alter role`, so a + setting written into a migration is invisible to visitors until something does. +- **Not confirmed: hosted behavior.** The Dashboard's 60 second ceiling, the pooler modes and the logs are not + measurable on a local stack. + +## Does an existing eval cover it? + +No. `statement_timeout` appears in `evals/cli/deploy-database-006-push-and-verify-remote` and +`evals/cli/resolve-database-004-reconcile-migration-history`, both only in test files that run SQL, and no eval has a +docs page about timeouts as its subject. `build-docs-025-postgres-roles` and `build-docs-020-securing-your-api` are +about what a role may read, not how long it may run. + +## Where the checks came from + +No user evidence for this page turned up, which the ticket said to expect. + +- **Reached:** the page and the real stack above. +- **Out of reach:** Linear, Slack, Hex, the internal report. `supabase/agent-skills` has nothing on timeouts. + +The reload check comes from the stack as much as the page. The page says the reload is needed and says nothing about +what an agent sees when it is missing: a role that reads back correctly from `pg_roles` and a slow query that still runs +to the old limit. + +## Do not reintroduce the vocabulary + +Keep all of these out of `PROMPT.md`: + +timeout, statement timeout, `statement_timeout`, cancel, role, `alter role`, reload, `pgrst`, `NOTIFY`, `pg_sleep`, +session, global, function-level, pooler. + +"Cut off after one second", "left to run" and "the whole database crawls" are how the user says it. + +## The seed carries the contract + +- `local/supabase/migrations/20240101000000_create_slow_report.sql` creates `public.slow_report(pause_seconds)`, which + sleeps and returns `done`, executable by `anon`, `authenticated` and `service_role`. The scorer needs a call that can be + made slow on purpose, and the function is the report the prompt describes. It buys an observable answer at the cost of + the agent not designing the query. The migration's header says it has already run and that anything new goes in a new + file. Without it an agent can append to the file that already ran, and the change never reaches the database. +- `local/app/report.mjs` (publishable key) and `local/app/nightly.mjs` (secret key) are the two callers. The nightly job + is the conflict: the same function, a call that must take its full 4 seconds. A function-level timeout cancels it, + and so does a timeout on the secret key's role, so only a timeout on the visitor's role satisfies both. +- No role is touched in the seed, so every timeout in the project is the platform's default. +- `services: gotrue, kong, postgrest`. Storage and the rest aren't needed. `gotrue` is there because `supabase status` + reports no keys without it. + +## How the scorer works, and why in this order + +1. **Apply pending migrations**, so a setting written into a migration and never applied costs one check. +2. **One quick visitor call, then one slow one.** A 0.3 second call must finish, which is the control. A 4 second call + must be cancelled in under 2.5 seconds. The user asks for one second and the default is 3, so anything cancelled + by 2.5 seconds was set by the agent, and 2 seconds passes as well. +3. **Reload only if needed.** When the slow call was not cancelled in time, the scorer sends `NOTIFY pgrst, 'reload + config'`, waits, and calls again. If that call is cancelled in time, the setting was right and the reload was + missing, which costs `the Data API was reloaded after the role was changed` and nothing else, because the cut-off + check then reads the reloaded state. +4. **The job's call last**, 4 seconds with the secret key. + +Refusals are read from the response's error code `57014` and the time the call took. 503s while PostgREST reloads +are retried and don't count towards the time. A typical correct run spends about 6 seconds in the probes, the +worst case about 15. + +## Do not drop the positive controls + +An agent that built nothing, and one that set a timeout so short everything is cancelled, both cancel slow queries. + +- `a visitor's quick query still finishes` separates a limit from a wall. When it fails, the cut-off check fails with + a `not run` note instead of passing for a role that runs nothing. +- `the nightly job's 4 second query still finishes` is what stops a global or function-level answer. It is the only + check that fails a solution that cancels everyone. +- The reload check passes when the reload changed nothing, so a project with no timeout set doesn't fail it as well as + the cut-off check. Its notes say `nothing to reload`. + +## What each check proves + +| Check | Proves | +| --- | --- | +| `the agent applied the migrations it wrote` | Nothing the agent wrote is left unapplied. | +| `the Data API was reloaded after the role was changed` | A setting that cancels slow queries is live without the scorer's help. | +| `a visitor's quick query still finishes` | The visitor's timeout is not so short that it breaks real queries. | +| `a visitor's slow query is cut off within 2.5 seconds` | The visitor's role has a timeout under about 2.5 seconds, live in the Data API. | +| `the nightly job's 4 second query still finishes` | The timeout is on the visitor's role and not on everyone. | +| `the agent read the timeouts guide the prompt referenced` | The page was opened with content. | + +## Predictions, and what the probes were run against + +The probes ran against the real stack above, with each state of the settings written directly. Predictions were +written first and all held. + +| State of the project | Red | +| --- | --- | +| `anon` at 1s or at 2s, reloaded | none | +| `anon` at 1s, never reloaded | reloaded | +| nothing changed | cut-off | +| function-level 1s | job | +| `anon` and `service_role` at 1s | job | +| `anon` at 100ms | quick, and cut-off as `not run` | +| `anon` raised to 10s | cut-off | + +## The guide has to actually be read + +`the agent read the timeouts guide the prompt referenced` fails unless a docs call returned the page's content. Read +`docs.calls` before the score. + +## What this eval does not score + +- **Signed-in users (`authenticated`).** The prompt is about visitors. Signing up adds the token-timing problem seen in + `build-docs-020`. +- **Direct and pooler connections, and session-level `set`.** The page says a session setting doesn't reach the Data + API. The probes only use the Data API. +- **Global timeouts.** `alter database` leaves a role that has its own setting alone, so a global answer fails the + cut-off check for the right reason. The value is not probed. +- **Lock and idle timeouts, and the 60 second Dashboard ceiling.** Not on the local stack. +- **Reading timeout logs.** The page describes the Dashboard's Explorer. Not asked for. +- **The exact boundary.** One second is asked for and 2.5 seconds is the line, because the platform's default is + 3 seconds. +- **How the setting was persisted.** A migration, `psql` and a seed all land in `pg_roles`. Whether it survives a reset + is `build-docs-020`'s kind of claim. + +## Risks + +- **The reload is the scorer's, not the agent's, when it is missing.** The scorer sends `reload config` itself, so + the reload check is a diagnostic. It passes for a project that set nothing. +- **Refresh twice before describing how agents fail.** One baseline's failure mode is not the eval's. diff --git a/evals/docs/build-docs-033-timeouts/local/app/nightly.mjs b/evals/docs/build-docs-033-timeouts/local/app/nightly.mjs new file mode 100644 index 00000000..edc8bdb3 --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/local/app/nightly.mjs @@ -0,0 +1,13 @@ +// The nightly job. It runs on our server with the secret key and builds the +// same report for the archive. It takes about 4 seconds and has always +// finished. +import { createClient } from '@supabase/supabase-js'; + +const supabase = createClient( + process.env.SUPABASE_URL, + process.env.SUPABASE_SECRET_KEY +); + +const { data, error } = await supabase.rpc('slow_report'); +if (error) throw error; +console.log('archived', data); diff --git a/evals/docs/build-docs-033-timeouts/local/app/report.mjs b/evals/docs/build-docs-033-timeouts/local/app/report.mjs new file mode 100644 index 00000000..8d29aa3a --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/local/app/report.mjs @@ -0,0 +1,14 @@ +// The public report page. Visitors are never signed in, so it calls the +// project with the publishable key. +import { createClient } from '@supabase/supabase-js'; + +const supabase = createClient( + process.env.SUPABASE_URL, + process.env.SUPABASE_PUBLISHABLE_KEY +); + +export async function showReport() { + const { data, error } = await supabase.rpc('slow_report'); + if (error) throw error; + return data; +} diff --git a/evals/docs/build-docs-033-timeouts/local/supabase/config.toml b/evals/docs/build-docs-033-timeouts/local/supabase/config.toml new file mode 100644 index 00000000..8dacbb61 --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/local/supabase/config.toml @@ -0,0 +1,165 @@ +project_id = "sandbox-timeouts" + +[api] +enabled = true +port = 54321 +schemas = ["public", "graphql_public"] +extra_search_path = ["public", "extensions"] +max_rows = 1000 + +[api.tls] +enabled = false + +[db] +port = 54322 +shadow_port = 54320 +major_version = 17 + +[db.pooler] +enabled = false +port = 54329 +pool_mode = "transaction" +default_pool_size = 20 +max_client_conn = 100 + +[db.migrations] +enabled = true +schema_paths = [] + +[db.seed] +enabled = false + +[realtime] +enabled = true + +[studio] +enabled = true +port = 54323 +api_url = "http://127.0.0.1" +openai_api_key = "env(OPENAI_API_KEY)" + +[inbucket] +enabled = true +port = 54324 + +[storage] +enabled = true +file_size_limit = "50MiB" + +[storage.s3_protocol] +enabled = true + +[storage.analytics] +enabled = false +max_namespaces = 5 +max_tables = 10 +max_catalogs = 2 + +[storage.vector] +enabled = false +max_buckets = 10 +max_indexes = 5 + +[auth] +enabled = true +site_url = "http://127.0.0.1:3000" +additional_redirect_urls = ["https://127.0.0.1:3000"] +jwt_expiry = 3600 +enable_refresh_token_rotation = true +refresh_token_reuse_interval = 10 +enable_signup = true +enable_anonymous_sign_ins = false +enable_manual_linking = false +minimum_password_length = 6 +password_requirements = "" + +[auth.rate_limit] +email_sent = 2 +sms_sent = 30 +anonymous_users = 30 +token_refresh = 150 +sign_in_sign_ups = 30 +token_verifications = 30 +web3 = 30 + +[auth.email] +enable_signup = true +double_confirm_changes = true +enable_confirmations = false +secure_password_change = false +max_frequency = "1s" +otp_length = 6 +otp_expiry = 3600 + +[auth.sms] +enable_signup = false +enable_confirmations = false +template = "Your code is {{ .Code }}" +max_frequency = "5s" + +[auth.sms.twilio] +enabled = false +account_sid = "" +message_service_sid = "" +auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" + +[auth.mfa] +max_enrolled_factors = 10 + +[auth.mfa.totp] +enroll_enabled = false +verify_enabled = false + +[auth.mfa.phone] +enroll_enabled = false +verify_enabled = false +otp_length = 6 +template = "Your code is {{ .Code }}" +max_frequency = "5s" + +[auth.external.apple] +enabled = false +client_id = "" +secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)" +redirect_uri = "" +url = "" +skip_nonce_check = false +email_optional = false + +[auth.web3.solana] +enabled = false + +[auth.third_party.firebase] +enabled = false + +[auth.third_party.auth0] +enabled = false + +[auth.third_party.aws_cognito] +enabled = false + +[auth.third_party.clerk] +enabled = false + +[auth.oauth_server] +enabled = false +authorization_url_path = "/oauth/consent" +allow_dynamic_registration = false + +[edge_runtime] +enabled = true +policy = "per_worker" +inspector_port = 8083 +deno_version = 2 + +[analytics] +enabled = true +port = 54327 +backend = "postgres" + +[experimental] +orioledb_version = "" +s3_host = "env(S3_HOST)" +s3_region = "env(S3_REGION)" +s3_access_key = "env(S3_ACCESS_KEY)" +s3_secret_key = "env(S3_SECRET_KEY)" diff --git a/evals/docs/build-docs-033-timeouts/local/supabase/migrations/20240101000000_create_slow_report.sql b/evals/docs/build-docs-033-timeouts/local/supabase/migrations/20240101000000_create_slow_report.sql new file mode 100644 index 00000000..210fa253 --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/local/supabase/migrations/20240101000000_create_slow_report.sql @@ -0,0 +1,17 @@ +-- This migration has already run on every environment. Anything new goes in a +-- new migration file, never in this one. + +-- The monthly report. The pause stands in for how long the real one takes, +-- about 4 seconds on a full month. +create function public.slow_report(pause_seconds numeric default 4) +returns text +language plpgsql +as $$ +begin + perform pg_sleep(pause_seconds); + return 'done'; +end; +$$; + +grant execute on function public.slow_report(numeric) + to anon, authenticated, service_role; diff --git a/evals/docs/build-docs-033-timeouts/migrations.ts b/evals/docs/build-docs-033-timeouts/migrations.ts new file mode 100644 index 00000000..89f75cab --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/migrations.ts @@ -0,0 +1,97 @@ +import { readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import type { CheckResult, LocalStackEvalContext } from '@supabase-evals/core'; + +export type MigrationState = { + pending: string[]; + applyFailed?: string; +}; + +export async function applyPendingMigrations( + ctx: LocalStackEvalContext +): Promise { + try { + return await apply(ctx); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { pending: ['unknown'], applyFailed: message.slice(0, 300) }; + } +} + +async function apply(ctx: LocalStackEvalContext): Promise { + const pending = await pendingVersions(ctx); + + if (pending.length === 0) { + return { pending }; + } + + const applied = await ctx.exec('supabase migration up --local', { + timeoutMs: 300_000, + }); + if (applied.exitCode !== 0) { + return { + pending, + applyFailed: firstError( + `${applied.stderr ?? ''}\n${applied.stdout ?? ''}` + ), + }; + } + return { pending }; +} + +export function checkMigrationsWereApplied(state: MigrationState): CheckResult { + return { + name: 'the agent applied the migrations it wrote', + passed: state.pending.length === 0, + notes: + state.pending.length === 0 + ? 'nothing pending' + : state.applyFailed + ? `pending: ${state.pending.join(', ')}; the scorer could not apply them: ${state.applyFailed}` + : `pending: ${state.pending.join(', ')}; the scorer applied them so the rest of the checks could run`, + }; +} + +async function pendingVersions(ctx: LocalStackEvalContext): Promise { + const onDisk = migrationVersionsOnDisk(ctx.hostWorkspace); + if (onDisk.length === 0) { + return []; + } + + const { rows: history } = await ctx.query( + "SELECT to_regclass('supabase_migrations.schema_migrations') IS NOT NULL AS present;" + ); + if (history[0]?.present !== true) { + return onDisk; + } + + const { rows } = await ctx.query( + 'SELECT version FROM supabase_migrations.schema_migrations;' + ); + const applied = new Set(rows.map((row) => String(row.version))); + return onDisk.filter((version) => !applied.has(version)); +} + +function migrationVersionsOnDisk(hostWorkspace: string): string[] { + let entries: string[]; + try { + entries = readdirSync(join(hostWorkspace, 'supabase', 'migrations')); + } catch { + return []; + } + return entries + .map((entry) => /^(\d+)(?:_.*)?\.sql$/.exec(entry)?.[1]) + .filter((version): version is string => version !== undefined) + .sort(); +} + +function firstError(output: string): string { + const lines = output + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0); + const named = lines.find((line) => + /^(ERROR|FATAL|DETAIL|HINT)\b/i.test(line) + ); + return (named ?? lines[0] ?? 'no output').slice(0, 300); +} diff --git a/evals/docs/build-docs-033-timeouts/probes.ts b/evals/docs/build-docs-033-timeouts/probes.ts new file mode 100644 index 00000000..a1aa8459 --- /dev/null +++ b/evals/docs/build-docs-033-timeouts/probes.ts @@ -0,0 +1,193 @@ +import type { CheckResult, LocalStackEvalContext } from '@supabase-evals/core'; +import { execSql } from '../lib/exec-sql.js'; + +export const CHECK = { + reloaded: 'the Data API was reloaded after the role was changed', + quick: "a visitor's quick query still finishes", + cutOff: "a visitor's slow query is cut off within 2.5 seconds", + job: "the nightly job's 4 second query still finishes", +} as const; + +// The user asks for one second. Anon's default is 3 seconds, so anything the +// scorer sees cancelled by 2.5 seconds was set by the agent, and 2 seconds or +// 1.5 seconds pass as well. +const CUT_OFF_BY_MS = 2500; +const SLOW = 4; +const QUICK = 0.3; +const JOB = 4; + +type Call = { status: number; code?: string; ms: number; body: string }; + +export type Probe = + | { ok: false; reason: string } + | { + ok: true; + quick: Call; + /** The slow visitor call the cut-off check reads. */ + slow: Call; + /** The slow visitor call before the scorer reloaded the Data API. */ + beforeReload: Call; + reloadMadeTheDifference: boolean; + job: Call; + anonSetting: string; + }; + +const short = (text: string) => text.replace(/\s+/g, ' ').slice(0, 160); +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const finished = (call: Call) => call.status === 200 && call.body === '"done"'; +const cut = (call: Call) => call.code === '57014' && call.ms < CUT_OFF_BY_MS; + +/** + * One round of calls to the function, as a visitor and as the server key, + * through the Data API. The role settings only reach it after a reload, so a + * visitor call that isn't cut off is repeated after the scorer reloads, and + * the reload is what the lifecycle check reads. + */ +export async function probeTimeouts( + ctx: LocalStackEvalContext +): Promise { + try { + const stack = await ctx.stackStatus(); + const visitor = (seconds: number) => + call(stack.apiUrl, stack.publishableKey, seconds); + const server = (seconds: number) => + call(stack.apiUrl, stack.secretKey, seconds); + + const quick = await visitor(QUICK); + const beforeReload = await visitor(SLOW); + let slow = beforeReload; + let reloadMadeTheDifference = false; + if (!cut(beforeReload)) { + await execSql(ctx, "notify pgrst, 'reload config';"); + await sleep(1500); + slow = await visitor(SLOW); + reloadMadeTheDifference = cut(slow); + } + const job = await server(JOB); + return { + ok: true, + quick, + slow, + beforeReload, + reloadMadeTheDifference, + job, + anonSetting: await anonSetting(ctx), + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { ok: false, reason: message.slice(0, 300) }; + } +} + +async function call( + apiUrl: string, + key: string, + seconds: number +): Promise { + // A key in the new format is not a JWT, so it only goes in `apikey`. + const headers: Record = { + apikey: key, + 'Content-Type': 'application/json', + }; + if (key.split('.').length === 3) headers.Authorization = `Bearer ${key}`; + let last: Call = { status: 0, ms: 0, body: 'no response' }; + // PostgREST answers 503 while it reloads its schema cache. The retries do + // not count towards the time the call took. + for (let attempt = 0; attempt < 6; attempt++) { + const started = Date.now(); + try { + const response = await fetch(`${apiUrl}/rest/v1/rpc/slow_report`, { + method: 'POST', + headers, + body: JSON.stringify({ pause_seconds: seconds }), + }); + const text = await response.text(); + let code: string | undefined; + try { + code = JSON.parse(text)?.code; + } catch {} + last = { + status: response.status, + code, + ms: Date.now() - started, + body: short(text), + }; + } catch (error) { + last = { + status: 0, + ms: Date.now() - started, + body: error instanceof Error ? error.message : String(error), + }; + } + if (last.status !== 503 && last.status !== 0) return last; + await sleep(1000); + } + return last; +} + +async function anonSetting(ctx: LocalStackEvalContext): Promise { + const { rows } = await ctx.query( + "select rolconfig::text as config from pg_roles where rolname = 'anon';" + ); + return String(rows[0]?.config ?? 'no setting'); +} + +function blocked(name: string, reason: string): CheckResult { + return { name, passed: false, notes: `not run: ${reason}` }; +} + +// Passes when the reload made no difference: a project with no timeout set has +// nothing to reload, and its cut-off check carries the failure. +export function checkReloaded(probe: Probe): CheckResult { + if (!probe.ok) return blocked(CHECK.reloaded, probe.reason); + return { + name: CHECK.reloaded, + passed: !probe.reloadMadeTheDifference, + notes: probe.reloadMadeTheDifference + ? `the role's setting was not live in the Data API until the scorer reloaded it (anon: ${probe.anonSetting}); the first call ran ${probe.beforeReload.ms} ms` + : cut(probe.beforeReload) + ? `live without a reload (anon: ${probe.anonSetting})` + : `nothing to reload: reloading changed nothing (anon: ${probe.anonSetting})`, + }; +} + +// The control for the cut-off check: a visitor limited to nothing at all would +// pass it. +export function checkQuickFinishes(probe: Probe): CheckResult { + if (!probe.ok) return blocked(CHECK.quick, probe.reason); + return { + name: CHECK.quick, + passed: finished(probe.quick), + notes: finished(probe.quick) + ? `finished in ${probe.quick.ms} ms` + : `${probe.quick.code ?? probe.quick.status} after ${probe.quick.ms} ms: ${probe.quick.body} (anon: ${probe.anonSetting})`, + }; +} + +export function checkCutOff(probe: Probe): CheckResult { + if (!probe.ok) return blocked(CHECK.cutOff, probe.reason); + if (!finished(probe.quick)) { + return blocked( + CHECK.cutOff, + `a quick visitor query did not finish (see "${CHECK.quick}")` + ); + } + return { + name: CHECK.cutOff, + passed: cut(probe.slow), + notes: cut(probe.slow) + ? `cancelled after ${probe.slow.ms} ms` + : `${probe.slow.code ?? probe.slow.status} after ${probe.slow.ms} ms: ${probe.slow.body} (anon: ${probe.anonSetting})`, + }; +} + +export function checkJobFinishes(probe: Probe): CheckResult { + if (!probe.ok) return blocked(CHECK.job, probe.reason); + return { + name: CHECK.job, + passed: finished(probe.job), + notes: finished(probe.job) + ? `finished in ${probe.job.ms} ms` + : `${probe.job.code ?? probe.job.status} after ${probe.job.ms} ms: ${probe.job.body}`, + }; +}