Skip to content
Merged
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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,18 @@ While pre-1.0, the public API may change between 0.x releases.
typed with `wrangler types` and `skipLibCheck: false` no longer fails with
TS2307. The pack smoke test now checks both type setups (ADR-0022
amendment).
- **A query on a column the table does not have is refused.** This holds for
a `sub`, a `fetch` and `readSyncSnapshot` whose `where` or `orderBy` names
such a column. A `sub` gets `reset` with nothing registered, a `fetch` gets
an empty page, and `readSyncSnapshot` rejects (over RPC with a plain `Error`
whose message starts with `UnsupportedPredicateError:`). The server logs one
line. Until refusals are made loud, the app sees such a query as no results.
A name in another letter case than the declared one (`BODY` for `body`) and
`rowid` are refused too. Before, SQLite read an unknown name as a string, so
the snapshot held every row or none and disagreed with the deltas. A
subscription restored on wake whose predicate names a column that a
migration dropped closes its socket with 1011, so the client reconnects and
that query is refused (ADR-0013 amendment 2026-11-17).

### Tests

Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,11 @@ show. The conventions, what's verified and how, and the full
so a search box that builds `%term%` stops matching at 49 ASCII characters, or
about 17 CJK characters. Until refusals fail loud, a refused query reads as no
results.
- **A column the table does not have:** a `where` or `orderBy` that names a
column the table does not have is refused, and the server logs one line. Until
refusals fail loud, the query reads as no results. Two names that used to
return rows are refused too: a name in another letter case than the declared
one (`BODY` for `body`), and `rowid`.

---

Expand Down
143 changes: 143 additions & 0 deletions docs/adr/0013-predicate-floor-one-evaluator.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,146 @@ by SQLite, that every family crosses its own edge, and that early refusal stays
within a stated slack; it also runs a deterministic fuzz of 89 376 predicates
(about 13 seconds). `tests/long-in-lists.test.ts` drives every path that runs the
compiled SQL.

## Amendment 2026-11-17: a query that names a column the table does not have is refused

**Context.** The compiler writes a column as a double quoted name. When the table
has no such column, SQLite does not fail: it reads the name as a string literal
and runs the statement. The evaluator, which decides the deltas, reads the
missing column as undefined. Measured on the test table `messages (id, body)`
with raw `sub` and `fetch` frames: `eq`, `gt`, `in`, `like` and `not(isNull)` on
`nope` snapshot every row; `eq(nope, "other")` and `isNull(nope)` snapshot none;
`orderBy nope limit 2` returns two rows in no meaningful order; later inserts
send synthetic deletes; and `fetch` returns the same wrong rows. There was no
refusal and no log line, so a typo in a column name gave an app a wrong list
that looked right. The 2026-09-29 amendment called unknown columns out of
contract. That is replaced here: they are refused.

**What SQLite does.** Measured in workerd 1.20260721.1:

- A double quoted name that matches no column is a string literal in `WHERE`
and in `ORDER BY` alike, so `"nope" = 'nope'` is true on every row,
`"nope" IS NULL` is false, and `ORDER BY "nope"` sorts by a constant. The same
holds on a rowid table, a `WITHOUT ROWID` table and a view.
- A name in backticks, or one qualified with the table (`"messages"."nope"`), is
never read as a string. Both clauses fail with `no such column`.
- SQLite matches a name in any case (`"BODY"` finds `body`) and resolves
`rowid` and `_rowid_` on a rowid table. A row from `SELECT *` has
neither key: its keys are the declared names, and the rowid is not one of
them. So the evaluator reads `row.BODY` and `row.rowid` as undefined while the
SQL reads a real value.
- A generated column, virtual or stored, is in `SELECT *` and in
`pragma_table_xinfo` (with `hidden` 2 or 3), but not in `pragma_table_info`.
- A view and a `WITHOUT ROWID` table cannot be registered (`assertSyncCompatible`
finds no primary key on a view and no rowid on the other), and a virtual table
cannot carry the capture triggers. So none of them is a synced table, and none
changes the answer below.

**Options.**

1. Read the table's columns when a query is compiled, and refuse a name that is
not one of them.
2. Quote names so SQLite never reads them as strings (backticks, or the table
name in front), and treat `no such column` as a refusal.
3. Both.

Option 2 is not correct on its own. It still accepts `BODY` and `rowid`, which
SQLite resolves and the evaluator does not see. It only fails when the
statement is prepared, but the catch-up path of a reconnecting `sub` never runs
the compiled SQL, and a sub restored on wake (ADR-0019) has no SQL at all, so
both would still accept the query. It would also have to pick `no such column`
out of other errors by the message text. Option 3 refuses nothing that option 1
does not already refuse. Option 1 is the simplest one that is correct.

**Decision.**

- `compileSubsetQuery` returns, beside the SQL, the names its `where` and
`orderBy` refer to (`columns`). It stays free of SQLite.
- The mixin refuses a query that names a column not in
`SELECT name FROM pragma_table_xinfo(?)`. For any table that can be synced,
that is the list of names `SELECT *` returns. The names are compared exactly,
as a row's keys are. The refusal is an `UnsupportedPredicateError`, so it takes
the same path as an operator off the floor: a `sub` gets `reset` and nothing of
it stays registered, a `fetch` gets the empty page, and `readSyncSnapshot`
throws. The class does not survive the RPC: a caller of `readSyncSnapshot`
through a stub gets a plain `Error` whose message starts with
`UnsupportedPredicateError:`. The log line is the existing one, for example
`sub 's1' on 'messages' rejected: column 'nope' is not in table 'messages'`,
clipped like every client string.
- The pk is a column of the table, so it passes. The library adds no column to
a synced table: its triggers write to `_sync_changes`, and its own tables are
all `_sync_*`. The `ORDER BY rowid` default and the pk tie break are written by
the compiler and are not checked. A `rowid` named by the client is refused.
- For a ref as the library's client sends it, the SQL and the evaluator now
read the same column, so the residual in the 2026-09-29 amendment
(`isUndefined` is true in the evaluator for a column the table lacks) can no
longer be reached by such a ref. This says nothing about a ref built by hand
in a shape the client does not send.
- A table dropped while the object is alive gives an empty list, so a query
that names a column is now refused with `column 'x' is not in table 't'`,
where before it threw `no such table`. A query that names no column still
throws `no such table`.

**Cost.** One read of the pragma for each `sub`, `fetch` and `readSyncSnapshot`
whose query names a column, and none for one that names no column (an eager
collection's `sub`). A cursor `fetch` compiles two statements and reads the list
once for both. A restore reads it once per table. Each read counts as rows read,
one per column of the table (measured: `rowsRead` 2 and `rowsWritten` 0 on
`messages (id, body)`), so each such `sub`, `fetch` and snapshot read adds that
many rows read. Whether Cloudflare bills rows read from a pragma like rows read
from a table was not verified. The read is a synchronous call into SQLite's in
memory schema; it was not timed, because workerd does not advance its clock
inside a request.
Nothing is kept between queries, so a column added while the object is alive
(by `ALTER TABLE` in a migration, with or without a later `registerSync`) is
accepted by the next query. There is no timer and nothing runs while the object
is idle.

**Restore (ADR-0019).** A persisted sub carries only its `where` (its `orderBy`
shaped a snapshot that was already sent). On restore, that `where` now runs
through the whole SQL compiler, not only the evaluator, and its columns are
checked, reading each table's columns once per restore. Any compile refusal
closes the socket on wake. Within one build only a missing column can do that:
the statement compiled on restore is the sub's own, with the same `where` and no
`orderBy`, `limit` or `offset`, so it has no more parameters, bytes or depth
than the statement accepted at sub time. Any other refusal can only come from a
row written by an older build, which is what the 1011 close was written for.

If a migration dropped a column a persisted `where` names, the sub is handled as
one whose predicate no longer compiles: the socket closes with 1011 and its
persisted subs are deleted. What the client then goes through, checked by
reading `src/client/transport.ts` and `src/client/do-collection.ts` and not by
a run:

- The transport reconnects and sends every sub again. The sub on the dropped
column had bootstrapped, so it goes with `since`. The server refuses it with
`reset`, and persists nothing of it.
- In on-demand mode, a `reset` on a bootstrapped watch reads as "below the
retention floor". The collection truncates (`truncateAll`), and the truncate
replay loads every subset of that collection on that client again from
fresh snapshots. The replay sends a fresh sub for the bad query, which is
refused as a watch that never bootstrapped: its load settles and nothing else
is touched, so it does not loop.
- In eager mode, the collection's one sub truncates on that `reset` and the
collection stays empty, as for any refused eager sub.
- Subs of other collections on the same socket catch up from `since` as usual.
- A refused sub is not persisted, so the next wake has nothing to close.

So the cost is one reconnect and one full reload of that collection for each
client that held such a sub. Restore runs inside every `registerSync`, so a
column dropped while the object is awake is caught the same way when
`registerSync` runs after it. One dropped with no `registerSync` after it is not
caught: until the next wake or reconnect, live subs on it read the column as
undefined.

**Not changed.** A refused query still reads as no results on the client, as
every refusal does today. The kinds of values a column is compared with are not
checked.

**Evidence.** `tests/unknown-columns.test.ts` drives every shape above through a
`sub` (including the catch-up path), a `fetch` (including a cursor) and
`readSyncSnapshot` on a real Durable Object (one of them through the RPC stub),
pins each half of a cursor `fetch` alone, and checks that nothing of a
refused sub is registered or persisted, that the log line names the column and
is clipped, that the pk and a column added after the first query (plain or
generated) are accepted, and the restore after a column is dropped.
2 changes: 1 addition & 1 deletion docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ explains the displacement.
| [0010](./0010-typed-mutations-collection-manifest.md) | Typed mutations via a collection-row manifest on `SyncRegistry` | Accepted (manifest superseded by 0014) |
| [0011](./0011-ssr-dehydrate-hydrate.md) | SSR: dehydrate on the worker, hydrate to the cursor | Accepted (experimental; generalizes 0002 C1 → C1′; amended for merged upstream + 0015/0016 lift; D5 peer floor superseded by 0022; amended 2026-11-17: a render refuses writes, never reads) |
| [0012](./0012-wire-input-hardening.md) | Wire-input hardening: frame-shape guards, inbound limits, sanitized execute errors | Accepted (D1 amended by 0025 for op keys; D2 limit order amended by 0025; D4 accepted as a limitation, both effects named, 2026-11-17; amended 2026-11-17: a deliberate refusal is always answered and leaves nothing registered) |
| [0013](./0013-predicate-floor-one-evaluator.md) | Filtered-subscription membership: one evaluator is the source of truth; the floor is the verified-agreeing set | Accepted (amended 2026-09-29: `isNull`/`isUndefined`; amended 2026-11-17: long `in` lists, `in` compares by kind, SQLite limits refused at compile time) |
| [0013](./0013-predicate-floor-one-evaluator.md) | Filtered-subscription membership: one evaluator is the source of truth; the floor is the verified-agreeing set | Accepted (amended 2026-09-29: `isNull`/`isUndefined`; amended 2026-11-17: long `in` lists, `in` compares by kind, SQLite limits refused at compile time; amended 2026-11-17: a column the table does not have is refused) |
| [0014](./0014-object-sync-schema.md) | `defineSync`: one schema value, mutations on the collection, commands on the connection | Accepted (supersedes 0001 D11 builder; closes 0010 manifest) |
| [0015](./0015-syncable-mixin.md) | `Syncable` mixin: the sync core as a mixin over any DO base | Accepted (reframes 0001 D13; Actor unsupported; wake-test gap closed by 0019) |
| [0016](./0016-reconnect-policy.md) | Transport reconnect policy: injectable delay function, terminal 4xxx, jittered backoff | Accepted (§3 amended 2026-11-17: only a connection that stayed open 5 s resets the backoff) |
Expand Down
62 changes: 51 additions & 11 deletions src/server/mixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,13 +319,29 @@ export function Syncable<Env = unknown, TUser = unknown>() {
* cursor advances — codex review), whereas a close engages the
* reconnect machinery, which re-subscribes everything recoverable and
* routes the bad predicate through `#handleSub`'s pre-existing,
* app-visible rejection. */
* app-visible rejection.
*
* The whole SQL compiler runs on each persisted `where`, with the
* table's columns checked (ADR-0013 amendment 2026-11-17), so any
* compile refusal closes the socket, including a column a migration
* dropped. Within one build only that can fire: the statement compiled
* here is the sub's own with the same `where` and no `orderBy`, `limit`
* or `offset`, so it has no more parameters, bytes or depth than the one
* accepted at sub time. Any other refusal means the row was written by
* an older build, which is what this close is for. A sub on a
* collection that is no longer registered is left to `#reconcileSubs`. */
#restoreSubs(): void {
const columns = new Map<string, ReadonlySet<string>>() // read once per table, for this restore only
for (const ws of this.#liveWs) {
const sid = this.#socketIdFor(ws)
if (!sid) continue // legacy pre-0.6 socket: nothing was persisted
for (const row of loadPersistedSubs(this.#sql, sid)) {
try {
const coll = this.#registry.collections.get(row.collection)
if (coll) {
const q = compileSubsetQuery(coll.table, { pk: coll.pk, where: row.where })
this.#refuseUnknownColumns(coll.table, q.columns, columns)
}
this.#subs.add(ws, row.subId, row.collection, row.where)
} catch (e) {
if (e instanceof UnsupportedPredicateError) {
Expand Down Expand Up @@ -400,6 +416,7 @@ export function Syncable<Env = unknown, TUser = unknown>() {
orderBy: req.orderBy,
limit: req.limit,
})
this.#refuseUnknownColumns(coll.table, query.columns)
const rows = Array.from(this.#sql.exec(query.sql, ...query.params)).map((row) => {
let out: Record<string, SqlStorageValue> | undefined
for (const [k, v] of Object.entries(row)) {
Expand Down Expand Up @@ -685,22 +702,25 @@ export function Syncable<Env = unknown, TUser = unknown>() {
// Cursor present: ties first (base AND whereCurrent, unbounded boundary
// set), then the bounded next page (base AND whereFrom). The cursor
// expressions arrive raw — excluding the base — so we compose them here.
// No cursor: a plain bounded `where` read.
if (frame.cursor != null) {
const tq = compileSubsetQuery(frame.collection, {
pk: coll.pk,
where: andPredicates(frame.where, frame.cursor.whereCurrent),
orderBy: frame.orderBy,
})
rows.push(...Array.from(this.#sql.exec(tq.sql, ...tq.params)))
}
// No cursor: a plain bounded `where` read. Both are compiled and their
// columns checked before either runs.
const tq =
frame.cursor != null
? compileSubsetQuery(frame.collection, {
pk: coll.pk,
where: andPredicates(frame.where, frame.cursor.whereCurrent),
orderBy: frame.orderBy,
})
: undefined
const nextWhere = frame.cursor != null ? andPredicates(frame.where, frame.cursor.whereFrom) : frame.where
const nq = compileSubsetQuery(frame.collection, {
pk: coll.pk,
where: nextWhere,
orderBy: frame.orderBy,
limit: frame.limit,
})
this.#refuseUnknownColumns(coll.table, [...(tq?.columns ?? []), ...nq.columns])
if (tq) rows.push(...Array.from(this.#sql.exec(tq.sql, ...tq.params)))
rows.push(...Array.from(this.#sql.exec(nq.sql, ...nq.params)))
this.#send(ws, { t: "page", fetchId: frame.fetchId, rows, seq })
} catch (e) {
Expand Down Expand Up @@ -1064,7 +1084,7 @@ export function Syncable<Env = unknown, TUser = unknown>() {
// Lower where/orderBy/limit/offset into SQLite. An un-lowerable predicate
// (outside the supported floor, or over one of SQLite's limits) is
// rejected, not silently full-scanned.
let query: { sql: string; params: Array<unknown> }
let query: { sql: string; params: Array<unknown>; columns: Array<string> }
try {
query = compileSubsetQuery(frame.collection, {
pk: coll.pk,
Expand All @@ -1073,6 +1093,7 @@ export function Syncable<Env = unknown, TUser = unknown>() {
limit: frame.limit,
offset: frame.offset,
})
this.#refuseUnknownColumns(coll.table, query.columns)
} catch (e) {
if (e instanceof UnsupportedPredicateError) {
console.error(`sub '${clip(frame.subId)}' on '${clip(frame.collection)}' rejected: ${clip(e.message)}`)
Expand Down Expand Up @@ -1161,6 +1182,25 @@ export function Syncable<Env = unknown, TUser = unknown>() {
this.#send(ws, { t: "snap-end", sub: frame.subId, seq })
}

/** Refuse a query that names a column the table does not have, as
* `SELECT *` names them (ADR-0013 amendment 2026-11-17). SQLite reads such a
* name as a string, and resolves `rowid` or a name in another case, none of
* which the evaluator sees on a row. The columns are read from SQLite only
* when the query names one, and kept only in `cache` (the caller's own),
* so a column added since the last query is never refused. */
#refuseUnknownColumns(table: string, named: Array<string>, cache = new Map<string, ReadonlySet<string>>()): void {
for (const name of named) {
let columns = cache.get(table)
if (!columns) {
// `table_xinfo`, not `table_info`: it lists generated columns, which
// `SELECT *` returns. Rows read: one per column of the table.
const rows = this.#sql.exec<{ name: string }>("SELECT name FROM pragma_table_xinfo(?)", table)
cache.set(table, (columns = new Set(Array.from(rows, (r) => r.name))))
}
if (!columns.has(name)) throw new UnsupportedPredicateError(`column '${name}' is not in table '${table}'`)
}
}

/** The backstop behind the compiler's limit checks (ADR-0012 amendment
* 2026-11-17): SQLite rejected one of this sub's statements for one of its
* limits. That is deterministic for a given statement and schema, so it is
Expand Down
Loading
Loading