|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #5979 — `seedAutonumber` must not answer a READ OUTAGE with "seed from 0". |
| 5 | + * |
| 6 | + * The engine's fallback autonumber path seeds its in-memory counter from |
| 7 | + * `MAX(existing)` in the store, then increments. That seeding read used to sit |
| 8 | + * behind a bare `} catch { return 0; }`: EVERY failure — connection drop, |
| 9 | + * timeout, permission denial, query error — was answered with the same `0` a |
| 10 | + * genuinely empty table produces. |
| 11 | + * |
| 12 | + * Those are opposite facts (ADR-0110 D3), and conflating them here is the |
| 13 | + * costly half of the #4728 / #4825 / #5108 family. Against a table that already |
| 14 | + * holds N rows, one flaky read restarts the sequence at 1 and issues autonumbers |
| 15 | + * that COLLIDE with existing ones. The insert SUCCEEDS, nothing is logged, and |
| 16 | + * the collision lands in a business identifier — a value written wrong, which no |
| 17 | + * retry and no restart repairs. The hazard was already named in the comment |
| 18 | + * directly above the read (#4371: "the catch below would have swallowed the |
| 19 | + * guard's rejection into 'seed from 0', i.e. duplicate autonumbers"); the read |
| 20 | + * was fixed there, the catch was not. |
| 21 | + * |
| 22 | + * The fix discriminates by error TYPE through the shared `isMissingTableError` |
| 23 | + * predicate (`@objectstack/metadata/errors`, #4825) — never a hand-rolled |
| 24 | + * `code === '42P01'` copy, which would be the second "which driver errors are |
| 25 | + * benign" vocabulary that module exists to retire: |
| 26 | + * |
| 27 | + * - table never provisioned → seed from 0 (there are genuinely no rows, so |
| 28 | + * number 1 collides with nothing); |
| 29 | + * - every other read failure → propagate, allocate NOTHING, write NOTHING. |
| 30 | + * |
| 31 | + * These tests drive a fake DRIVER (not a fake engine), so no engine write-verb |
| 32 | + * dispatch contract is involved. |
| 33 | + */ |
| 34 | + |
| 35 | +import { describe, it, expect, vi, beforeEach } from 'vitest'; |
| 36 | +import { ObjectQL } from './engine'; |
| 37 | +import { SchemaRegistry } from './registry'; |
| 38 | +import type { IDataDriver } from '@objectstack/spec/contracts'; |
| 39 | + |
| 40 | +vi.mock('./registry', () => { |
| 41 | + const instance: any = { |
| 42 | + getObject: vi.fn(), |
| 43 | + resolveObject: vi.fn((n: string) => instance.getObject(n)), |
| 44 | + registerObject: vi.fn(), |
| 45 | + getObjectOwner: vi.fn(), |
| 46 | + registerNamespace: vi.fn(), |
| 47 | + registerKind: vi.fn(), |
| 48 | + registerItem: vi.fn(), |
| 49 | + registerApp: vi.fn(), |
| 50 | + installPackage: vi.fn(), |
| 51 | + reset: vi.fn(), |
| 52 | + metadata: { get: vi.fn(() => new Map()) }, |
| 53 | + }; |
| 54 | + function SchemaRegistry() { |
| 55 | + return instance; |
| 56 | + } |
| 57 | + Object.assign(SchemaRegistry, instance); |
| 58 | + return { |
| 59 | + SchemaRegistry, |
| 60 | + computeFQN: (_ns: string | undefined, name: string) => name, |
| 61 | + parseFQN: (fqn: string) => ({ namespace: undefined, shortName: fqn }), |
| 62 | + RESERVED_NAMESPACES: new Set(['base', 'system']), |
| 63 | + }; |
| 64 | +}); |
| 65 | + |
| 66 | +const DOC_SCHEMA = { |
| 67 | + name: 'doc', |
| 68 | + fields: { |
| 69 | + title: { type: 'text' }, |
| 70 | + doc_no: { type: 'autonumber', required: true, format: 'D-{0000}' }, |
| 71 | + }, |
| 72 | +}; |
| 73 | + |
| 74 | +/** |
| 75 | + * A driver whose seeding read (`find`) behaves as `findBehaviour` says, and |
| 76 | + * which records every row it was asked to create. `create` recording is the |
| 77 | + * load-bearing half: the defect's signature is a write that SUCCEEDS with a |
| 78 | + * colliding number, so "no row reached the driver" is what proves the fix. |
| 79 | + */ |
| 80 | +function makeDriver(findBehaviour: () => Promise<any[]>): IDataDriver & { |
| 81 | + created: any[]; |
| 82 | +} { |
| 83 | + const created: any[] = []; |
| 84 | + const driver: any = { |
| 85 | + name: 'memory', |
| 86 | + version: '0.0.0', |
| 87 | + // No native autonumber → the engine takes the fallback seeding path. |
| 88 | + supports: {}, |
| 89 | + connect: vi.fn().mockResolvedValue(undefined), |
| 90 | + disconnect: vi.fn().mockResolvedValue(undefined), |
| 91 | + checkHealth: vi.fn().mockResolvedValue(true), |
| 92 | + execute: vi.fn(), |
| 93 | + find: vi.fn(findBehaviour), |
| 94 | + findOne: vi.fn(), |
| 95 | + create: vi.fn(async (_obj: string, row: any) => { |
| 96 | + created.push(row); |
| 97 | + return { id: `r${created.length}`, ...row }; |
| 98 | + }), |
| 99 | + update: vi.fn(), |
| 100 | + delete: vi.fn(), |
| 101 | + count: vi.fn(), |
| 102 | + }; |
| 103 | + driver.created = created; |
| 104 | + return driver as any; |
| 105 | +} |
| 106 | + |
| 107 | +/** Driver-shaped errors that mean "the table was never provisioned". */ |
| 108 | +const MISSING_TABLE_ERRORS: Array<[string, () => unknown]> = [ |
| 109 | + ['PostgreSQL 42P01 undefined_table', () => Object.assign(new Error('relation "doc" does not exist'), { code: '42P01' })], |
| 110 | + ['MySQL ER_NO_SUCH_TABLE', () => Object.assign(new Error("Table 'app.doc' doesn't exist"), { code: 'ER_NO_SUCH_TABLE', errno: 1146 })], |
| 111 | + ['SQLite message-only', () => new Error('no such table: doc')], |
| 112 | +]; |
| 113 | + |
| 114 | +/** |
| 115 | + * Driver-shaped errors that mean "the rows may well exist — I just could not |
| 116 | + * see them". Each is a real outage class the old bare catch answered with 0. |
| 117 | + */ |
| 118 | +const OUTAGE_ERRORS: Array<[string, () => unknown]> = [ |
| 119 | + ['connection refused', () => Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { code: 'ECONNREFUSED' })], |
| 120 | + ['statement timeout', () => Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' })], |
| 121 | + ['permission denied', () => Object.assign(new Error('permission denied for table doc'), { code: '42501' })], |
| 122 | + ['connection terminated mid-query', () => Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' })], |
| 123 | +]; |
| 124 | + |
| 125 | +describe('ObjectQL seedAutonumber — read outage must not restart the sequence (#5979)', () => { |
| 126 | + let engine: ObjectQL; |
| 127 | + |
| 128 | + beforeEach(() => { |
| 129 | + vi.clearAllMocks(); |
| 130 | + vi.mocked(SchemaRegistry.getObject).mockReturnValue(DOC_SCHEMA as any); |
| 131 | + engine = new ObjectQL(); |
| 132 | + }); |
| 133 | + |
| 134 | + // ---------------------------------------------------------------- benign -- |
| 135 | + |
| 136 | + describe('table not provisioned → seed from 0 (benign, unchanged)', () => { |
| 137 | + for (const [label, make] of MISSING_TABLE_ERRORS) { |
| 138 | + it(`seeds from 0 and issues number 1 — ${label}`, async () => { |
| 139 | + const driver = makeDriver(async () => { |
| 140 | + throw make(); |
| 141 | + }); |
| 142 | + engine.registerDriver(driver, true); |
| 143 | + await engine.init(); |
| 144 | + |
| 145 | + const result = await engine.insert('doc', { title: 'First' }); |
| 146 | + |
| 147 | + // There are genuinely no rows, so 1 collides with nothing. |
| 148 | + expect(result.doc_no).toBe('D-0001'); |
| 149 | + expect(driver.created).toHaveLength(1); |
| 150 | + expect(driver.created[0].doc_no).toBe('D-0001'); |
| 151 | + }); |
| 152 | + } |
| 153 | + |
| 154 | + it('keeps counting in memory after a benign seed (second insert is 2)', async () => { |
| 155 | + const driver = makeDriver(async () => { |
| 156 | + throw Object.assign(new Error('no such table: doc'), {}); |
| 157 | + }); |
| 158 | + engine.registerDriver(driver, true); |
| 159 | + await engine.init(); |
| 160 | + |
| 161 | + const a = await engine.insert('doc', { title: 'First' }); |
| 162 | + const b = await engine.insert('doc', { title: 'Second' }); |
| 163 | + |
| 164 | + expect(a.doc_no).toBe('D-0001'); |
| 165 | + expect(b.doc_no).toBe('D-0002'); |
| 166 | + }); |
| 167 | + }); |
| 168 | + |
| 169 | + // ---------------------------------------------------------------- outage -- |
| 170 | + |
| 171 | + describe('read outage → propagate, allocate nothing, write nothing', () => { |
| 172 | + for (const [label, make] of OUTAGE_ERRORS) { |
| 173 | + it(`rethrows and writes NOTHING — ${label}`, async () => { |
| 174 | + const driver = makeDriver(async () => { |
| 175 | + throw make(); |
| 176 | + }); |
| 177 | + engine.registerDriver(driver, true); |
| 178 | + await engine.init(); |
| 179 | + |
| 180 | + await expect(engine.insert('doc', { title: 'First' })).rejects.toThrow(); |
| 181 | + |
| 182 | + // The whole point: no row reached the driver, so no autonumber was |
| 183 | + // issued from data the engine never read. |
| 184 | + expect(driver.create).not.toHaveBeenCalled(); |
| 185 | + expect(driver.created).toHaveLength(0); |
| 186 | + }); |
| 187 | + } |
| 188 | + |
| 189 | + it('propagates the ORIGINAL driver error, not a synthesized one', async () => { |
| 190 | + const original = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { |
| 191 | + code: 'ECONNREFUSED', |
| 192 | + }); |
| 193 | + const driver = makeDriver(async () => { |
| 194 | + throw original; |
| 195 | + }); |
| 196 | + engine.registerDriver(driver, true); |
| 197 | + await engine.init(); |
| 198 | + |
| 199 | + // The caller needs the driver's own diagnosis to act on; swallowing it |
| 200 | + // into a generic failure would repeat the zero-signal half of the defect. |
| 201 | + await expect(engine.insert('doc', { title: 'First' })).rejects.toThrow(/ECONNREFUSED/); |
| 202 | + }); |
| 203 | + |
| 204 | + /** |
| 205 | + * The defect's actual damage, pinned directly: a table already holding |
| 206 | + * D-0007 must never be handed D-0001 because one read failed. |
| 207 | + */ |
| 208 | + it('does NOT restart at 1 against a table that already holds rows', async () => { |
| 209 | + let outage = true; |
| 210 | + const driver = makeDriver(async () => { |
| 211 | + if (outage) throw Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' }); |
| 212 | + return [{ id: 'r1', doc_no: 'D-0007' }]; |
| 213 | + }); |
| 214 | + engine.registerDriver(driver, true); |
| 215 | + await engine.init(); |
| 216 | + |
| 217 | + // During the outage the write fails rather than forging a colliding number. |
| 218 | + await expect(engine.insert('doc', { title: 'During outage' })).rejects.toThrow(); |
| 219 | + expect(driver.created).toHaveLength(0); |
| 220 | + |
| 221 | + // Once the store recovers, seeding reads the real max and continues from |
| 222 | + // it. This also proves the failed seed poisoned no in-memory counter — |
| 223 | + // had the outage cached a 0, this would come back D-0001. |
| 224 | + outage = false; |
| 225 | + const recovered = await engine.insert('doc', { title: 'After recovery' }); |
| 226 | + expect(recovered.doc_no).toBe('D-0008'); |
| 227 | + }); |
| 228 | + }); |
| 229 | + |
| 230 | + // ---------------------------------------------------------------- normal -- |
| 231 | + |
| 232 | + describe('normal read path is unchanged', () => { |
| 233 | + it('seeds from the max of existing rows', async () => { |
| 234 | + const driver = makeDriver(async () => [ |
| 235 | + { id: 'r1', doc_no: 'D-0003' }, |
| 236 | + { id: 'r2', doc_no: 'D-0011' }, |
| 237 | + { id: 'r3', doc_no: 'D-0007' }, |
| 238 | + ]); |
| 239 | + engine.registerDriver(driver, true); |
| 240 | + await engine.init(); |
| 241 | + |
| 242 | + const result = await engine.insert('doc', { title: 'Next' }); |
| 243 | + |
| 244 | + expect(result.doc_no).toBe('D-0012'); |
| 245 | + }); |
| 246 | + |
| 247 | + it('seeds from 0 when the table exists and is genuinely empty', async () => { |
| 248 | + const driver = makeDriver(async () => []); |
| 249 | + engine.registerDriver(driver, true); |
| 250 | + await engine.init(); |
| 251 | + |
| 252 | + const result = await engine.insert('doc', { title: 'First' }); |
| 253 | + |
| 254 | + expect(result.doc_no).toBe('D-0001'); |
| 255 | + }); |
| 256 | + }); |
| 257 | +}); |
0 commit comments