From 9f97c2d49dad09d8d7463f1be80ebebe122de2c5 Mon Sep 17 00:00:00 2001 From: Miranda Limonczenko Date: Wed, 25 Nov 2026 12:05:45 -0800 Subject: [PATCH 1/2] feat(docs): add a Postgres Changes guide eval --- .../EVAL.ts | 86 +++ .../PROMPT.md | 36 ++ .../README.md | 79 +++ .../local/ORDER_SCREEN.md | 18 + .../local/app/order-updates.ts | 56 ++ .../local/supabase/config.toml | 165 ++++++ .../migrations/20240101000000_init.sql | 30 ++ .../migrations.ts | 97 ++++ .../probes.ts | 491 ++++++++++++++++++ 9 files changed, 1058 insertions(+) create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/EVAL.ts create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/PROMPT.md create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/README.md create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/local/ORDER_SCREEN.md create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/local/app/order-updates.ts create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/local/supabase/config.toml create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/local/supabase/migrations/20240101000000_init.sql create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/migrations.ts create mode 100644 evals/docs/build-docs-040-realtime-postgres-changes/probes.ts diff --git a/evals/docs/build-docs-040-realtime-postgres-changes/EVAL.ts b/evals/docs/build-docs-040-realtime-postgres-changes/EVAL.ts new file mode 100644 index 00000000..3344c965 --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/EVAL.ts @@ -0,0 +1,86 @@ +import { + buildDocsResult, + type CheckResult, + type LocalStackEvalContext, + type LocalStackScorer, +} from '@supabase-evals/core'; +import { execSql } from '../lib/exec-sql.js'; +import { + applyPendingMigrations, + checkMigrationsWereApplied, +} from './migrations.js'; +import { + CHECK, + checkBanner, + checkDeleted, + checkInserted, + checkOthers, + checkPrevious, + checkUpdated, + checkVisitor, + type Observation, + observe, + type Run, +} from './probes.js'; + +const GUIDE_PATH = 'guides/realtime/postgres-changes'; + +const scorer: LocalStackScorer = async (ctx) => { + try { + const migrations = await applyPendingMigrations(ctx); + const run: Run = (sql) => execSql(ctx, sql, { tuplesOnly: true }); + const observed = await observe(ctx, run); + const probe = ( + name: string, + check: (observation: Observation) => CheckResult + ): CheckResult => + 'observation' in observed + ? check(observed.observation) + : { name, passed: false, notes: `not run: ${observed.failure}` }; + + const checks: CheckResult[] = [ + checkMigrationsWereApplied(migrations), + probe(CHECK.inserted, (observation) => checkInserted(observation)), + probe(CHECK.updated, (observation) => checkUpdated(observation)), + probe(CHECK.previous, (observation) => checkPrevious(observation)), + probe(CHECK.deleted, (observation) => checkDeleted(observation)), + probe(CHECK.others, (observation) => checkOthers(observation)), + probe(CHECK.visitor, (observation) => checkVisitor(observation)), + probe(CHECK.banner, (observation) => checkBanner(observation)), + 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 who gets order changes live', + 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 Postgres Changes 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-040-realtime-postgres-changes/PROMPT.md b/evals/docs/build-docs-040-realtime-postgres-changes/PROMPT.md new file mode 100644 index 00000000..c1e8d7a3 --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/PROMPT.md @@ -0,0 +1,36 @@ +--- +stage: build +interface: cli +product: + - realtime + - database +topic: + - rls + - security +services: + - gotrue + - kong + - postgrest + - realtime +motivation: >- + A screen that should update by itself stays still, or shows rows to people + who should never see them. Customers and agents make a table send changes + and stop there, so a signed-in subscriber gets nothing, or open the table to + everyone so they do. This checks that an agent reading the Postgres Changes + guide gets each change to the customer who owns the row, with what it was + before, and to nobody else. The prompt omits the guide's vocabulary on + purpose, so read README.md before editing it. +--- + +The order screen in our app is supposed to update by itself when the shop +changes an order, but customers see nothing until they reopen the app. +ORDER_SCREEN.md says what the screen should do. That version of the app is +already out, so the fix has to be on the Supabase side. Customers must only +ever see their own orders. Make the change in the local project and make sure +it works on the local database. + +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/realtime/postgres-changes.md diff --git a/evals/docs/build-docs-040-realtime-postgres-changes/README.md b/evals/docs/build-docs-040-realtime-postgres-changes/README.md new file mode 100644 index 00000000..8567b822 --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/README.md @@ -0,0 +1,79 @@ +# build-docs-040-realtime-postgres-changes + +## What this eval measures + +The subject is [Postgres Changes](https://supabase.com/docs/guides/realtime/postgres-changes), 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 gets a table's changes to +the right subscribers. + +One claim: a signed-in customer receives each change to their own orders as it happens, with the status it had before, +and nobody else receives it. + +## Do not reintroduce the vocabulary + +Keep all of these out of `PROMPT.md`: + +realtime, live, postgres changes, publication, supabase_realtime, replication, replica identity, old record, payload, +RLS, row level security, policy, select, grant, authenticated, anon, auth.uid, JWT, token, subscribe, channel, filter, +broadcast. + +The seed is the world the user already has, so its client code uses `postgres_changes` and a filter as shipped code +would. + +## The seed carries the contract + +- `local/app/order-updates.ts` is the shipped client. It listens to every event on `orders` with + `customer_id=eq.` and reads the old status on an update. `local/ORDER_SCREEN.md` says the code cannot change. + The scorer listens with exactly this subscription, so the work is on the database side. +- `orders` has row level security on and no read rule, because the app read orders through its backend. A customer + receives nothing until a rule lets them read their own rows. +- `orders` is not sent to subscribers. `shop_status` already is, and anyone can read it. It is the banner the scorer uses + as a positive control. The banner check stays scored because an agent that rebuilds the publication breaks a feature + that works today. +- `enable_confirmations = false`, so the scorer's customers sign up with a session at once. + +## Do not drop the positive controls + +`a customer gets no changes to another customer's orders` and `a visitor who is not signed in gets no order changes` pass +for a project that sends nothing. Each one fails as could-not-measure unless the same connection receives something it +is allowed to: the other customer's own order, or the visitor's banner change plus the owner's new order. The leak +probes listen with no filter, as a client that edits the shipped code would. + +The visitor check also requires the server to accept the visitor's subscription to `orders`. A correct project accepts +it and then sends the visitor nothing, so a refusal is could-not-measure, not a pass. + +Every row the scorer writes carries a marker scoped to the run, and the changes are written after the listeners connect. + +## How the checks read the end state + +- The scorer applies pending migrations first with `supabase migration up --local`, so an unapplied migration costs one + check. That writes to the database, so score a workspace once per stack. +- It signs up two customers, then listens host-side through supabase-js: the owner with the shipped subscription, the + other customer and a signed-out visitor with no filter, and the visitor on the banner. It waits for the server to + answer each subscription before writing. +- On a stack where nobody has listened yet, the first change after the first subscription can be lost while the server + starts delivering. So the scorer first changes the banner and waits up to 30 seconds for it to reach the visitor. If it + never arrives, the checks that then fail say the result could not be measured. +- As the superuser it adds an order for each customer, changes the owner's order from packed to shipped, changes the + banner, and deletes the owner's order. It waits up to 20 seconds for the expected changes, then 3 more for leaks. +- Deletes are left out of both leak checks. Realtime sends a delete to every subscriber whose filter matches, carrying + only the primary key when row level security is on. That is the platform's behavior, not the agent's. +- A filtered delete and the old status both need the table to send whole old rows. One missing setting fails both + checks. + +## The guide has to actually be read + +`the agent read the Postgres Changes guide the prompt referenced` requires a docs call that reached the page with +content. Read `docs.calls` before reading a score. + +## Checks expected to saturate + +The migration check and the banner check. The signal is expected in the owner's three arrival checks, the old status, and +the two leak checks. + +## What this eval does not score + +- **The agent's client code.** The client is shipped and fixed, so the scorer replays it. +- **Deletes reaching other subscribers.** The platform decides what a delete carries. +- **Custom tokens, private schemas, column selection and scaling.** Each is a separate claim. +- **Hosted projects.** The dashboard's publication toggle is out of reach locally. diff --git a/evals/docs/build-docs-040-realtime-postgres-changes/local/ORDER_SCREEN.md b/evals/docs/build-docs-040-realtime-postgres-changes/local/ORDER_SCREEN.md new file mode 100644 index 00000000..454d050c --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/local/ORDER_SCREEN.md @@ -0,0 +1,18 @@ +# Order screen + +Version 4.2 of the Leafline app is in both app stores. Once a customer signs in, its order screen calls +`watchMyOrders` in `app/order-updates.ts`. That code ships inside the app, so it stays as it is until the next +release. + +The order screen should: + +- show a new order as soon as the shop creates it, +- show each status change with the status before and after, for example "was packed, now shipped", +- drop an order from the list as soon as the shop deletes it. + +Shop staff create, update and delete orders from the back office, which connects with the server key. The app +has always loaded orders through our backend, never straight from the database. + +Customers see their own orders and nobody else's. People who have not signed in see no orders at all. + +The open or closed banner at the top of every screen already updates by itself, for visitors and customers. diff --git a/evals/docs/build-docs-040-realtime-postgres-changes/local/app/order-updates.ts b/evals/docs/build-docs-040-realtime-postgres-changes/local/app/order-updates.ts new file mode 100644 index 00000000..2b5f46b8 --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/local/app/order-updates.ts @@ -0,0 +1,56 @@ +import type { + RealtimePostgresChangesPayload, + SupabaseClient, +} from '@supabase/supabase-js'; + +export type Order = { + id: number; + customer_id: string; + item: string; + status: 'placed' | 'packed' | 'shipped' | 'delivered'; + updated_at: string; +}; + +export type OrderScreen = { + addOrder: (order: Order) => void; + showStatusChange: (orderId: number, from: string, to: string) => void; + removeOrder: (orderId: number) => void; +}; + +export async function watchMyOrders( + supabase: SupabaseClient, + screen: OrderScreen +) { + const { + data: { user }, + } = await supabase.auth.getUser(); + if (!user) throw new Error('Sign in first'); + + return supabase + .channel(`my-orders-${user.id}`) + .on( + 'postgres_changes', + { + event: '*', + schema: 'public', + table: 'orders', + filter: `customer_id=eq.${user.id}`, + }, + (payload: RealtimePostgresChangesPayload) => { + if (payload.eventType === 'INSERT') { + screen.addOrder(payload.new); + } + if (payload.eventType === 'UPDATE') { + screen.showStatusChange( + payload.new.id, + payload.old.status ?? '', + payload.new.status + ); + } + if (payload.eventType === 'DELETE' && payload.old.id !== undefined) { + screen.removeOrder(payload.old.id); + } + } + ) + .subscribe(); +} diff --git a/evals/docs/build-docs-040-realtime-postgres-changes/local/supabase/config.toml b/evals/docs/build-docs-040-realtime-postgres-changes/local/supabase/config.toml new file mode 100644 index 00000000..0b63cbe4 --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/local/supabase/config.toml @@ -0,0 +1,165 @@ +project_id = "sandbox-realtime-postgres-changes" + +[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-040-realtime-postgres-changes/local/supabase/migrations/20240101000000_init.sql b/evals/docs/build-docs-040-realtime-postgres-changes/local/supabase/migrations/20240101000000_init.sql new file mode 100644 index 00000000..8ceeca9f --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/local/supabase/migrations/20240101000000_init.sql @@ -0,0 +1,30 @@ +create table public.orders ( + id bigint generated always as identity primary key, + customer_id uuid not null references auth.users (id) on delete cascade, + item text not null, + status text not null default 'placed' + check (status in ('placed', 'packed', 'shipped', 'delivered')), + updated_at timestamptz not null default now() +); + +create index orders_customer_id_idx on public.orders (customer_id); + +alter table public.orders enable row level security; + +create table public.shop_status ( + id int primary key, + is_open boolean not null, + message text not null +); + +alter table public.shop_status enable row level security; + +create policy "Everyone can see whether the shop is open" + on public.shop_status for select + to anon, authenticated + using (true); + +insert into public.shop_status (id, is_open, message) +values (1, true, 'Open until 6pm'); + +alter publication supabase_realtime add table public.shop_status; diff --git a/evals/docs/build-docs-040-realtime-postgres-changes/migrations.ts b/evals/docs/build-docs-040-realtime-postgres-changes/migrations.ts new file mode 100644 index 00000000..89f75cab --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/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-040-realtime-postgres-changes/probes.ts b/evals/docs/build-docs-040-realtime-postgres-changes/probes.ts new file mode 100644 index 00000000..ef3f2b7d --- /dev/null +++ b/evals/docs/build-docs-040-realtime-postgres-changes/probes.ts @@ -0,0 +1,491 @@ +import { randomUUID } from 'node:crypto'; +import type { + CheckResult, + LocalStackEvalContext, + SupabaseClient, +} from '@supabase-evals/core'; +import type { SqlResult } from '../lib/exec-sql.js'; +import { messageOf } from '../lib/local-stack.js'; + +export const CHECK = { + inserted: "a customer's order screen gets a new order as the shop creates it", + updated: "a customer's order screen gets a status change on their order", + previous: 'a status change carries the status the order had before', + deleted: "a customer's order screen drops an order the shop deletes", + others: "a customer gets no changes to another customer's orders", + visitor: 'a visitor who is not signed in gets no order changes', + banner: 'the open or closed banner still updates live', +} as const; + +const PASSWORD = 'leafline-secret-123'; +const READY_TIMEOUT_MS = 30_000; +const WARMUP_TIMEOUT_MS = 30_000; +const EVENT_TIMEOUT_MS = 20_000; +const QUIET_MS = 3_000; + +export type Run = (sql: string) => Promise; + +type Row = Record; + +type Change = { eventType: string; new: Row; old: Row }; + +type SystemMessage = { status?: string; message?: string; extension?: string }; + +type Listener = { + label: string; + changes: Change[]; + system: SystemMessage[]; + statuses: string[]; +}; + +export type Observation = { + marker: string; + ownerId: string; + orderId: string; + owner: Listener; + other: Listener; + visitorOrders: Listener; + visitorBanner: Listener; + warmup?: string; +}; + +export type Observed = { observation: Observation } | { failure: string }; + +export async function observe( + ctx: LocalStackEvalContext, + run: Run +): Promise { + const marker = `leaf-${randomUUID().slice(0, 8)}`; + const clients: SupabaseClient[] = []; + try { + const owner = await signUp(ctx, `${marker}-owner@example.test`); + if ('failure' in owner) return owner; + const other = await signUp(ctx, `${marker}-other@example.test`); + if ('failure' in other) return other; + const visitor = await ctx.getClient(); + clients.push(owner.client, other.client, visitor); + + const listeners = { + owner: listen(owner.client, `my-orders-${owner.id}`, 'orders', { + filter: `customer_id=eq.${owner.id}`, + }), + other: listen(other.client, `${marker}-other`, 'orders'), + visitorOrders: listen(visitor, `${marker}-visitor-orders`, 'orders'), + visitorBanner: listen(visitor, `${marker}-visitor-banner`, 'shop_status'), + }; + + const ready = await Promise.all( + Object.values(listeners).map((entry) => entry.ready) + ); + const stuck = ready.filter((problem): problem is string => !!problem); + if (stuck.length > 0) { + return { + failure: `the scorer could not listen for changes: ${stuck.join('; ')}`, + }; + } + + const warmup = await warmUp(run, marker, listeners.visitorBanner.listener); + const written = await writeChanges(run, marker, owner.id, other.id); + if ('failure' in written) return written; + + const observation: Observation = { + marker, + ownerId: owner.id, + orderId: written.orderId, + owner: listeners.owner.listener, + other: listeners.other.listener, + visitorOrders: listeners.visitorOrders.listener, + visitorBanner: listeners.visitorBanner.listener, + warmup, + }; + + await waitForPositives(observation); + await sleep(QUIET_MS); + return { observation }; + } catch (error) { + return { failure: messageOf(error) }; + } finally { + await Promise.all( + clients.map((client) => client.removeAllChannels().catch(() => [])) + ); + } +} + +async function signUp( + ctx: LocalStackEvalContext, + email: string +): Promise<{ client: SupabaseClient; id: string } | { failure: string }> { + const client = await ctx.getClient(); + const { data, error } = await client.auth.signUp({ + email, + password: PASSWORD, + }); + if (error || !data.user || !data.session) { + return { + failure: `a customer could not sign up: ${error?.message ?? 'no session'}`, + }; + } + return { client, id: data.user.id }; +} + +function listen( + client: SupabaseClient, + topic: string, + table: string, + options: { filter?: string } = {} +): { listener: Listener; ready: Promise } { + const listener: Listener = { + label: `${table} as ${topic}`, + changes: [], + system: [], + statuses: [], + }; + const ready = new Promise((resolve) => { + const timer = setTimeout(() => { + resolve( + `${listener.label} did not connect within ${READY_TIMEOUT_MS / 1000}s (${listener.statuses.join(', ') || 'no status'})` + ); + }, READY_TIMEOUT_MS); + const settle = () => { + if ( + listener.statuses.includes('SUBSCRIBED') && + answer(listener) !== undefined + ) { + clearTimeout(timer); + resolve(undefined); + } + }; + client + .channel(topic) + .on('system', {}, (payload: SystemMessage) => { + listener.system.push(payload); + settle(); + }) + .on( + 'postgres_changes', + { event: '*', schema: 'public', table, ...options }, + (payload: Change) => { + listener.changes.push({ + eventType: payload.eventType, + new: payload.new ?? {}, + old: payload.old ?? {}, + }); + } + ) + .subscribe((status: string, error?: Error) => { + listener.statuses.push(error ? `${status} ${error.message}` : status); + if (status === 'CHANNEL_ERROR' || status === 'TIMED_OUT') { + clearTimeout(timer); + resolve(`${listener.label}: ${status} ${error?.message ?? ''}`); + return; + } + settle(); + }); + }); + return { listener, ready }; +} + +function answer(listener: Listener): SystemMessage | undefined { + return listener.system.find( + (message) => message.extension === 'postgres_changes' + ); +} + +function accepted(listener: Listener): boolean { + return answer(listener)?.status === 'ok'; +} + +async function warmUp( + run: Run, + marker: string, + banner: Listener +): Promise { + const message = `${marker} warming up`; + const result = await run( + `update public.shop_status set message = ${literal(message)} where id = 1;` + ); + if (!result.ok) { + return `the scorer could not change the banner before the orders: ${result.message}`; + } + const deadline = Date.now() + WARMUP_TIMEOUT_MS; + while (Date.now() < deadline) { + if ( + banner.changes.some( + (change) => + change.eventType === 'UPDATE' && change.new.message === message + ) + ) { + return undefined; + } + await sleep(250); + } + return `the banner change sent before the orders never arrived within ${WARMUP_TIMEOUT_MS / 1000}s, so the stack may not have been delivering changes yet${systemNote(banner)}`; +} + +async function writeChanges( + run: Run, + marker: string, + ownerId: string, + otherId: string +): Promise<{ orderId: string } | { failure: string }> { + const inserted = await run( + `insert into public.orders (customer_id, item, status) values (${literal(ownerId)}, ${literal(`${marker} fern`)}, 'packed') returning id;` + ); + const orderId = inserted.stdout.trim().split('\n')[0]?.trim() ?? ''; + if (!inserted.ok || !/^\d+$/.test(orderId)) { + return { failure: `could not add an order: ${inserted.message}` }; + } + const steps = [ + `insert into public.orders (customer_id, item, status) values (${literal(otherId)}, ${literal(`${marker} cactus`)}, 'placed');`, + `update public.orders set status = 'shipped', updated_at = now() where id = ${orderId};`, + `update public.shop_status set message = ${literal(`${marker} closing early`)} where id = 1;`, + `delete from public.orders where id = ${orderId};`, + ]; + for (const step of steps) { + await sleep(300); + const result = await run(step); + if (!result.ok) { + return { failure: `could not change the data: ${result.message}` }; + } + } + return { orderId }; +} + +async function waitForPositives(observation: Observation): Promise { + const deadline = Date.now() + EVENT_TIMEOUT_MS; + while (Date.now() < deadline) { + const arrived = + ownerInsert(observation) && + ownerUpdate(observation) && + ownerDelete(observation) && + otherOwnInsert(observation) && + bannerUpdate(observation); + if (arrived) return; + await sleep(250); + } +} + +function ownerInsert(observation: Observation): Change | undefined { + return observation.owner.changes.find( + (change) => + change.eventType === 'INSERT' && + change.new.item === `${observation.marker} fern` + ); +} + +function ownerUpdate(observation: Observation): Change | undefined { + return observation.owner.changes.find( + (change) => + change.eventType === 'UPDATE' && + String(change.new.id) === observation.orderId && + change.new.status === 'shipped' + ); +} + +function ownerDelete(observation: Observation): Change | undefined { + return observation.owner.changes.find( + (change) => + change.eventType === 'DELETE' && + String(change.old.id) === observation.orderId + ); +} + +function otherOwnInsert(observation: Observation): Change | undefined { + return observation.other.changes.find( + (change) => + change.eventType === 'INSERT' && + change.new.item === `${observation.marker} cactus` + ); +} + +function bannerUpdate(observation: Observation): Change | undefined { + return observation.visitorBanner.changes.find( + (change) => + change.eventType === 'UPDATE' && + change.new.message === `${observation.marker} closing early` + ); +} + +function ownerOrderLeaks( + observation: Observation, + listener: Listener +): Change[] { + return listener.changes.filter( + (change) => + change.eventType !== 'DELETE' && + (change.new.customer_id === observation.ownerId || + String(change.new.item ?? '').startsWith(`${observation.marker} fern`)) + ); +} + +export function checkInserted(observation: Observation): CheckResult { + return arrival( + CHECK.inserted, + observation, + ownerInsert(observation), + 'the new order arrived on the screen' + ); +} + +export function checkUpdated(observation: Observation): CheckResult { + return arrival( + CHECK.updated, + observation, + ownerUpdate(observation), + 'the change to shipped arrived on the screen' + ); +} + +export function checkPrevious(observation: Observation): CheckResult { + const change = ownerUpdate(observation); + if (!change) { + return { + name: CHECK.previous, + passed: false, + notes: `no status change arrived, so there was no earlier status to read${systemNote(observation.owner)}${warmupNote(observation)}`, + }; + } + const before = change.old.status; + return { + name: CHECK.previous, + passed: before === 'packed', + notes: + before === 'packed' + ? 'the change says it was packed before' + : `the change carries no earlier status: old is ${JSON.stringify(change.old)}`, + }; +} + +export function checkDeleted(observation: Observation): CheckResult { + return arrival( + CHECK.deleted, + observation, + ownerDelete(observation), + 'the deletion arrived on the screen' + ); +} + +export function checkOthers(observation: Observation): CheckResult { + const leaks = ownerOrderLeaks(observation, observation.other); + if (leaks.length > 0) { + return { + name: CHECK.others, + passed: false, + notes: `another customer listening to every order got ${describe(leaks)}`, + }; + } + if (!otherOwnInsert(observation)) { + return { + name: CHECK.others, + passed: false, + notes: `could not measure: the other customer did not get a change to their own order either${systemNote(observation.other)}${warmupNote(observation)}`, + }; + } + return { + name: CHECK.others, + passed: true, + notes: + "another customer listening to every order got their own order and nothing of the first customer's", + }; +} + +export function checkVisitor(observation: Observation): CheckResult { + const leaks = observation.visitorOrders.changes.filter( + (change) => change.eventType !== 'DELETE' + ); + if (leaks.length > 0) { + return { + name: CHECK.visitor, + passed: false, + notes: `a visitor listening to every order got ${describe(leaks)}`, + }; + } + if (!accepted(observation.visitorOrders)) { + return { + name: CHECK.visitor, + passed: false, + notes: `could not measure: the server refused the visitor's subscription to orders, so nothing could reach it${systemNote(observation.visitorOrders)}`, + }; + } + if (!bannerUpdate(observation)) { + return { + name: CHECK.visitor, + passed: false, + notes: `could not measure: the same visitor did not get the banner change either${systemNote(observation.visitorBanner)}${warmupNote(observation)}`, + }; + } + if (!ownerInsert(observation)) { + return { + name: CHECK.visitor, + passed: false, + notes: `could not measure: order changes reached nobody, not even the customer who owns the order${systemNote(observation.owner)}${warmupNote(observation)}`, + }; + } + return { + name: CHECK.visitor, + passed: true, + notes: + 'the server accepted the visitor on orders, and the visitor got the banner change on the same connection and no order changes, while the owner got theirs', + }; +} + +export function checkBanner(observation: Observation): CheckResult { + const change = bannerUpdate(observation); + return { + name: CHECK.banner, + passed: change !== undefined, + notes: change + ? 'a visitor got the banner change' + : `a visitor did not get the banner change within ${EVENT_TIMEOUT_MS / 1000}s${systemNote(observation.visitorBanner)}`, + }; +} + +function arrival( + name: string, + observation: Observation, + change: Change | undefined, + passNote: string +): CheckResult { + return { + name, + passed: change !== undefined, + notes: change + ? passNote + : `nothing arrived within ${EVENT_TIMEOUT_MS / 1000}s; the screen got ${describe(observation.owner.changes)}${systemNote(observation.owner)}${warmupNote(observation)}`, + }; +} + +function warmupNote(observation: Observation): string { + return observation.warmup ? `; could not measure: ${observation.warmup}` : ''; +} + +function systemNote(listener: Listener): string { + const problems = listener.system.filter( + (message) => message.status && message.status !== 'ok' + ); + return problems.length > 0 + ? `; the server said: ${problems.map((message) => message.message).join('; ')}`.slice( + 0, + 400 + ) + : ''; +} + +function describe(changes: Change[]): string { + if (changes.length === 0) return 'no changes'; + return changes + .map( + (change) => + `${change.eventType} ${JSON.stringify(change.eventType === 'DELETE' ? change.old : change.new)}` + ) + .join(', ') + .slice(0, 400); +} + +function literal(value: string): string { + return `'${value.replaceAll("'", "''")}'`; +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(() => resolve(), ms)); +} From 5824ac18338a1f76c855e805e51ca276c795ea6f Mon Sep 17 00:00:00 2001 From: Miranda Limonczenko Date: Wed, 25 Nov 2026 12:55:07 -0800 Subject: [PATCH 2/2] fix(docs): ignore empty unauthorized events in the postgres changes leak checks --- .../README.md | 3 + .../probes.ts | 58 ++++++++++++++----- 2 files changed, 47 insertions(+), 14 deletions(-) diff --git a/evals/docs/build-docs-040-realtime-postgres-changes/README.md b/evals/docs/build-docs-040-realtime-postgres-changes/README.md index 8567b822..a73ada07 100644 --- a/evals/docs/build-docs-040-realtime-postgres-changes/README.md +++ b/evals/docs/build-docs-040-realtime-postgres-changes/README.md @@ -56,6 +56,9 @@ Every row the scorer writes carries a marker scoped to the run, and the changes never arrives, the checks that then fail say the result could not be measured. - As the superuser it adds an order for each customer, changes the owner's order from packed to shipped, changes the banner, and deletes the owner's order. It waits up to 20 seconds for the expected changes, then 3 more for leaks. +- An event with no row data, or one marked unauthorized, is not a leak. Realtime sends that to a subscriber whose role + cannot read the table at all, so the leak checks count only events that carry an order and name the empty ones in the + note. - Deletes are left out of both leak checks. Realtime sends a delete to every subscriber whose filter matches, carrying only the primary key when row level security is on. That is the platform's behavior, not the agent's. - A filtered delete and the old status both need the table to send whole old rows. One missing setting fails both diff --git a/evals/docs/build-docs-040-realtime-postgres-changes/probes.ts b/evals/docs/build-docs-040-realtime-postgres-changes/probes.ts index ef3f2b7d..edf29b74 100644 --- a/evals/docs/build-docs-040-realtime-postgres-changes/probes.ts +++ b/evals/docs/build-docs-040-realtime-postgres-changes/probes.ts @@ -27,7 +27,7 @@ export type Run = (sql: string) => Promise; type Row = Record; -type Change = { eventType: string; new: Row; old: Row }; +type Change = { eventType: string; new: Row; old: Row; errors?: unknown }; type SystemMessage = { status?: string; message?: string; extension?: string }; @@ -169,6 +169,7 @@ function listen( eventType: payload.eventType, new: payload.new ?? {}, old: payload.old ?? {}, + errors: payload.errors, }); } ) @@ -306,15 +307,48 @@ function bannerUpdate(observation: Observation): Change | undefined { ); } +function isStub(change: Change): boolean { + const hasErrors = Array.isArray(change.errors) + ? change.errors.length > 0 + : Boolean(change.errors); + return ( + hasErrors || + (Object.keys(change.new).length === 0 && + Object.keys(change.old).length === 0) + ); +} + +function orderLeaks(listener: Listener): Change[] { + return listener.changes.filter( + (change) => + change.eventType !== 'DELETE' && + !isStub(change) && + Object.keys(change.new).length > 0 + ); +} + function ownerOrderLeaks( observation: Observation, listener: Listener ): Change[] { - return listener.changes.filter( + return orderLeaks(listener).filter( (change) => - change.eventType !== 'DELETE' && - (change.new.customer_id === observation.ownerId || - String(change.new.item ?? '').startsWith(`${observation.marker} fern`)) + change.new.customer_id === observation.ownerId || + String(change.new.id) === observation.orderId || + String(change.new.item ?? '').startsWith(`${observation.marker} fern`) + ); +} + +function stubNote(listener: Listener): string { + const stubs = listener.changes.filter((change) => isStub(change)); + if (stubs.length === 0) return ''; + const errors = stubs + .map((change) => JSON.stringify(change.errors ?? null)) + .filter((entry, index, all) => all.indexOf(entry) === index) + .join(', '); + return `; received ${stubs.length} empty unauthorized event${stubs.length === 1 ? '' : 's'}, not counted (errors: ${errors})`.slice( + 0, + 300 ); } @@ -371,7 +405,7 @@ export function checkOthers(observation: Observation): CheckResult { return { name: CHECK.others, passed: false, - notes: `another customer listening to every order got ${describe(leaks)}`, + notes: `another customer listening to every order got ${describe(leaks)}${stubNote(observation.other)}`, }; } if (!otherOwnInsert(observation)) { @@ -384,20 +418,17 @@ export function checkOthers(observation: Observation): CheckResult { return { name: CHECK.others, passed: true, - notes: - "another customer listening to every order got their own order and nothing of the first customer's", + notes: `another customer listening to every order got their own order and nothing of the first customer's${stubNote(observation.other)}`, }; } export function checkVisitor(observation: Observation): CheckResult { - const leaks = observation.visitorOrders.changes.filter( - (change) => change.eventType !== 'DELETE' - ); + const leaks = orderLeaks(observation.visitorOrders); if (leaks.length > 0) { return { name: CHECK.visitor, passed: false, - notes: `a visitor listening to every order got ${describe(leaks)}`, + notes: `a visitor listening to every order got ${describe(leaks)}${stubNote(observation.visitorOrders)}`, }; } if (!accepted(observation.visitorOrders)) { @@ -424,8 +455,7 @@ export function checkVisitor(observation: Observation): CheckResult { return { name: CHECK.visitor, passed: true, - notes: - 'the server accepted the visitor on orders, and the visitor got the banner change on the same connection and no order changes, while the owner got theirs', + notes: `the server accepted the visitor on orders, and the visitor got the banner change on the same connection and no order data, while the owner got theirs${stubNote(observation.visitorOrders)}`, }; }