T-151: M2.1i — findings + provider_caveats append-only PostgreSQL migration (research track, 37-research-findings.sql) with fresh-database schema tests (no adapters, no new deps)
This commit is contained in:
parent
c16d6b3f60
commit
310354b54a
3 changed files with 77 additions and 29 deletions
|
|
@ -3,6 +3,20 @@
|
|||
-- lookup/idempotency indexes, and immutability triggers reusing
|
||||
-- reject_research_evidence_mutation() from 17-research-retention.sql.
|
||||
|
||||
CREATE OR REPLACE FUNCTION research_trim_ecmascript(value TEXT)
|
||||
RETURNS TEXT
|
||||
LANGUAGE SQL
|
||||
IMMUTABLE
|
||||
STRICT
|
||||
AS $$
|
||||
-- Explicit ECMAScript WhiteSpace + LineTerminator set so nonblank checks and
|
||||
-- trimmed length caps match String.prototype.trim() regardless of DB collation.
|
||||
SELECT btrim(
|
||||
value,
|
||||
U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF'
|
||||
);
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION research_finding_refs_valid(refs TEXT[], max_len INTEGER)
|
||||
RETURNS BOOLEAN
|
||||
LANGUAGE SQL
|
||||
|
|
@ -20,15 +34,15 @@ $$;
|
|||
|
||||
CREATE TABLE IF NOT EXISTS findings (
|
||||
id TEXT PRIMARY KEY
|
||||
CHECK (id ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(id) <> ''),
|
||||
kind TEXT NOT NULL
|
||||
CHECK (kind IN ('finding', 'dead_end')),
|
||||
title TEXT NOT NULL
|
||||
CHECK (char_length(regexp_replace(title, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 256),
|
||||
CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256),
|
||||
summary TEXT NOT NULL
|
||||
CHECK (char_length(regexp_replace(summary, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 4096),
|
||||
CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096),
|
||||
status TEXT NOT NULL DEFAULT 'pending_review'
|
||||
CHECK (status ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(status) <> ''),
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
trial_refs TEXT[] NOT NULL
|
||||
CHECK (cardinality(trial_refs) <= 32)
|
||||
|
|
@ -39,7 +53,7 @@ CREATE TABLE IF NOT EXISTS findings (
|
|||
CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1)
|
||||
CHECK (research_finding_refs_valid(evidence_refs, 256)),
|
||||
idempotency_key TEXT
|
||||
CHECK (idempotency_key IS NULL OR (idempotency_key ~ '\S' AND char_length(idempotency_key) BETWEEN 1 AND 128))
|
||||
CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128))
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key
|
||||
|
|
@ -51,13 +65,13 @@ CREATE INDEX IF NOT EXISTS idx_findings_created_at
|
|||
|
||||
CREATE TABLE IF NOT EXISTS provider_caveats (
|
||||
id TEXT PRIMARY KEY
|
||||
CHECK (id ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(id) <> ''),
|
||||
provider TEXT NOT NULL
|
||||
CHECK (provider ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(provider) <> ''),
|
||||
dataset TEXT NOT NULL
|
||||
CHECK (dataset ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(dataset) <> ''),
|
||||
caveat TEXT NOT NULL
|
||||
CHECK (caveat ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(caveat) <> ''),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -200,20 +200,20 @@ Applied via `@stock-bot/postgres` (`research` migration track, `database/postgre
|
|||
|
||||
- **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`.
|
||||
- **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt.
|
||||
- **Character-length convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters.
|
||||
- **Character-length & whitespace convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). Nonblank and trimmed-length checks use `research_trim_ecmascript(...)`, which strips the explicit 25-character ECMAScript `WhiteSpace` + `LineTerminator` set (`U+0009`..`U+000D`, `U+0020`, `U+00A0`, `U+1680`, `U+2000`..`U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`) regardless of database collation. JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters.
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS findings (
|
||||
id TEXT PRIMARY KEY
|
||||
CHECK (id ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(id) <> ''),
|
||||
kind TEXT NOT NULL
|
||||
CHECK (kind IN ('finding', 'dead_end')),
|
||||
title TEXT NOT NULL
|
||||
CHECK (char_length(regexp_replace(title, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 256),
|
||||
CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256),
|
||||
summary TEXT NOT NULL
|
||||
CHECK (char_length(regexp_replace(summary, '^\s+|\s+$', '', 'g')) BETWEEN 1 AND 4096),
|
||||
CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096),
|
||||
status TEXT NOT NULL DEFAULT 'pending_review'
|
||||
CHECK (status ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(status) <> ''),
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
trial_refs TEXT[] NOT NULL
|
||||
CHECK (cardinality(trial_refs) <= 32)
|
||||
|
|
@ -224,7 +224,7 @@ CREATE TABLE IF NOT EXISTS findings (
|
|||
CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1)
|
||||
CHECK (research_finding_refs_valid(evidence_refs, 256)),
|
||||
idempotency_key TEXT
|
||||
CHECK (idempotency_key IS NULL OR (idempotency_key ~ '\S' AND char_length(idempotency_key) BETWEEN 1 AND 128))
|
||||
CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128))
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key
|
||||
|
|
@ -236,13 +236,13 @@ CREATE INDEX IF NOT EXISTS idx_findings_created_at
|
|||
|
||||
CREATE TABLE IF NOT EXISTS provider_caveats (
|
||||
id TEXT PRIMARY KEY
|
||||
CHECK (id ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(id) <> ''),
|
||||
provider TEXT NOT NULL
|
||||
CHECK (provider ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(provider) <> ''),
|
||||
dataset TEXT NOT NULL
|
||||
CHECK (dataset ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(dataset) <> ''),
|
||||
caveat TEXT NOT NULL
|
||||
CHECK (caveat ~ '\S'),
|
||||
CHECK (research_trim_ecmascript(caveat) <> ''),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -29,16 +29,26 @@ async function createIsolatedFixture() {
|
|||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
|
||||
});
|
||||
const poolUrl = new URL(url);
|
||||
const existingOptions = poolUrl.searchParams.get('options')?.trim();
|
||||
const fixtureOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`;
|
||||
poolUrl.searchParams.set(
|
||||
'options',
|
||||
existingOptions ? `${existingOptions} ${fixtureOptions}` : fixtureOptions
|
||||
);
|
||||
const pool = new Pool({ connectionString: poolUrl.toString() });
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
|
||||
const activeSchema = (await pool.query<{ schema: string }>('SELECT current_schema() AS schema'))
|
||||
.rows[0]?.schema;
|
||||
if (activeSchema !== schema) {
|
||||
throw new Error(`Expected active fixture schema ${schema}, got ${activeSchema ?? 'null'}`);
|
||||
}
|
||||
|
||||
// Bootstrap pre-additive tables needed by the research migration track.
|
||||
for (const filename of [
|
||||
'06-create-backtest-tables.sql',
|
||||
|
|
@ -308,14 +318,15 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => {
|
|||
expect(first.evidence_refs).toEqual(['artifact:drift-v1']);
|
||||
expect(first.idempotency_key).toBe('req-001');
|
||||
|
||||
// Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities.
|
||||
// Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities
|
||||
// including Unicode NBSP / ideographic-space padding around max-length title and summary.
|
||||
const maxRefs = Array.from({ length: 32 }, (_, i) => `${i}`.padStart(256, 'r'));
|
||||
const boundary = (
|
||||
await insertFinding(f.pool, {
|
||||
id: 'finding-002',
|
||||
kind: 'dead_end',
|
||||
title: ` ${'t'.repeat(256)} `,
|
||||
summary: 's'.repeat(4096),
|
||||
title: `\u00A0${'t'.repeat(256)}\u00A0`,
|
||||
summary: `\u00A0\u3000${'s'.repeat(4096)}\u00A0`,
|
||||
createdAt: '2026-02-01T00:00:00.000Z',
|
||||
trialRefs: maxRefs,
|
||||
evidenceRefs: [],
|
||||
|
|
@ -347,24 +358,37 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => {
|
|||
test('findings rejects invalid kind, blank or oversized fields, malformed ref arrays, and invalid idempotency keys', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
// Blank / whitespace-only id and status
|
||||
// Blank / whitespace-only (ASCII and ECMAScript Unicode) id and status
|
||||
const unicodeBlanks = ['\u00A0', '\u00A0\u2003\u3000\uFEFF', '\u2028\u2029'];
|
||||
await expectPgErrorCode(insertFinding(f.pool, { id: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { id: ' \t\n ' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { status: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { status: ' \t\r\n ' }), '23514');
|
||||
for (const blank of unicodeBlanks) {
|
||||
await expectPgErrorCode(insertFinding(f.pool, { id: blank }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { status: blank }), '23514');
|
||||
}
|
||||
|
||||
// Invalid kind
|
||||
await expectPgErrorCode(insertFinding(f.pool, { kind: 'hypothesis' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { kind: 'FINDING' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { kind: '' }), '23514');
|
||||
|
||||
// Blank, whitespace-only, or oversized title / summary
|
||||
// Blank, whitespace-only (ASCII and ECMAScript Unicode), or oversized title / summary
|
||||
await expectPgErrorCode(insertFinding(f.pool, { title: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { title: ' \t\n\r ' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { title: 't'.repeat(257) }), '23514');
|
||||
await expectPgErrorCode(
|
||||
insertFinding(f.pool, { title: `\u00A0${'t'.repeat(257)}\u00A0` }),
|
||||
'23514'
|
||||
);
|
||||
await expectPgErrorCode(insertFinding(f.pool, { summary: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { summary: ' \t\n\r ' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { summary: 's'.repeat(4097) }), '23514');
|
||||
for (const blank of unicodeBlanks) {
|
||||
await expectPgErrorCode(insertFinding(f.pool, { title: blank }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { summary: blank }), '23514');
|
||||
}
|
||||
|
||||
// Cardinality > 32
|
||||
const refs33 = Array.from({ length: 33 }, (_, i) => `ref-${i}`);
|
||||
|
|
@ -401,6 +425,9 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => {
|
|||
// Invalid idempotency_key (empty, whitespace-only, > 128 chars)
|
||||
await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: '' }), '23514');
|
||||
await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: ' \t\n ' }), '23514');
|
||||
for (const blank of unicodeBlanks) {
|
||||
await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: blank }), '23514');
|
||||
}
|
||||
await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: 'k'.repeat(129) }), '23514');
|
||||
|
||||
expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0);
|
||||
|
|
@ -445,7 +472,14 @@ describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => {
|
|||
const defaulted = (await insertProviderCaveat(f.pool, { id: 'caveat-002' })).rows[0];
|
||||
expect(defaulted.created_at).toBeInstanceOf(Date);
|
||||
|
||||
for (const blank of ['', ' ', '\t\n\r']) {
|
||||
for (const blank of [
|
||||
'',
|
||||
' ',
|
||||
'\t\n\r',
|
||||
'\u00A0',
|
||||
'\u00A0\u2003\u3000\uFEFF',
|
||||
'\u2028\u2029',
|
||||
]) {
|
||||
await expectPgErrorCode(insertProviderCaveat(f.pool, { id: blank }), '23514');
|
||||
await expectPgErrorCode(insertProviderCaveat(f.pool, { provider: blank }), '23514');
|
||||
await expectPgErrorCode(insertProviderCaveat(f.pool, { dataset: blank }), '23514');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue