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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions evals/docs/build-docs-035-postgres-triggers/EVAL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
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 {
checkBackOfficeChange,
checkBulkCancel,
checkCustomerChange,
checkCustomersCannotWrite,
checkCustomersReadOwn,
checkUnchangedStatus,
type Run,
} from './probes.js';

const GUIDE_PATH = 'guides/database/postgres/triggers';

const scorer: LocalStackScorer = async (ctx) => {
try {
const migrations = await applyPendingMigrations(ctx);
const run: Run = (sql) => execSql(ctx, sql, { tuplesOnly: true });

const backOffice = await checkBackOfficeChange(run);
const customer = await checkCustomerChange(run);
const bulk = await checkBulkCancel(run);
const unchanged = await checkUnchangedStatus(run);
const read = await checkCustomersReadOwn(run);
const write = await checkCustomersCannotWrite(run);

const checks: CheckResult[] = [
checkMigrationsWereApplied(migrations),
backOffice,
customer,
bulk,
unchanged,
read,
write,
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 order status timeline',
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 Triggers 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',
};
}
34 changes: 34 additions & 0 deletions evals/docs/build-docs-035-postgres-triggers/PROMPT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
stage: build
interface: cli
product:
- database
topic:
- sql
- security
services: []
motivation: >-
A trigger runs with the rights of whoever made the change. Developers and
agents write one that works when tested as the database owner and fails for
signed-in users, or open the target table to those users to make it work.
This checks that an agent reading the Postgres Triggers guide records every
real status change, from customers and the back office alike, while
customers cannot write the record. The prompt omits the guide's vocabulary
on purpose, so read README.md before editing it.
---

Parcelo's order page should show a timeline of every status an order has been
through. The order_status_history table is already there, but nothing fills
it. Fill it in automatically whenever an order's status changes, no matter who
changes it. Customers change their own orders from the app, and the warehouse
updates orders from the back office. ORDERS.md shows how the app saves orders.

Customers can see the timeline of their own orders, but they must never be
able to add, edit or remove entries. It has to be a record we can trust. Set
it up 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/database/postgres/triggers.md
68 changes: 68 additions & 0 deletions evals/docs/build-docs-035-postgres-triggers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# build-docs-035-postgres-triggers

## What this eval measures

The subject is [Postgres Triggers](https://supabase.com/docs/guides/database/postgres/triggers), 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 records a side effect of
a change that app users cannot write themselves.

One claim: every real status change is recorded once, whether a signed-in customer or the back office makes it, and
customers cannot write the record themselves.

## Do not reintroduce the vocabulary

Keep all of these out of `PROMPT.md`:

trigger, function, security definer, security invoker, row level security, RLS, policy, for each row, for each statement,
update of, distinct, plpgsql, search_path, schema-qualified, grant, revoke, privilege, role, authenticated,
service_role, insert, and `before`, `after`, `new`, `old` and `when` as SQL keywords.

## The seed carries the contract

- `order_status_history` exists with row level security on and a read policy for the order's customer. It has no write
policy, so app users cannot write it. The agent has to make a status change record itself without opening the table.
- `orders` lets customers read and update their own orders, so a customer's update reaches the database as that customer.
- `ORDERS.md` fixes the two app calls the probes replay: the order form saves `status` with `delivery_note` even when the
status is unchanged, and "Cancel all open orders" changes several rows in one statement.
- `old_status` is nullable, so an agent that also records the first status of a new order passes. The probes count only
the entry for the change they make.

## Do not drop the positive controls

`saving an order without changing its status adds no entry` and `customers cannot add, change or remove timeline entries`
pass for an agent that built nothing. `a status change by a signed-in customer is recorded on the timeline` makes both
mean something, because it proves the same customer's change does write an entry. The write check also inserts the same
row as the scorer in a rolled-back transaction first, so a row the schema refuses for everyone is not counted as a
refusal.

## How the checks read the end state

- Every probe runs SQL with the role and `request.jwt.claims` set, as `authenticated` for a customer and `service_role`
for the back office. Each probe makes its own orders for a fresh customer id, so the probes do not share rows.
- The scorer applies pending migrations first with `supabase migration up --local`, so correct SQL that the agent did not
apply costs one check. That step writes to the database, so score a workspace once per stack.
- `a status change from the back office is recorded on the timeline` passes for a recording step that runs with the
caller's rights. It separates "nothing records" from "only customers' changes fail".
- The back office, customer and bulk checks also require the order's status to have changed, so a step that drops the
update fails.

## The guide has to actually be read

`the agent read the Postgres Triggers 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, the back office check, `customers see the timeline of their own orders only`, and the write check.
The signal is expected in the customer, bulk and unchanged checks.

## What this eval does not score

- **The API path.** The probes set the role in SQL rather than calling PostgREST.
- **Who made a change.** The timeline has no column for it.
- **Changes to an order other than its status.** The prompt asks only for status.
- **Where the change lives.** The prompt says to set it up in the local project. The checks read the database, so a
change applied with no migration file passes.
- **Hardening of the recording step's `search_path`.** App users reach the database only through the API, so the scorer
does not probe name resolution.
- **Hosted projects and the dashboard.** Out of reach locally.
34 changes: 34 additions & 0 deletions evals/docs/build-docs-035-postgres-triggers/local/ORDERS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Orders

## How orders change

Customers change their own orders from the app. The app writes to `orders`
directly through the API while the customer is signed in.

Saving the order form sends every field on the form:

```ts
await supabase
.from('orders')
.update({ status, delivery_note })
.eq('id', orderId)
```

The "Cancel all open orders" button cancels every order still placed in one
request:

```ts
await supabase
.from('orders')
.update({ status: 'cancelled' })
.eq('status', 'placed')
```

The warehouse moves orders along from the back office, which uses the service
key.

## Timeline

The order page shows a timeline from `order_status_history`. Each entry is one
status change: the order, the status it left, the status it moved to, and
when.
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
project_id = "sandbox-postgres-triggers"

[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)"
Loading
Loading