From 0fc5bbc345c60df6fde4563629f6f159bbd2a751 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Sep 2026 09:53:45 +0000 Subject: [PATCH 1/3] fix(drivers): update() on a missing id answers null on MongoDB and Turso remote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `IDataDriver.update()` declares `Promise | null>`, and four of six shipped implementations return `null` for an id that names no row. `MongoDBDriver.update()` and `RemoteTransport.update()` fabricated a record instead — the caller's own payload with the id stapled on (and, on Mongo, the `updated_at` the driver had just stamped). Through the engine's by-id door that surfaced as a 200 with a record that does not exist. Both now return `null`. `TursoDriver.update()`'s remote branch needed no edit: `formatRemoteRow` already guards `row && typeof row === 'object'`, so the two faces of that driver converge. `RemoteTransport.bulkUpdate()`'s `if (updated) results.push(updated)` skip stops being dead code. `upsert()` is untouched on both: an upsert never answers "not found". Regression pins added per driver (net-new — no landed test pinned the fabricating posture), each with a positive control so "return null always" cannot pass, plus a local/remote parity pin on TursoDriver. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_0112hMx9hjJ9BgB28X97DS68 --- .changeset/driver-update-missing-id-null.md | 49 ++++ .../driver-mongodb/src/mongodb-driver.ts | 31 ++- .../src/mongodb-update-missing-id.test.ts | 180 +++++++++++++ .../driver-turso/src/remote-transport.ts | 35 ++- .../src/turso-update-missing-id.test.ts | 244 ++++++++++++++++++ 5 files changed, 535 insertions(+), 4 deletions(-) create mode 100644 .changeset/driver-update-missing-id-null.md create mode 100644 packages/drivers/driver-mongodb/src/mongodb-update-missing-id.test.ts create mode 100644 packages/drivers/driver-turso/src/turso-update-missing-id.test.ts diff --git a/.changeset/driver-update-missing-id-null.md b/.changeset/driver-update-missing-id-null.md new file mode 100644 index 0000000000..2175fa4b22 --- /dev/null +++ b/.changeset/driver-update-missing-id-null.md @@ -0,0 +1,49 @@ +--- +"@objectstack/driver-mongodb": patch +"@objectstack/driver-turso": patch +--- + +fix(drivers): `update()` on a missing id answers `null` on MongoDB and on Turso's remote face + +`IDataDriver.update()` declares `Promise | null>` — the +not-found arm landed with the ruling on the contract, and it is the answer +`InMemoryDriver`, `SqlDriver`, `SqliteWasmDriver` and `TursoDriver`'s local face +have always given. Two implementations did not honour it. They **invented a +record** instead: + +- `MongoDBDriver.update()` ran `updateOne({ id })`, then `findOne({ id })`, and + when nothing came back returned + `withoutUndefinedOwnKeys({ id: String(id), ...updateData })` — a row assembled + from the caller's own payload plus the `updated_at` it had just stamped, under + an id that names no document. +- `RemoteTransport.update()` ran `UPDATE … WHERE "id" = ?`, then + `SELECT * … WHERE "id" = ?`, and when no row came back returned + `{ id, ...data }` — the caller's payload with the id stapled on. + +Both now return `null`. + +This is the expensive direction of wrong, not merely the wrong answer: the +fabricated row said **succeeded** where the truth was **not found**, and said it +in a shape carrying the caller's own fields back, so nothing about it looked +wrong. Through the engine's by-id door a REST / SDK / MCP `update` against a +deleted or mistyped id answered **200 with a record that does not exist** — on +these two implementations only. A caller, human or agent, read that as a landed +write and did not retry, alert or roll back. + +Two things downstream become correct rather than merely different: + +- **One `TursoDriver`, one answer.** Its remote branch passes the transport + result through `formatRemoteRow`, which already guards + `row && typeof row === 'object'`, so `null` reaches the engine untouched and + the two faces converge with no edit at that seam. Previously the same driver + answered the same missing id two ways, chosen by `isRemote`. +- **`RemoteTransport.bulkUpdate()`'s skip stops being dead code.** + `if (updated) results.push(updated)` is the cross-driver convention + `SqlDriver.bulkUpdate` follows; on this transport `updated` could never be + falsy, so a batch over N missing ids answered N invented rows. It now answers + the rows that exist. + +`upsert()` is untouched on both drivers: an upsert never answers "not found". + +No landed test pinned the fabricating posture on either driver, so the +regression pins added here are net-new coverage rather than a changed baseline. diff --git a/packages/drivers/driver-mongodb/src/mongodb-driver.ts b/packages/drivers/driver-mongodb/src/mongodb-driver.ts index 96be5112f3..2ba14c86d2 100644 --- a/packages/drivers/driver-mongodb/src/mongodb-driver.ts +++ b/packages/drivers/driver-mongodb/src/mongodb-driver.ts @@ -400,7 +400,34 @@ export class MongoDBDriver implements IDataDriver { return result; } - async update(object: string, id: string | number, data: Record, options?: DriverOptions): Promise> { + /** + * [#14428] A miss answers `null` — the arm `IDataDriver.update()` declares + * (#13878) and the one `InMemoryDriver`, `SqlDriver`, `SqliteWasmDriver` and + * `TursoDriver`'s local face already return. + * + * This door used to answer a missing id with a row ASSEMBLED from the + * caller's own payload plus the `updated_at` it had just stamped: + * + * return (updated as Record[string, unknown]) || withoutUndefinedOwnKeys({ id: String(id), ...updateData }); + * + * `updateOne` matched nothing, `findOne` came back `null`, and the caller was + * handed a record for an id that names no document. The reason that was ever + * written — "the declaration does not permit `null`, so something has to come + * back" — was removed by #13878; the posture outlived it. The maintainer + * ruled it out on 2026-09-03 (「同意」, decision batch #15 item 1, posture A). + * + * Why the fabricated row is the expensive direction, not merely the wrong + * one: it says SUCCEEDED where the truth is NOT FOUND, and it says so in a + * shape that carries the caller's own fields back, so nothing about it looks + * wrong. A caller — human or agent — reads it as a landed write and does not + * retry, alert or roll back. Through the engine's by-id door + * (`engine.ts` → `driver.update`) it surfaced as a REST/SDK/MCP `200` with a + * record that does not exist, on this driver and Turso's remote face only. + * + * ⚠️ `upsert()` is deliberately untouched: an upsert never answers + * "not found" (it inserts instead), so it has no not-found arm to declare. + */ + async update(object: string, id: string | number, data: Record, options?: DriverOptions): Promise | null> { const collection = this.getCollection(object); const session = this.getSession(options); @@ -419,7 +446,7 @@ export class MongoDBDriver implements IDataDriver { { session, projection: { _id: 0 } }, ); - return (updated as Record) || withoutUndefinedOwnKeys({ id: String(id), ...updateData }); + return (updated as Record | null) ?? null; } async upsert(object: string, data: Record, conflictKeys?: string[], options?: DriverOptions): Promise> { diff --git a/packages/drivers/driver-mongodb/src/mongodb-update-missing-id.test.ts b/packages/drivers/driver-mongodb/src/mongodb-update-missing-id.test.ts new file mode 100644 index 0000000000..5c7f9aae8d --- /dev/null +++ b/packages/drivers/driver-mongodb/src/mongodb-update-missing-id.test.ts @@ -0,0 +1,180 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#14428] `MongoDBDriver.update()` answers a missing id with `null`, not with + * a record it made up. + * + * # What was broken + * + * The door read: + * + * return (updated as Record[string, unknown]) || withoutUndefinedOwnKeys({ id: String(id), ...updateData }); + * + * `updateOne({ id })` matching nothing and `findOne({ id })` coming back `null` + * still produced a row — the caller's own payload plus the `updated_at` this + * driver had just stamped, under an id that names no document. Since #13878 + * (PR #14434) `IDataDriver.update()` declares `Promise[Record[string, unknown] + * | null]`, so "a row for an id that does not exist" is no longer a way of + * satisfying the declaration: it is a value the declaration distinguishes from. + * Four of six shipped implementations already answered `null`; this one and + * Turso's remote face answered "updated". Maintainer ruling 2026-09-03, + * posture A. + * + * # Why this file exists at all + * + * The card measured that NO landed test pinned the miss posture on this driver + * — `mongodb-driver.test.ts:157,171` read `update()` results over rows that + * EXIST. So this is net-new coverage, and the fabricating posture could have + * come back without reddening anything. + * + * # Why it does not live in `mongodb-driver.test.ts` + * + * That suite is `describe.skipIf(!sharedMongod)` and `createTestMongod` skips + * it unless `OS_TEST_MONGODB_MEMORY_SERVER_ENABLED=1` (#5517 retired the + * 123 MB binary download that was ejecting unrelated PRs from the merge queue). + * A pin added there would be GREEN-BY-SKIP on every CI run — a phantom pin, + * which is worse than none: it reads as coverage in the file list and can + * never fail. The fake `Db` below is the pattern + * `mongodb-findone-options.test.ts` established and + * `mongodb-own-key-undefined.test.ts` reuses: `getCollection` is + * `this.db.collection(name)`, so replacing `db` observes every call the real + * code path makes, with no server and no download. + * + * # The pins, and what each alone would miss + * + * - **The miss pin** is the defect: `findOne` empty ⇒ `null`. + * - **The positive control** is what stops the fix from being "return `null` + * always". A driver that had simply deleted the read-back would pass the + * miss pin and break every update that works. + * - **The no-fabrication pin** asserts the specific shape that used to come + * back (the caller's fields, the stamped `updated_at`). `toBeNull()` alone + * would also be satisfied by a driver that threw and was caught elsewhere; + * this states what must NOT be synthesized. + * - **The write-still-issued pin** holds the other half of the contract: the + * `updateOne` is still sent. A "fix" that short-circuited on a miss by + * reading FIRST would answer `null` correctly and quietly stop writing. + * + * # ⚠️ There is deliberately NO type-level pin in this file — MEASURED + * + * #13878's `memory-update-declared-null.test.ts` pins the declared return type + * with `Equals`/`IsAny` consts. That instrument does not work HERE and would be + * a phantom: this package's `tsconfig.json` carries + * `"exclude": [..., "**\/*.test.ts"]` (escaped here so this very comment does + * not terminate early), so no test file is in its tsc program and + * a `const x: Equals[A, B] = true` here is never checked by anything — vitest + * transpiles without typechecking, and the root `tsconfig.json` excludes + * `packages` entirely, so no repo-wide program picks it up either. Measured, + * not assumed: `tsc --noEmit --listFiles` in this package lists 0 files ending + * `.test.ts` (the sibling `driver-turso`, whose tsconfig excludes only + * `node_modules`/`dist`, lists 43 — which is why the twin file + * `turso-update-missing-id.test.ts` DOES carry the type pin). + * + * The declared type is nevertheless pinned, in both directions, by instruments + * that DO run: + * + * - **narrowing the declaration back** to `Promise[Record[string, unknown]]` + * is a `tsc` error in `mongodb-driver.ts` itself — that file IS in the + * program, and the body's `?? null` then returns `Record[string, unknown] | + * null` from a non-null signature. `pnpm --filter @objectstack/driver-mongodb + * typecheck` reds. + * - **losing the contract linkage** (should `IDataDriver.update()` drop its + * `| null` arm) reds the same typecheck through `implements IDataDriver`. + * - **reverting the behaviour** while keeping the signature reds the runtime + * pins below. + * + * # Reverse verification, direction predicted BEFORE running + * + * Predicted: restoring the `|| withoutUndefinedOwnKeys({ id: String(id), + * ...updateData })` fallback reds the miss pin and the no-fabrication pin, and + * reds the type pin's `Equals` const at COMPILE time (so the whole file fails + * to typecheck) while the positive control and the write-still-issued pin stay + * GREEN — they exercise the found arm, which the revert does not touch. + */ + +import { describe, it, expect } from 'vitest'; + +import { MongoDBDriver } from './mongodb-driver.js'; + +/** What the fake collection recorded, so the WRITE half stays observable. */ +interface Recorded { + updateOne: Array<{ filter: Record; update: Record }>; + findOne: Array>; +} + +/** + * A driver wired to a recording fake `Db` — no `connect()`, no server. + * + * `stored` is the document `findOne` answers with; `null` models the miss (a + * real `findOne` resolves `null` when nothing matches), and an object models + * the row that exists. + */ +function makeDriver(stored: Record | null) { + const recorded: Recorded = { updateOne: [], findOne: [] }; + const collection = { + async updateOne(filter: Record, update: Record) { + recorded.updateOne.push({ filter, update }); + return { matchedCount: stored ? 1 : 0, modifiedCount: stored ? 1 : 0 }; + }, + async findOne(filter: Record) { + recorded.findOne.push(filter); + return stored; + }, + }; + const driver = new MongoDBDriver({ url: 'mongodb://127.0.0.1:1/probe' }); + (driver as any).db = { collection: () => collection }; + return { driver, recorded }; +} + +describe('[#14428] MongoDBDriver.update() on a missing id', () => { + it('resolves null when no document carries that id', async () => { + const { driver } = makeDriver(null); + + const result = await driver.update('task', 'no-such-id', { title: 'edited' }); + + expect(result).toBeNull(); + // The narrowing the declared type demands of every caller. + const title = result === null ? 'absent' : result.title; + expect(title).toBe('absent'); + }); + + it('fabricates nothing — no id, no payload echo, no stamped updated_at', async () => { + const { driver } = makeDriver(null); + + const result = await driver.update('task', 'no-such-id', { title: 'edited', owner: 'u1' }); + + // The exact shape the old fallback produced: `{ id, ...updateData }` with + // `updated_at` stamped a moment earlier. Asserted as a NON-match against a + // reconstruction of it, so the pin names the thing it forbids rather than + // only the thing it wants — `toBeNull()` alone would also be satisfied by a + // driver that threw and was caught somewhere up the stack. + // + // ⚠️ NOT written as `expect(result).not.toBeTypeOf('object')`: `typeof + // null` IS `'object'` in JS, so that assertion fails on the correct value. + expect(result).toBeNull(); + expect(result).not.toMatchObject({ id: 'no-such-id' }); + expect(Object.keys((result as Record | null) ?? {})).toEqual([]); + }); + + it('still ISSUES the write — the miss is discovered by reading back, not by refusing', async () => { + const { driver, recorded } = makeDriver(null); + + await driver.update('task', 'no-such-id', { title: 'edited' }); + + expect(recorded.updateOne).toHaveLength(1); + expect(recorded.updateOne[0].filter).toEqual({ id: 'no-such-id' }); + expect((recorded.updateOne[0].update as any).$set.title).toBe('edited'); + expect(recorded.findOne).toHaveLength(1); + expect(recorded.findOne[0]).toEqual({ id: 'no-such-id' }); + }); + + it('POSITIVE CONTROL — an id that DOES exist still returns the stored row', async () => { + const stored = { id: 'task-1', title: 'edited', owner: 'u1', updated_at: new Date('2026-01-01T00:00:00Z') }; + const { driver } = makeDriver(stored); + + const result = await driver.update('task', 'task-1', { title: 'edited' }); + + expect(result).not.toBeNull(); + expect(result!.id).toBe('task-1'); + expect(result!.title).toBe('edited'); + }); +}); diff --git a/packages/drivers/driver-turso/src/remote-transport.ts b/packages/drivers/driver-turso/src/remote-transport.ts index 7de7f70ffa..09aac9b89f 100644 --- a/packages/drivers/driver-turso/src/remote-transport.ts +++ b/packages/drivers/driver-turso/src/remote-transport.ts @@ -1530,7 +1530,38 @@ export class RemoteTransport { return rows[0] || toInsert; } - async update(object: string, id: string | number, data: Record): Promise> { + /** + * [#14428] A miss answers `null` — the arm `IDataDriver.update()` declares + * (#13878), and the answer this driver's LOCAL face (`SqlDriver.update`, + * through `TursoDriver.update`'s `super` branch) has always given. + * + * The line this replaces stapled the id onto the caller's own payload: + * + * return rows[0] || { id, ...data }; + * + * so `UPDATE … WHERE "id" = ?` matching nothing, followed by a `SELECT` + * returning nothing, still handed back a row. One `TursoDriver`, two answers + * to one question, chosen by `isRemote` — the divergence class this package + * has paid for repeatedly (#5769, #5903, #6203, #8413). The maintainer ruled + * the convergence on 2026-09-03 (「同意」, decision batch #15 item 1, + * posture A: return `null`, not throw — a throw would have been a THIRD + * posture on top of the two this collapses). + * + * Two things downstream become correct rather than merely different: + * + * - `TursoDriver.update()`'s remote branch passes this through + * `formatRemoteRow`, which already guards `row && typeof row === 'object'` + * — so `null` reaches the engine untouched and the two faces converge with + * no edit at that seam. + * - {@link bulkUpdate}'s `if (updated)` skip stops being DEAD CODE. It is + * the cross-driver convention `SqlDriver.bulkUpdate` follows, and on this + * transport `updated` could never be falsy, so a batch over N missing ids + * answered N invented rows. It now answers the rows that exist. + * + * ⚠️ `upsert()` is deliberately untouched: an upsert never answers + * "not found". + */ + async update(object: string, id: string | number, data: Record): Promise | null> { await this.ensureConnected(); const columns = Object.keys(data); @@ -1546,7 +1577,7 @@ export class RemoteTransport { args: [id], }); const rows = this.mapRows(result); - return rows[0] || { id, ...data }; + return rows[0] ?? null; } async upsert(object: string, data: Record, conflictKeys?: string[]): Promise> { diff --git a/packages/drivers/driver-turso/src/turso-update-missing-id.test.ts b/packages/drivers/driver-turso/src/turso-update-missing-id.test.ts new file mode 100644 index 0000000000..f2d1001559 --- /dev/null +++ b/packages/drivers/driver-turso/src/turso-update-missing-id.test.ts @@ -0,0 +1,244 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#14428] `RemoteTransport.update()` answers a missing id with `null`, so ONE + * `TursoDriver` gives ONE answer to "update a row that is not there". + * + * # What was broken + * + * The door read: + * + * return rows[0] || { id, ...data }; + * + * `UPDATE … WHERE "id" = ?` matching nothing, then `SELECT * … WHERE "id" = ?` + * returning nothing, still handed back a row: the caller's payload with the id + * stapled on. The LOCAL face of the same driver (`SqlDriver.update`, reached + * through `TursoDriver.update`'s `super` branch) answered `null` for the same + * miss. One driver, two answers, chosen by `isRemote` — the divergence class + * this package has already paid for in #5769, #5903, #6203 and #8413. + * + * Since #13878 (PR #14434) `IDataDriver.update()` declares + * `Promise[Record[string, unknown] | null]`, so the fabricated row is not a + * second way of satisfying the declaration — it is the value the declaration + * distinguishes from. Maintainer ruling 2026-09-03, posture A (`null`, not + * throw: a throw would have been a THIRD posture on top of the two this + * collapses). + * + * # Why THIS file rather than cases in the remote suite + * + * #6203's lesson, which this package has paid for twice: a posture that + * differs by face cannot fail a per-face suite. A divergence shows up as one + * file red and the other green, in whichever order someone reads them. The + * divergence itself is the defect, so the divergence is what is pinned — same + * driver, same missing id, both faces, one assertion. + * + * The card measured that NO landed test pinned the miss posture on this driver + * (`turso-driver.test.ts:138,731` and + * `turso-remote-autonumber-refusal.test.ts:369` all read `update()` results + * over rows that EXIST), so every pin here is net-new coverage. + * + * # The pins, and what each alone would miss + * + * - **The transport miss pin** is the defect at its source. + * - **The positive control** beside it is what stops the fix from being + * "return `null` always" — a transport that had simply dropped the read-back + * would pass the miss pin and break every update that works. + * - **The write-still-issued pin**: the `UPDATE` statement still goes out and + * still affects zero rows. A "fix" that short-circuited by reading FIRST + * would answer `null` correctly and silently stop writing. + * - **The `bulkUpdate` pin** is the one the card found as DEAD CODE: + * `if (updated) results.push(updated)` is the cross-driver skip convention + * `SqlDriver.bulkUpdate` follows, and on this transport `updated` could + * never be falsy, so a batch over N missing ids answered N invented rows. + * Its mixed batch also proves the skip is per row, not all-or-nothing. + * - **The parity pin** holds the two `TursoDriver` faces against each other. + * Without it, a future revert of one face alone leaves both single-face + * suites green. + * - **The pass-through pin** covers the seam that needed no edit: + * `TursoDriver.update()`'s remote branch wraps the transport result in + * `formatRemoteRow`, whose `row && typeof row === 'object'` guard already + * admits `null`. That guard is load-bearing now in a way it was not before, + * and nothing else would notice if it were "simplified" away. + * - **The type pin** reads the transport's declared return type, the shape + * #13878's `memory-update-declared-null.test.ts` established. + * + * # Reverse verification, direction predicted BEFORE running + * + * Predicted: restoring `return rows[0] || { id, ...data };` reds the transport + * miss pin, the `bulkUpdate` pin, the REMOTE half of the parity pin and the + * pass-through pin, and reds the type pin's `Equals` const at COMPILE time + * (the whole file then fails to typecheck). The positive control, the + * write-still-issued pin and the LOCAL half of the parity pin stay GREEN — + * they exercise arms the revert does not touch. + * + * ⚠️ One measured trap for whoever runs that verification: the LOCAL face + * arrives here through the BUILT `@objectstack/driver-sql` (this package + * resolves the workspace dependency to its `dist`, and there is no vitest alias + * to `src`), so a source edit there changes nothing until that package is + * rebuilt. The transport and `TursoDriver` themselves ARE this package's `src`. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; + +import { RemoteTransport } from './remote-transport.js'; +import { TursoDriver } from './turso-driver.js'; +import { asLibsqlClient, makeLibsqlSqliteStub, type LibsqlSqliteStub } from './libsql-sqlite-stub.testkit.js'; + +/** `any` defeats ordinary assignability checks; this is the standard detector. */ +type IsAny = 0 extends 1 & T ? true : false; +/** Exact (mutual, non-`any`) type equality. */ +type Equals = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; + +type TransportUpdate = Awaited>; + +const transportUpdateIsAny: IsAny = false; +const transportUpdateIsContract: Equals | null> = true; + +/** The card's object: one row that exists, one id that names nothing. */ +const TASK = { + name: 'task', + fields: { + title: { type: 'string' }, + owner: { type: 'string' }, + }, +} as const; + +describe('[#14428] RemoteTransport.update() on a missing id', () => { + let stub: LibsqlSqliteStub; + let transport: RemoteTransport; + + beforeEach(() => { + stub = makeLibsqlSqliteStub(); + stub.raw.prepare('CREATE TABLE "task" (id TEXT PRIMARY KEY, title TEXT, owner TEXT)').run(); + stub.raw.prepare(`INSERT INTO "task" (id, title, owner) VALUES ('t1', 'before', 'u1')`).run(); + transport = new RemoteTransport(); + transport.setClient(asLibsqlClient(stub)); + }); + + afterEach(() => { + stub.close(); + }); + + it('pins the declared return type', () => { + expect([transportUpdateIsAny, transportUpdateIsContract]).toEqual([false, true]); + }); + + it('seeded the fixture (the premise)', () => { + expect(stub.raw.prepare('SELECT id FROM "task" ORDER BY id').all()).toEqual([{ id: 't1' }]); + }); + + it('resolves null when no row carries that id', async () => { + const result = await transport.update('task', 'no-such-id', { title: 'edited' }); + + expect(result).toBeNull(); + // The narrowing the declared type demands of every caller. + expect(result === null ? 'absent' : result.title).toBe('absent'); + }); + + it('fabricates nothing — the id is not stapled onto the payload', async () => { + const result = await transport.update('task', 'no-such-id', { title: 'edited', owner: 'u9' }); + + // The exact shape the old fallback produced, named so the pin forbids the + // thing rather than only wanting its absence. + expect(result).not.toMatchObject({ id: 'no-such-id' }); + expect(Object.keys((result as Record | null) ?? {})).toEqual([]); + }); + + it('still ISSUES the write — and it lands on zero rows, creating none', async () => { + await transport.update('task', 'no-such-id', { title: 'edited' }); + + // A miss must not become an insert, and the row that exists must be + // untouched by an update aimed at a different id. + expect(stub.raw.prepare('SELECT id, title FROM "task" ORDER BY id').all()).toEqual([ + { id: 't1', title: 'before' }, + ]); + }); + + it('POSITIVE CONTROL — an id that DOES exist still returns the updated row', async () => { + const result = await transport.update('task', 't1', { title: 'after' }); + + expect(result).not.toBeNull(); + expect(result!.id).toBe('t1'); + expect(result!.title).toBe('after'); + expect(stub.raw.prepare(`SELECT title FROM "task" WHERE id = 't1'`).all()).toEqual([{ title: 'after' }]); + }); + + it('bulkUpdate() SKIPS the missing ids — `if (updated)` is no longer dead code', async () => { + stub.raw.prepare(`INSERT INTO "task" (id, title, owner) VALUES ('t2', 'before', 'u2')`).run(); + + const results = await transport.bulkUpdate('task', [ + { id: 't1', data: { title: 'after-1' } }, + { id: 'gone-a', data: { title: 'ghost-a' } }, + { id: 't2', data: { title: 'after-2' } }, + { id: 'gone-b', data: { title: 'ghost-b' } }, + ]); + + // Two rows exist, two ids name nothing: two results, not four. + expect(results).toHaveLength(2); + expect(results.map((r) => r.id)).toEqual(['t1', 't2']); + expect(results.map((r) => r.title)).toEqual(['after-1', 'after-2']); + // The skip is per row, not all-or-nothing: the writes that could land did. + expect(stub.raw.prepare('SELECT id, title FROM "task" ORDER BY id').all()).toEqual([ + { id: 't1', title: 'after-1' }, + { id: 't2', title: 'after-2' }, + ]); + }); +}); + +describe('[#14428] both TursoDriver faces answer a missing id the same way', () => { + let local: TursoDriver; + let remote: TursoDriver; + let stub: LibsqlSqliteStub; + + beforeEach(async () => { + local = new TursoDriver({ url: ':memory:' }); + expect(local.transportMode).toBe('local'); + await local.initObjects([{ ...TASK, fields: { ...TASK.fields } }]); + await local.create('task', { id: 't1', title: 'before', owner: 'u1' }, { bypassTenantAudit: true }); + + stub = makeLibsqlSqliteStub(); + remote = new TursoDriver({ url: 'libsql://update-miss.turso.io', client: asLibsqlClient(stub) }); + await remote.connect(); + expect(remote.transportMode).toBe('remote'); + await remote.initObjects([{ ...TASK, fields: { ...TASK.fields } }]); + await remote.create('task', { id: 't1', title: 'before', owner: 'u1' }, { bypassTenantAudit: true }); + }); + + afterEach(async () => { + await local.disconnect(); + await remote.disconnect(); + stub.close(); + }); + + it('PARITY — one missing id, two faces, one answer', async () => { + const localMiss = await local.update('task', 'no-such-id', { title: 'edited' }); + const remoteMiss = await remote.update('task', 'no-such-id', { title: 'edited' }); + + expect(localMiss).toBeNull(); + expect(remoteMiss, 'local/remote divergence on the not-found arm').toEqual(localMiss); + }); + + it('PARITY POSITIVE CONTROL — one id that exists, two faces, both return the row', async () => { + const localHit = await local.update('task', 't1', { title: 'after' }); + const remoteHit = await remote.update('task', 't1', { title: 'after' }); + + expect(localHit).not.toBeNull(); + expect(remoteHit).not.toBeNull(); + expect(localHit.id).toBe('t1'); + expect(remoteHit.id).toBe('t1'); + expect(localHit.title).toBe('after'); + expect(remoteHit.title).toBe('after'); + }); + + it('the remote branch passes `null` through `formatRemoteRow` untouched', async () => { + // `TursoDriver.update()`'s remote branch is + // `this.formatRemoteRow(object, await this.remoteTransport!.update(...))`, + // and `formatRemoteRow` guards `row && typeof row === 'object'`. That guard + // needed no edit for this card — which is exactly why it needs a pin: it is + // load-bearing now, and nothing else would fail if it were removed as + // "defensive". `typeof null === 'object'`, so an unguarded `formatOutput` + // would reach a null row here. + const result = await remote.update('task', 'absent', { title: 'edited' }); + expect(result).toBeNull(); + }); +}); From 87696991120036de3ac3508f6dd38c77dabd1b50 Mon Sep 17 00:00:00 2001 From: os-musk Date: Thu, 3 Sep 2026 10:43:48 +0000 Subject: [PATCH 2/3] fix(driver-mongodb): narrow the three found-arm `update()` reads in mongodb-driver.test.ts The widened `update(): Promise | null>` declaration made `expect(result.title|.status|.id)` three TS18047 errors. The package tsconfig excludes `**/*.test.ts`, so `pnpm typecheck` could not see them; the type-check debt ratchet re-measures with the tests un-hidden and caught the +3 (10 -> 13). Narrowed at the three sites with the file's own `findOne` idiom -- assert the found arm, then read through it. Re-measured with the ratchet's own project shape: back to exactly 10 (TS1309 x7 + TS2550 x3), the ledger's frozen entry. The ledger is NOT raised. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_0112hMx9hjJ9BgB28X97DS68 --- .../drivers/driver-mongodb/src/mongodb-driver.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/drivers/driver-mongodb/src/mongodb-driver.test.ts b/packages/drivers/driver-mongodb/src/mongodb-driver.test.ts index fb67a16798..6b0ccfc11e 100644 --- a/packages/drivers/driver-mongodb/src/mongodb-driver.test.ts +++ b/packages/drivers/driver-mongodb/src/mongodb-driver.test.ts @@ -155,9 +155,13 @@ describe.skipIf(!sharedMongod)('MongoDBDriver', () => { it('should update a record and return updated data', async () => { await driver.create('task', { id: 'upd-1', title: 'Original', status: 'new' }); const result = await driver.update('task', 'upd-1', { title: 'Updated', status: 'done' }); - expect(result.title).toBe('Updated'); - expect(result.status).toBe('done'); - expect(result.id).toBe('upd-1'); + // `update()` declares `Record | null` (#14428): a miss + // answers `null`. This case is the FOUND arm, so pin that first and read + // the fields through it -- same idiom as `findOne` above. + expect(result).not.toBeNull(); + expect(result!.title).toBe('Updated'); + expect(result!.status).toBe('done'); + expect(result!.id).toBe('upd-1'); expect(result).not.toHaveProperty('_id'); }); From c2400c547e98c7ee22cbabfa3968eac5afce3cf0 Mon Sep 17 00:00:00 2001 From: os-musk Date: Thu, 3 Sep 2026 10:54:21 +0000 Subject: [PATCH 3/3] docs(drivers): correct the changeset semver row and the two test headers to what was measured Contract-review round on PR #14914. Changeset: `patch`/`patch` understated a published TYPE-surface narrowing plus a runtime behaviour change on two published drivers. Now `minor`/`minor` with a `**BREAKING**` sentence naming what breaks for TypeScript consumers, and exactly one ADR-0087 disposition -- `not-required (no-migration-prescription)`, the same shape and reasoning as `.changeset/driver-memory-update-upsert-honest-types.md` (PR #14434) one day earlier in this series. `type-surface-only` is not claimable: its predicate 4 (narrowed-from-erased) is false, and runtime behaviour moves too. `mongodb-update-missing-id.test.ts`: the header claimed a type-level pin here would be "never checked by anything". False -- `pnpm check:type-check-debt` re-measures this package with its tests un-hidden, which is exactly how CI caught the three TS18047 the widened declaration introduced. The section now states both programs, names the tsconfig exclusion as the filed defect (#14917), and gives the real reason the pin lives in the turso twin instead. Its reverse-verification paragraph now reports the OBSERVED leg (2 failed | 2 passed (4), all four ran) rather than predicting a compile-time red for a type pin this file does not have. `turso-update-missing-id.test.ts`: same correction. Restoring the fabricating EXPRESSION leaves the declaration untouched, so the `Equals` const cannot red and nothing fails at compile time; the parity pin is one assertion, not two halves; and the no-fabrication pin, omitted before, does red. The paragraph now names all five reds and all five greens from the run. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_0112hMx9hjJ9BgB28X97DS68 --- .changeset/driver-update-missing-id-null.md | 27 ++++++-- .../src/mongodb-update-missing-id.test.ts | 64 +++++++++++++------ .../src/turso-update-missing-id.test.ts | 30 +++++++-- 3 files changed, 88 insertions(+), 33 deletions(-) diff --git a/.changeset/driver-update-missing-id-null.md b/.changeset/driver-update-missing-id-null.md index 2175fa4b22..f170d3572e 100644 --- a/.changeset/driver-update-missing-id-null.md +++ b/.changeset/driver-update-missing-id-null.md @@ -1,14 +1,25 @@ --- -"@objectstack/driver-mongodb": patch -"@objectstack/driver-turso": patch +"@objectstack/driver-mongodb": minor +"@objectstack/driver-turso": minor --- fix(drivers): `update()` on a missing id answers `null` on MongoDB and on Turso's remote face +**BREAKING** for TypeScript consumers — a published TYPE-surface narrowing alongside a +runtime behaviour change, shipped as `minor` under the launch-window convention. Two +published declared returns move: `MongoDBDriver.update()` and `RemoteTransport.update()` +(both exported from their package index) now declare +`Promise | null>` where they declared +`Promise>`. A caller that reads fields off either result — +`result.id`, `result.title` — no longer compiles until it narrows the `null` arm first. +The narrowing is delivered by the compiler at every call site, and it is the honest +declaration: the value that arm carries has always been reachable, it was simply being +answered with a fabricated record instead. + `IDataDriver.update()` declares `Promise | null>` — the -not-found arm landed with the ruling on the contract, and it is the answer -`InMemoryDriver`, `SqlDriver`, `SqliteWasmDriver` and `TursoDriver`'s local face -have always given. Two implementations did not honour it. They **invented a +not-found arm landed with the ruling on the contract (`packages/spec` is untouched here), +and it is the answer `InMemoryDriver`, `SqlDriver`, `SqliteWasmDriver` and `TursoDriver`'s +local face have always given. Two implementations did not honour it. They **invented a record** instead: - `MongoDBDriver.update()` ran `updateOne({ id })`, then `findOne({ id })`, and @@ -20,7 +31,9 @@ record** instead: `SELECT * … WHERE "id" = ?`, and when no row came back returned `{ id, ...data }` — the caller's payload with the id stapled on. -Both now return `null`. +Both now return `null`. That is the runtime half of this change, and it is why this +release is not a pure type-surface move: the value a caller receives for a missing id is +different at run time, not only in the `.d.ts`. This is the expensive direction of wrong, not merely the wrong answer: the fabricated row said **succeeded** where the truth was **not found**, and said it @@ -47,3 +60,5 @@ Two things downstream become correct rather than merely different: No landed test pinned the fabricating posture on either driver, so the regression pins added here are net-new coverage rather than a changed baseline. + + diff --git a/packages/drivers/driver-mongodb/src/mongodb-update-missing-id.test.ts b/packages/drivers/driver-mongodb/src/mongodb-update-missing-id.test.ts index 5c7f9aae8d..c542f82cff 100644 --- a/packages/drivers/driver-mongodb/src/mongodb-update-missing-id.test.ts +++ b/packages/drivers/driver-mongodb/src/mongodb-update-missing-id.test.ts @@ -23,7 +23,7 @@ * # Why this file exists at all * * The card measured that NO landed test pinned the miss posture on this driver - * — `mongodb-driver.test.ts:157,171` read `update()` results over rows that + * — `mongodb-driver.test.ts:157,175` read `update()` results over rows that * EXIST. So this is net-new coverage, and the fabricating posture could have * come back without reddening anything. * @@ -54,23 +54,38 @@ * `updateOne` is still sent. A "fix" that short-circuited on a miss by * reading FIRST would answer `null` correctly and quietly stop writing. * - * # ⚠️ There is deliberately NO type-level pin in this file — MEASURED + * # ⚠️ There is deliberately NO type-level pin in this file — and NOT because + * # nothing would read one * * #13878's `memory-update-declared-null.test.ts` pins the declared return type - * with `Equals`/`IsAny` consts. That instrument does not work HERE and would be - * a phantom: this package's `tsconfig.json` carries - * `"exclude": [..., "**\/*.test.ts"]` (escaped here so this very comment does - * not terminate early), so no test file is in its tsc program and - * a `const x: Equals[A, B] = true` here is never checked by anything — vitest - * transpiles without typechecking, and the root `tsconfig.json` excludes - * `packages` entirely, so no repo-wide program picks it up either. Measured, - * not assumed: `tsc --noEmit --listFiles` in this package lists 0 files ending - * `.test.ts` (the sibling `driver-turso`, whose tsconfig excludes only - * `node_modules`/`dist`, lists 43 — which is why the twin file - * `turso-update-missing-id.test.ts` DOES carry the type pin). - * - * The declared type is nevertheless pinned, in both directions, by instruments - * that DO run: + * with `Equals`/`IsAny` consts. That instrument reaches this file through only + * ONE program, and it is not the one whose name is on the package: + * + * - **This package's own `typecheck` script cannot see it.** `tsconfig.json` + * here carries `"exclude": [..., "**\/*.test.ts"]` (escaped so this comment + * does not terminate early), and `tsc --noEmit` reads that config. Measured, + * not assumed: `tsc --noEmit --listFiles` in this package lists 0 files + * ending `.test.ts` (the sibling `driver-turso`, whose tsconfig excludes + * only `node_modules`/`dist`, lists 43). vitest transpiles without + * typechecking, and the root `tsconfig.json` excludes `packages` entirely, + * so neither of those picks it up either. That exclusion is itself a filed + * defect (#14917), not a design. + * - **`pnpm check:type-check-debt` DOES compile it.** The ratchet's + * `--re-measure` leg generates a project that drops the test exclusion and + * runs `tsc` over this package with its tests un-hidden, then compares the + * error count to the frozen `TEST_DEBT['@objectstack/driver-mongodb']` entry + * (10: `TS1309` x7 + `TS2550` x3). ⭐ Not theory: the first head of this + * branch widened `update()`'s declaration, the three found-arm reads in + * `mongodb-driver.test.ts` became `TS18047 'result' is possibly 'null'`, and + * that lane went red at 13 (+3) while `pnpm typecheck` stayed green. CI + * caught in this file's layer exactly what the package's own typecheck is + * blind to. + * + * So a type pin here would not be a phantom — it would be checked, once, in a + * lane that reports a break as a ledger COUNT moving rather than as a named + * assertion failure, and that reports it only when someone runs the whole-repo + * re-measure. The declaration is pinned by better instruments instead, both of + * which run in this package's own `typecheck`: * * - **narrowing the declaration back** to `Promise[Record[string, unknown]]` * is a `tsc` error in `mongodb-driver.ts` itself — that file IS in the @@ -82,13 +97,20 @@ * - **reverting the behaviour** while keeping the signature reds the runtime * pins below. * - * # Reverse verification, direction predicted BEFORE running + * # Reverse verification — predicted direction, then what was OBSERVED * * Predicted: restoring the `|| withoutUndefinedOwnKeys({ id: String(id), - * ...updateData })` fallback reds the miss pin and the no-fabrication pin, and - * reds the type pin's `Equals` const at COMPILE time (so the whole file fails - * to typecheck) while the positive control and the write-still-issued pin stay - * GREEN — they exercise the found arm, which the revert does not touch. + * ...updateData })` fallback reds the miss pin and the no-fabrication pin, + * while the positive control and the write-still-issued pin stay GREEN — they + * exercise the found arm, which the revert does not touch. + * + * Observed, with the mutation proved on disk (injected text counted, deleted + * text absent) and the restore proved by a `git hash-object` match against the + * HEAD blob: `Test Files 1 failed (1)`, `Tests 2 failed | 2 passed (4)`. The + * two reds are the miss pin and the no-fabrication pin, by name. ⚠️ All FOUR + * cases ran — there is no compile-time leg here, because there is no type pin + * in this file to red; a prediction that the file would fail to typecheck as a + * whole would have been wrong for exactly that reason. */ import { describe, it, expect } from 'vitest'; diff --git a/packages/drivers/driver-turso/src/turso-update-missing-id.test.ts b/packages/drivers/driver-turso/src/turso-update-missing-id.test.ts index f2d1001559..be839788c9 100644 --- a/packages/drivers/driver-turso/src/turso-update-missing-id.test.ts +++ b/packages/drivers/driver-turso/src/turso-update-missing-id.test.ts @@ -62,14 +62,32 @@ * - **The type pin** reads the transport's declared return type, the shape * #13878's `memory-update-declared-null.test.ts` established. * - * # Reverse verification, direction predicted BEFORE running + * # Reverse verification — predicted direction, then what was OBSERVED * * Predicted: restoring `return rows[0] || { id, ...data };` reds the transport - * miss pin, the `bulkUpdate` pin, the REMOTE half of the parity pin and the - * pass-through pin, and reds the type pin's `Equals` const at COMPILE time - * (the whole file then fails to typecheck). The positive control, the - * write-still-issued pin and the LOCAL half of the parity pin stay GREEN — - * they exercise arms the revert does not touch. + * miss pin, the no-fabrication pin, the `bulkUpdate` pin, the parity pin and + * the pass-through pin. The positive control, the write-still-issued pin, the + * parity positive control and the fixture premise stay GREEN — they exercise + * arms the revert does not touch. + * + * ⚠️ The type pin is NOT on either list, and that is the point of writing this + * paragraph from the measurement rather than from the shape of the fix. The + * mutation restores an EXPRESSION; the declared return type stays + * `Promise[Record[string, unknown] | null]`, so `Equals` still holds and the + * const cannot red. Nothing here fails at compile time, and all ten cases run. + * The parity pin is likewise ONE assertion over both faces, not two halves that + * can red independently — that indivisibility is the whole reason it exists. + * + * Observed, with the mutation proved on disk (injected text counted, deleted + * text absent) and the restore proved by a `git hash-object` match against the + * HEAD blob: `Test Files 1 failed (1)`, `Tests 5 failed | 5 passed (10)`. The + * five reds, by name: `resolves null when no row carries that id`, + * `fabricates nothing — the id is not stapled onto the payload`, + * `bulkUpdate() SKIPS the missing ids`, `PARITY — one missing id, two faces, + * one answer`, and `the remote branch passes 'null' through formatRemoteRow + * untouched`. The five greens: `pins the declared return type`, `seeded the + * fixture (the premise)`, `still ISSUES the write`, `POSITIVE CONTROL` and + * `PARITY POSITIVE CONTROL`. * * ⚠️ One measured trap for whoever runs that verification: the LOCAL face * arrives here through the BUILT `@objectstack/driver-sql` (this package