or3-provider-sqlite 0.0.24 → 0.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +27 -3
  2. package/dist/module.json +1 -1
  3. package/dist/runtime/server/background-jobs/sqlite-provider.d.ts +37 -2
  4. package/dist/runtime/server/background-jobs/sqlite-provider.js +848 -30
  5. package/dist/runtime/server/db/kysely.d.ts +1 -0
  6. package/dist/runtime/server/db/kysely.js +3 -0
  7. package/dist/runtime/server/db/migrate.js +12 -2
  8. package/dist/runtime/server/db/migration-schema.d.ts +3 -0
  9. package/dist/runtime/server/db/migration-schema.js +21 -0
  10. package/dist/runtime/server/db/migrations/029_delegation_wait.d.ts +4 -0
  11. package/dist/runtime/server/db/migrations/029_delegation_wait.js +89 -0
  12. package/dist/runtime/server/db/migrations/030_storage_generations.d.ts +4 -0
  13. package/dist/runtime/server/db/migrations/030_storage_generations.js +42 -0
  14. package/dist/runtime/server/db/migrations/031_storage_generation_uploads.d.ts +4 -0
  15. package/dist/runtime/server/db/migrations/031_storage_generation_uploads.js +56 -0
  16. package/dist/runtime/server/db/schema.d.ts +8 -0
  17. package/dist/runtime/server/db/storage-generation-guards.d.ts +17 -0
  18. package/dist/runtime/server/db/storage-generation-guards.js +169 -0
  19. package/dist/runtime/server/db/storage-generation-upload-guards.d.ts +7 -0
  20. package/dist/runtime/server/db/storage-generation-upload-guards.js +182 -0
  21. package/dist/runtime/server/storage/sqlite-generation-coordinator.d.ts +62 -0
  22. package/dist/runtime/server/storage/sqlite-generation-coordinator.js +223 -0
  23. package/dist/runtime/server/storage/sqlite-generation-upload-coordinator.d.ts +60 -0
  24. package/dist/runtime/server/storage/sqlite-generation-upload-coordinator.js +435 -0
  25. package/dist/runtime/server/sync/background-history-fingerprint.d.ts +6 -0
  26. package/dist/runtime/server/sync/background-history-fingerprint.js +14 -0
  27. package/dist/runtime/server/sync/canonical-project-ownership.d.ts +6 -0
  28. package/dist/runtime/server/sync/canonical-project-ownership.js +20 -0
  29. package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +17 -0
  30. package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +145 -34
  31. package/package.json +13 -7
@@ -22,6 +22,7 @@ type SqliteTransaction<T> = ((...args: unknown[]) => T) & {
22
22
  immediate: (...args: unknown[]) => T;
23
23
  };
24
24
  export interface SqliteRawDatabase {
25
+ readonly inTransaction?: boolean;
25
26
  close(): void;
26
27
  prepare(sql: string): SqliteRawStatement;
27
28
  pragma?(source: string): unknown;
@@ -105,6 +105,9 @@ class BunDatabaseAdapter {
105
105
  constructor(database) {
106
106
  this.database = database;
107
107
  }
108
+ get inTransaction() {
109
+ return this.database.inTransaction;
110
+ }
108
111
  close() {
109
112
  this.database.close();
110
113
  }
@@ -51,14 +51,21 @@ const REQUIRED_SCHEMA_TABLES = [
51
51
  "connect_environments",
52
52
  "rate_limits",
53
53
  "background_jobs",
54
+ "background_job_execution_quarantine",
54
55
  "background_admission_cancels",
55
- "background_generation_receipts"
56
+ "background_generation_receipts",
57
+ "storage_object_generations",
58
+ "storage_object_heads",
59
+ "storage_generation_uploads"
56
60
  ];
57
61
  import * as m024 from "./migrations/024_signup_invites.js";
58
62
  import * as m025 from "./migrations/025_background_shutdown_accounting.js";
59
63
  import * as m026 from "./migrations/026_retained_storage_usage.js";
60
64
  import * as m027 from "./migrations/027_verified_storage_usage.js";
61
65
  import * as m028 from "./migrations/028_user_scoped_device_cursors.js";
66
+ import * as m029 from "./migrations/029_delegation_wait.js";
67
+ import * as m030 from "./migrations/030_storage_generations.js";
68
+ import * as m031 from "./migrations/031_storage_generation_uploads.js";
62
69
  const migrations = {
63
70
  "001_init": m001,
64
71
  "002_sync_tables": m002,
@@ -87,7 +94,10 @@ const migrations = {
87
94
  "025_background_shutdown_accounting": m025,
88
95
  "026_retained_storage_usage": m026,
89
96
  "027_verified_storage_usage": m027,
90
- "028_user_scoped_device_cursors": m028
97
+ "028_user_scoped_device_cursors": m028,
98
+ "029_delegation_wait": m029,
99
+ "030_storage_generations": m030,
100
+ "031_storage_generation_uploads": m031
91
101
  };
92
102
  class StaticMigrationProvider {
93
103
  async getMigrations() {
@@ -0,0 +1,3 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Resume nontransactional SQLite/D1 DDL without trusting an unrelated schema. */
3
+ export declare function ensureMigrationSchema(db: Kysely<unknown>, statement: string, previousTrigger?: string): Promise<void>;
@@ -0,0 +1,21 @@
1
+ import { sql } from "kysely";
2
+ export async function ensureMigrationSchema(db, statement, previousTrigger) {
3
+ const match = /^CREATE (?:UNIQUE )?(TABLE|INDEX|TRIGGER) (\w+)/.exec(statement);
4
+ if (!match) throw new Error("Unsupported migration schema statement");
5
+ const [, kind, name] = match;
6
+ const existing = (await sql`
7
+ SELECT type, sql FROM sqlite_master WHERE name = ${name}
8
+ `.execute(db)).rows;
9
+ if (existing.length) {
10
+ const current = existing[0];
11
+ if (existing.length !== 1 || !current || current.type !== kind?.toLowerCase()) {
12
+ throw new Error(`Incompatible migration schema: ${name}`);
13
+ }
14
+ if (current.sql?.trim() === statement.trim()) return;
15
+ if (kind !== "TRIGGER" || !previousTrigger || current.sql?.trim() !== previousTrigger.trim()) {
16
+ throw new Error(`Incompatible migration schema: ${name}`);
17
+ }
18
+ await sql.raw(`DROP TRIGGER ${name}`).execute(db);
19
+ }
20
+ await sql.raw(statement).execute(db);
21
+ }
@@ -0,0 +1,4 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Find due parked parents without scanning unrelated response bodies. */
3
+ export declare function up(db: Kysely<unknown>): Promise<void>;
4
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -0,0 +1,89 @@
1
+ import { sql } from "kysely";
2
+ export async function up(db) {
3
+ const columns = new Set((await sql`PRAGMA table_info(background_jobs)`.execute(db)).rows.map((row) => row.name));
4
+ if (!columns.has("delegation_admission_digest")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_admission_digest TEXT`.execute(db);
5
+ if (!columns.has("delegation_parent_id")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_parent_id TEXT`.execute(db);
6
+ if (!columns.has("delegation_history_retry_at")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_history_retry_at INTEGER NOT NULL DEFAULT 0`.execute(db);
7
+ if (!columns.has("delegation_wait_active")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_wait_active INTEGER NOT NULL DEFAULT 0 CHECK (delegation_wait_active IN (0, 1))`.execute(db);
8
+ if (!columns.has("delegation_wait_deadline")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_wait_deadline INTEGER`.execute(db);
9
+ await sql`CREATE TABLE IF NOT EXISTS background_job_execution_quarantine (
10
+ job_id TEXT PRIMARY KEY REFERENCES background_jobs(id) ON DELETE RESTRICT,
11
+ execution_json TEXT NOT NULL,
12
+ lease_owner TEXT,
13
+ lease_expires_at INTEGER
14
+ )`.execute(db);
15
+ await sql`INSERT INTO background_job_execution_quarantine (job_id, execution_json, lease_owner, lease_expires_at)
16
+ SELECT id, execution_json, lease_owner, lease_expires_at FROM background_jobs
17
+ WHERE execution_json IS NOT NULL AND json_valid(execution_json) = 0
18
+ ON CONFLICT(job_id) DO NOTHING`.execute(db);
19
+ const conflict = await sql`SELECT evidence.job_id FROM background_job_execution_quarantine AS evidence
20
+ JOIN background_jobs AS job ON job.id = evidence.job_id
21
+ WHERE job.execution_json IS NOT NULL AND json_valid(job.execution_json) = 0
22
+ AND job.execution_json IS NOT evidence.execution_json LIMIT 1`.execute(db);
23
+ if (conflict.rows.length) throw new Error("Conflicting quarantined background job execution evidence");
24
+ await sql`UPDATE background_jobs SET execution_json = '{"version":1,"delegationQuarantinedAt":0}',
25
+ delegation_wait_active = 1, delegation_wait_deadline = NULL, lease_owner = NULL, lease_expires_at = NULL
26
+ WHERE id IN (SELECT job_id FROM background_job_execution_quarantine)`.execute(db);
27
+ await sql`UPDATE background_jobs SET delegation_wait_active = 1, delegation_wait_deadline =
28
+ CASE WHEN json_type(execution_json, '$.delegationWait.deadlineAt') = 'integer'
29
+ THEN json_extract(execution_json, '$.delegationWait.deadlineAt') ELSE NULL END
30
+ WHERE json_type(execution_json, '$.delegationWait') IS NOT NULL`.execute(db);
31
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_deadline ON background_jobs(delegation_wait_deadline, started_at, id)
32
+ WHERE delegation_wait_active = 1 AND status = 'streaming'
33
+ AND (json_type(execution_json, '$.delegationWait') IS NOT 'object' OR
34
+ (json_extract(execution_json, '$.delegationWait.version') = 1 AND
35
+ (json_type(execution_json, '$.delegationQuarantinedAt') IS NOT NULL OR
36
+ json_extract(execution_json, '$.delegationWait.deadlineAt') IS NOT delegation_wait_deadline)))`.execute(db);
37
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_terminal_damage ON background_jobs(started_at, id)
38
+ WHERE delegation_wait_active = 1 AND status != 'streaming'
39
+ AND (json_type(execution_json, '$.delegationWait') IS NOT 'object' OR
40
+ (json_extract(execution_json, '$.delegationWait.version') = 1 AND
41
+ (json_type(execution_json, '$.delegationQuarantinedAt') IS NOT NULL OR
42
+ json_extract(execution_json, '$.delegationWait.deadlineAt') IS NOT delegation_wait_deadline)))`.execute(db);
43
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_missing_wait ON background_jobs(started_at, id)
44
+ WHERE delegation_wait_active = 1 AND json_type(execution_json, '$.delegationWait') IS NULL`.execute(db);
45
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_parent ON background_jobs(delegation_parent_id, id)
46
+ WHERE delegation_parent_id IS NOT NULL`.execute(db);
47
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_due
48
+ ON background_jobs(json_extract(execution_json, '$.delegationWait.nextCheckAt'), started_at, id)
49
+ WHERE json_type(execution_json, '$.delegationWait') IS NOT NULL`.execute(db);
50
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_invalid_due ON background_jobs(started_at, id)
51
+ WHERE json_extract(execution_json, '$.version') = 1
52
+ AND json_type(execution_json, '$.delegationWait') IS NOT NULL
53
+ AND json_extract(execution_json, '$.delegationWait.version') = 1
54
+ AND json_type(execution_json, '$.delegationQuarantinedAt') IS NULL
55
+ AND (COALESCE(json_type(execution_json, '$.delegationWait.nextCheckAt'), 'missing') NOT IN ('integer', 'real')
56
+ OR json_extract(execution_json, '$.delegationWait.nextCheckAt') < 0
57
+ OR json_extract(execution_json, '$.delegationWait.nextCheckAt') > 9007199254740991
58
+ OR json_extract(execution_json, '$.delegationWait.nextCheckAt') != CAST(json_extract(execution_json, '$.delegationWait.nextCheckAt') AS INTEGER))`.execute(db);
59
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_unsupported ON background_jobs(started_at, id)
60
+ WHERE json_type(execution_json, '$.delegationWait') IS NOT NULL
61
+ AND (json_extract(execution_json, '$.version') IS NOT 1
62
+ OR json_extract(execution_json, '$.delegationWait.version') IS NOT 1)`.execute(db);
63
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_quarantined ON background_jobs(started_at, id)
64
+ WHERE json_type(execution_json, '$.delegationQuarantinedAt') IS NOT NULL`.execute(db);
65
+ await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_history_due
66
+ ON background_jobs(history_phase, delegation_history_retry_at, started_at, id)
67
+ WHERE history_phase IN ('admission_pending', 'finalization_pending')`.execute(db);
68
+ }
69
+ export async function down(db) {
70
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_deadline`.execute(db);
71
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_terminal_damage`.execute(db);
72
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_missing_wait`.execute(db);
73
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_history_due`.execute(db);
74
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_quarantined`.execute(db);
75
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_unsupported`.execute(db);
76
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_invalid_due`.execute(db);
77
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_due`.execute(db);
78
+ await sql`DROP INDEX IF EXISTS background_jobs_delegation_parent`.execute(db);
79
+ await sql`UPDATE background_jobs SET execution_json = (
80
+ SELECT execution_json FROM background_job_execution_quarantine AS evidence
81
+ WHERE evidence.job_id = background_jobs.id)
82
+ WHERE id IN (SELECT job_id FROM background_job_execution_quarantine)`.execute(db);
83
+ await sql`DROP TABLE background_job_execution_quarantine`.execute(db);
84
+ await sql`ALTER TABLE background_jobs DROP COLUMN delegation_wait_deadline`.execute(db);
85
+ await sql`ALTER TABLE background_jobs DROP COLUMN delegation_wait_active`.execute(db);
86
+ await sql`ALTER TABLE background_jobs DROP COLUMN delegation_parent_id`.execute(db);
87
+ await sql`ALTER TABLE background_jobs DROP COLUMN delegation_history_retry_at`.execute(db);
88
+ await sql`ALTER TABLE background_jobs DROP COLUMN delegation_admission_digest`.execute(db);
89
+ }
@@ -0,0 +1,4 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Dormant foundation: no runtime creates managed rows or advertises this protocol. */
3
+ export declare function up(db: Kysely<unknown>): Promise<void>;
4
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -0,0 +1,42 @@
1
+ import { sql } from "kysely";
2
+ import { ensureMigrationSchema } from "../migration-schema.js";
3
+ import { GENERATION_TABLE, HEAD_TABLE, generationGuardTriggers } from "../storage-generation-guards.js";
4
+ export async function up(db) {
5
+ await ensureMigrationSchema(db, `CREATE TABLE ${GENERATION_TABLE} (
6
+ generation_id TEXT PRIMARY KEY,
7
+ workspace_id TEXT NOT NULL,
8
+ hash TEXT NOT NULL,
9
+ storage_provider_id TEXT NOT NULL,
10
+ storage_id TEXT NOT NULL UNIQUE,
11
+ size_bytes INTEGER NOT NULL CHECK (typeof(size_bytes) = 'integer' AND size_bytes BETWEEN 0 AND 9007199254740991),
12
+ state TEXT NOT NULL CHECK (state IN ('verified', 'claimed', 'deleted')),
13
+ created_at INTEGER NOT NULL CHECK (typeof(created_at) = 'integer' AND created_at BETWEEN 0 AND 9007199254740991),
14
+ last_activity_at INTEGER NOT NULL CHECK (typeof(last_activity_at) = 'integer' AND last_activity_at BETWEEN 0 AND 9007199254740991),
15
+ claim_id TEXT UNIQUE,
16
+ claimed_at INTEGER CHECK (claimed_at IS NULL OR (typeof(claimed_at) = 'integer' AND claimed_at BETWEEN 0 AND 9007199254740991)),
17
+ deleted_at INTEGER CHECK (deleted_at IS NULL OR (typeof(deleted_at) = 'integer' AND deleted_at BETWEEN 0 AND 9007199254740991)),
18
+ UNIQUE (workspace_id, hash, generation_id),
19
+ CHECK (last_activity_at >= created_at),
20
+ CHECK ((state = 'verified' AND claim_id IS NULL AND claimed_at IS NULL AND deleted_at IS NULL)
21
+ OR (state = 'claimed' AND claim_id IS NOT NULL AND claimed_at IS NOT NULL AND claimed_at >= last_activity_at AND deleted_at IS NULL)
22
+ OR (state = 'deleted' AND claim_id IS NOT NULL AND claimed_at IS NOT NULL AND deleted_at IS NOT NULL
23
+ AND claimed_at >= last_activity_at AND deleted_at >= claimed_at))
24
+ )`);
25
+ await ensureMigrationSchema(db, `CREATE TABLE ${HEAD_TABLE} (
26
+ workspace_id TEXT NOT NULL,
27
+ hash TEXT NOT NULL,
28
+ generation_id TEXT NOT NULL UNIQUE,
29
+ PRIMARY KEY (workspace_id, hash),
30
+ FOREIGN KEY (workspace_id, hash, generation_id)
31
+ REFERENCES ${GENERATION_TABLE}(workspace_id, hash, generation_id) ON DELETE RESTRICT
32
+ )`);
33
+ await ensureMigrationSchema(db, `CREATE INDEX storage_generations_workspace_hash ON ${GENERATION_TABLE}(workspace_id, hash)`);
34
+ for (const trigger of Object.values(generationGuardTriggers())) await ensureMigrationSchema(db, trigger);
35
+ }
36
+ export async function down(db) {
37
+ const result = await sql`SELECT count(*) AS count FROM storage_object_generations`.execute(db);
38
+ if (result.rows[0]?.count) throw new Error("Managed generation barriers are permanent; cannot roll back this schema.");
39
+ for (const name of Object.keys(generationGuardTriggers())) await sql.raw(`DROP TRIGGER IF EXISTS ${name}`).execute(db);
40
+ await sql.raw(`DROP TABLE ${HEAD_TABLE}`).execute(db);
41
+ await sql.raw(`DROP TABLE ${GENERATION_TABLE}`).execute(db);
42
+ }
@@ -0,0 +1,4 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Dormant: no production route or factory registers upload enrollment. */
3
+ export declare function up(db: Kysely<unknown>): Promise<void>;
4
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { sql } from "kysely";
2
+ import { ensureMigrationSchema } from "../migration-schema.js";
3
+ import { generationGuardTriggers } from "../storage-generation-guards.js";
4
+ import { GENERATION_UPLOAD_TABLE, generationUploadGuardTriggers } from "../storage-generation-upload-guards.js";
5
+ export async function up(db) {
6
+ await ensureMigrationSchema(db, `CREATE TABLE ${GENERATION_UPLOAD_TABLE} (
7
+ intent_id TEXT PRIMARY KEY,
8
+ workspace_id TEXT NOT NULL, hash TEXT NOT NULL,
9
+ generation_id TEXT NOT NULL, storage_id TEXT NOT NULL,
10
+ purpose TEXT NOT NULL DEFAULT 'upload' CHECK (purpose IN ('upload','restore')),
11
+ storage_provider_id TEXT NOT NULL, namespace_id TEXT NOT NULL, user_id TEXT NOT NULL,
12
+ mime_type TEXT NOT NULL,
13
+ size_bytes INTEGER NOT NULL CHECK (typeof(size_bytes) = 'integer' AND size_bytes BETWEEN 0 AND 9007199254740991),
14
+ reserved_bytes INTEGER NOT NULL CHECK (typeof(reserved_bytes) = 'integer' AND reserved_bytes >= 0),
15
+ created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,
16
+ request_ttl INTEGER NOT NULL, quota_bytes INTEGER,
17
+ state TEXT NOT NULL CHECK (state IN ('reserved','ready','published_pending_metadata','materialized','abandon_claimed','abandoned')),
18
+ ready_receipt_id TEXT, ready_at INTEGER,
19
+ published_generation_id TEXT, published_at INTEGER, materialized_at INTEGER,
20
+ claim_id TEXT UNIQUE, claimed_at INTEGER, deleted_at INTEGER,
21
+ CHECK (typeof(created_at) = 'integer' AND created_at >= 0 AND typeof(expires_at) = 'integer' AND expires_at > created_at),
22
+ CHECK ((state IN ('reserved','ready','published_pending_metadata') AND reserved_bytes = size_bytes)
23
+ OR (state IN ('materialized','abandon_claimed','abandoned') AND reserved_bytes = 0)),
24
+ CHECK ((state = 'reserved' AND ready_receipt_id IS NULL AND ready_at IS NULL)
25
+ OR (state <> 'reserved' AND ready_receipt_id IS NOT NULL AND ready_at IS NOT NULL AND ready_at >= created_at)),
26
+ CHECK ((published_generation_id IS NULL AND published_at IS NULL)
27
+ OR (published_generation_id = generation_id AND published_at IS NOT NULL AND published_at >= ready_at)),
28
+ CHECK (state NOT IN ('published_pending_metadata','materialized') OR published_generation_id IS NOT NULL),
29
+ CHECK (purpose = 'upload' OR (published_generation_id IS NOT NULL AND state NOT IN ('reserved','ready'))),
30
+ CHECK ((state = 'materialized' AND materialized_at IS NOT NULL AND materialized_at >= published_at)
31
+ OR (state <> 'materialized' AND materialized_at IS NULL)),
32
+ CHECK ((state IN ('abandon_claimed','abandoned') AND claim_id IS NOT NULL AND claimed_at IS NOT NULL AND claimed_at >= expires_at AND claimed_at >= ready_at)
33
+ OR (state NOT IN ('abandon_claimed','abandoned') AND claim_id IS NULL AND claimed_at IS NULL)),
34
+ CHECK ((state = 'abandoned' AND deleted_at IS NOT NULL AND deleted_at >= claimed_at)
35
+ OR (state <> 'abandoned' AND deleted_at IS NULL)),
36
+ FOREIGN KEY (intent_id) REFERENCES upload_intents(id) DEFERRABLE INITIALLY DEFERRED,
37
+ FOREIGN KEY (published_generation_id) REFERENCES storage_object_generations(generation_id) DEFERRABLE INITIALLY DEFERRED
38
+ )`);
39
+ await ensureMigrationSchema(db, `CREATE UNIQUE INDEX storage_upload_generation_identity ON ${GENERATION_UPLOAD_TABLE}(generation_id) WHERE purpose = 'upload'`);
40
+ await ensureMigrationSchema(db, `CREATE UNIQUE INDEX storage_upload_target_identity ON ${GENERATION_UPLOAD_TABLE}(storage_id) WHERE purpose = 'upload'`);
41
+ await ensureMigrationSchema(db, `CREATE UNIQUE INDEX storage_upload_pending_hash ON ${GENERATION_UPLOAD_TABLE}(workspace_id, hash)
42
+ WHERE state IN ('reserved','ready','published_pending_metadata')`);
43
+ await ensureMigrationSchema(db, `CREATE INDEX storage_upload_recovery ON ${GENERATION_UPLOAD_TABLE}(workspace_id, intent_id)`);
44
+ for (const [name, trigger] of Object.entries(generationUploadGuardTriggers())) {
45
+ await ensureMigrationSchema(db, trigger, generationGuardTriggers()[name]);
46
+ }
47
+ }
48
+ export async function down(db) {
49
+ const result = await sql`SELECT count(*) AS count FROM storage_generation_uploads`.execute(db);
50
+ if (result.rows[0]?.count) throw new Error("Managed upload bindings are permanent; cannot roll back this schema.");
51
+ for (const name of Object.keys(generationUploadGuardTriggers())) await sql.raw(`DROP TRIGGER IF EXISTS ${name}`).execute(db);
52
+ await sql.raw(`DROP TABLE ${GENERATION_UPLOAD_TABLE}`).execute(db);
53
+ for (const [name, trigger] of Object.entries(generationGuardTriggers())) {
54
+ if (name in generationUploadGuardTriggers()) await sql.raw(trigger).execute(db);
55
+ }
56
+ }
@@ -230,6 +230,8 @@ export interface BackgroundJobsTable {
230
230
  lease_owner: string | null;
231
231
  lease_expires_at: number | null;
232
232
  attempts: number;
233
+ delegation_wait_active: number;
234
+ delegation_wait_deadline: number | null;
233
235
  }
234
236
  export interface BackgroundGenerationReceiptsTable {
235
237
  id: string;
@@ -271,6 +273,12 @@ export interface Or3SqliteDb {
271
273
  connect_environments: ConnectEnvironmentsTable;
272
274
  rate_limits: RateLimitsTable;
273
275
  background_jobs: BackgroundJobsTable;
276
+ background_job_execution_quarantine: {
277
+ job_id: string;
278
+ execution_json: string;
279
+ lease_owner: string | null;
280
+ lease_expires_at: number | null;
281
+ };
274
282
  background_generation_receipts: BackgroundGenerationReceiptsTable;
275
283
  s_threads: SyncedEntityTable;
276
284
  s_messages: SyncedEntityTable;
@@ -0,0 +1,17 @@
1
+ /** Dormant managed-generation barriers. All identifiers below are internal constants. */
2
+ export declare const GENERATION_TABLE = "storage_object_generations";
3
+ export declare const HEAD_TABLE = "storage_object_heads";
4
+ export declare const MAX_GENERATION_PAYLOAD_BYTES: number;
5
+ export declare const MAX_GENERATION_ROW_EDGES = 1000;
6
+ export declare const GENERATION_PROOF_ROWS = 1000;
7
+ export declare const GENERATION_PROOF_EDGES = 10000;
8
+ /** Do not trim: whitespace and unknown prefixes are invalid, never invisible aliases. */
9
+ export declare function generationHashSql(value: string): string;
10
+ export declare function validGenerationHashSql(value: string): string;
11
+ /** JSON path labels containing NUL can shadow exact keys in SQLite. */
12
+ export declare function validGenerationObjectSql(json: string): string;
13
+ export declare function generationReferencesSql(json: string): string;
14
+ export declare function validGenerationReferencesSql(json: string): string;
15
+ /** Exact SQL is also checked inside every coordinator mutation transaction. */
16
+ export declare function generationGuardTriggers(): Record<string, string>;
17
+ export declare function canonicalGuardSql(sql: string): string;
@@ -0,0 +1,169 @@
1
+ export const GENERATION_TABLE = "storage_object_generations";
2
+ export const HEAD_TABLE = "storage_object_heads";
3
+ export const MAX_GENERATION_PAYLOAD_BYTES = 256 * 1024;
4
+ export const MAX_GENERATION_ROW_EDGES = 1e3;
5
+ export const GENERATION_PROOF_ROWS = 1e3;
6
+ export const GENERATION_PROOF_EDGES = 1e4;
7
+ export function generationHashSql(value) {
8
+ return `(CASE WHEN lower(substr(${value}, 1, 7)) = 'sha256:' THEN lower(substr(${value}, 8))
9
+ WHEN lower(substr(${value}, 1, 4)) = 'md5:' THEN lower(substr(${value}, 5)) ELSE lower(${value}) END)`;
10
+ }
11
+ export function validGenerationHashSql(value) {
12
+ const hash = generationHashSql(value);
13
+ return `(typeof(${value}) = 'text' AND length(CAST(${value} AS BLOB)) = length(${value})
14
+ AND ${hash} NOT GLOB '*[^0-9a-f]*'
15
+ AND ((length(${value}) IN (32, 64) AND length(${hash}) = length(${value}))
16
+ OR (length(${value}) = 71 AND lower(substr(${value}, 1, 7)) = 'sha256:' AND length(${hash}) = 64)
17
+ OR (length(${value}) = 36 AND lower(substr(${value}, 1, 4)) = 'md5:' AND length(${hash}) = 32)))`;
18
+ }
19
+ export function validGenerationObjectSql(json) {
20
+ return `(CASE WHEN typeof(${json}) <> 'text' OR length(CAST(${json} AS BLOB)) > ${MAX_GENERATION_PAYLOAD_BYTES}
21
+ OR json_valid(${json}) IS NOT 1 THEN 0
22
+ WHEN json_type(${json}) <> 'object' THEN 0
23
+ WHEN EXISTS (SELECT 1 FROM json_each(${json}) WHERE instr(key, char(0)) > 0) THEN 0
24
+ WHEN EXISTS (SELECT 1 FROM json_each(${json}) GROUP BY key HAVING count(*) > 1) THEN 0
25
+ ELSE 1 END)`;
26
+ }
27
+ export function generationReferencesSql(json) {
28
+ return `(CASE WHEN json_type(${json}, '$.file_hashes') IS NULL OR json_type(${json}, '$.file_hashes') = 'null' THEN '[]'
29
+ ELSE json_extract(${json}, '$.file_hashes') END)`;
30
+ }
31
+ export function validGenerationReferencesSql(json) {
32
+ const refs = generationReferencesSql(json);
33
+ return `(CASE WHEN ${validGenerationObjectSql(json)} = 0 THEN 0
34
+ WHEN json_type(${json}, '$.fileHashes') IS NOT NULL THEN 0
35
+ WHEN json_type(${json}, '$.file_hashes') IS NULL OR json_type(${json}, '$.file_hashes') = 'null' THEN 1
36
+ WHEN json_type(${json}, '$.file_hashes') NOT IN ('text', 'array') THEN 0
37
+ WHEN json_valid(${refs}) IS NOT 1 THEN 0
38
+ WHEN json_type(${refs}) <> 'array' OR json_array_length(${refs}) > ${MAX_GENERATION_ROW_EDGES} THEN 0
39
+ WHEN EXISTS (SELECT 1 FROM json_each(${refs}) WHERE type <> 'text' OR NOT ${validGenerationHashSql("value")}) THEN 0
40
+ ELSE 1 END)`;
41
+ }
42
+ function safeReferencesSql(json) {
43
+ return `(CASE WHEN ${validGenerationReferencesSql(json)} = 1 THEN ${generationReferencesSql(json)} ELSE '[]' END)`;
44
+ }
45
+ function metadataStorageSql(json) {
46
+ return `coalesce(json_extract(${json}, '$.storage_id'), json_extract(${json}, '$.storageId'))`;
47
+ }
48
+ function sourceTouch(table, row, prior = false) {
49
+ const match = `${row}.deleted = 0 AND ${row}.workspace_id = ${GENERATION_TABLE}.workspace_id
50
+ AND (${validGenerationReferencesSql(`${row}.data_json`)} = 0
51
+ OR ${GENERATION_TABLE}.hash IN (SELECT ${generationHashSql("value")} FROM json_each(${safeReferencesSql(`${row}.data_json`)})))`;
52
+ return `UPDATE ${GENERATION_TABLE} SET last_activity_at = max(last_activity_at, unixepoch())
53
+ WHERE state = 'verified' AND generation_id IN (SELECT generation_id FROM ${HEAD_TABLE})
54
+ AND ${prior ? `EXISTS (SELECT 1 FROM ${table} prior WHERE ${table === "upload_intents" ? "" : "prior.workspace_id = NEW.workspace_id AND "}prior.id = NEW.id AND ${match})` : `(${match})`};`;
55
+ }
56
+ function keyTouch(table, row, prior = false) {
57
+ const column = table === "s_file_meta" ? "id" : "hash";
58
+ const match = `${row}.workspace_id = ${GENERATION_TABLE}.workspace_id
59
+ AND ${generationHashSql(`${row}.${column}`)} = ${GENERATION_TABLE}.hash
60
+ ${table === "upload_intents" ? `AND ${row}.status = 'active'` : ""}`;
61
+ return `UPDATE ${GENERATION_TABLE} SET last_activity_at = max(last_activity_at, unixepoch())
62
+ WHERE state = 'verified' AND generation_id IN (SELECT generation_id FROM ${HEAD_TABLE})
63
+ AND ${prior ? `EXISTS (SELECT 1 FROM ${table} prior WHERE ${table === "upload_intents" ? "" : "prior.workspace_id = NEW.workspace_id AND "}prior.id = NEW.id AND ${match})` : `(${match})`};`;
64
+ }
65
+ export function generationGuardTriggers() {
66
+ const triggers = {};
67
+ const add = (name, clause) => {
68
+ triggers[name] = `CREATE TRIGGER ${name} ${clause}`;
69
+ };
70
+ add("storage_generation_no_replace", `BEFORE INSERT ON ${GENERATION_TABLE}
71
+ WHEN EXISTS (SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = NEW.generation_id OR storage_id = NEW.storage_id)
72
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_IDENTITY_REUSE'); END`);
73
+ add("storage_generation_no_delete", `BEFORE DELETE ON ${GENERATION_TABLE}
74
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_PERMANENT'); END`);
75
+ add("storage_generation_immutable", `BEFORE UPDATE ON ${GENERATION_TABLE}
76
+ WHEN NEW.generation_id IS NOT OLD.generation_id OR NEW.workspace_id IS NOT OLD.workspace_id
77
+ OR NEW.hash IS NOT OLD.hash OR NEW.storage_id IS NOT OLD.storage_id
78
+ OR NEW.storage_provider_id IS NOT OLD.storage_provider_id OR NEW.size_bytes IS NOT OLD.size_bytes
79
+ OR NEW.created_at IS NOT OLD.created_at OR NEW.last_activity_at < OLD.last_activity_at
80
+ OR (OLD.state = 'verified' AND NEW.state = 'deleted')
81
+ OR (OLD.state <> 'verified' AND NEW.last_activity_at IS NOT OLD.last_activity_at)
82
+ OR (OLD.state <> 'verified' AND (NEW.claim_id IS NOT OLD.claim_id OR NEW.claimed_at IS NOT OLD.claimed_at))
83
+ OR (OLD.state = 'claimed' AND NEW.state NOT IN ('claimed', 'deleted'))
84
+ OR (OLD.state = 'deleted' AND (NEW.state <> 'deleted' OR NEW.deleted_at IS NOT OLD.deleted_at))
85
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_IMMUTABLE'); END`);
86
+ add("storage_generation_head_insert", `BEFORE INSERT ON ${HEAD_TABLE}
87
+ WHEN EXISTS (SELECT 1 FROM ${HEAD_TABLE} WHERE workspace_id = NEW.workspace_id AND hash = NEW.hash)
88
+ OR NOT EXISTS (SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = NEW.generation_id
89
+ AND workspace_id = NEW.workspace_id AND hash = NEW.hash AND state = 'verified')
90
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_HEAD_CONFLICT'); END`);
91
+ add("storage_generation_head_update", `BEFORE UPDATE ON ${HEAD_TABLE}
92
+ WHEN NEW.workspace_id IS NOT OLD.workspace_id OR NEW.hash IS NOT OLD.hash
93
+ OR NOT EXISTS (SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = OLD.generation_id AND state IN ('claimed', 'deleted'))
94
+ OR NOT EXISTS (SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = NEW.generation_id
95
+ AND workspace_id = NEW.workspace_id AND hash = NEW.hash AND state = 'verified')
96
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_HEAD_CONFLICT'); END`);
97
+ add("storage_generation_head_no_delete", `BEFORE DELETE ON ${HEAD_TABLE}
98
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_HEAD_PERMANENT'); END`);
99
+ for (const table of ["s_messages", "s_posts"]) {
100
+ for (const event of ["INSERT", "UPDATE"]) {
101
+ add(`${table}_generation_guard_${event.toLowerCase()}`, `BEFORE ${event} ON ${table}
102
+ WHEN NEW.deleted = 0 AND EXISTS (SELECT 1 FROM ${HEAD_TABLE} WHERE workspace_id = NEW.workspace_id)
103
+ BEGIN
104
+ SELECT CASE WHEN ${validGenerationReferencesSql("NEW.data_json")} = 0
105
+ THEN RAISE(ABORT, 'STORAGE_GENERATION_UNKNOWN_REFERENCES') END;
106
+ SELECT CASE WHEN EXISTS (
107
+ SELECT 1 FROM json_each(${generationReferencesSql("NEW.data_json")}) edge
108
+ JOIN ${HEAD_TABLE} head ON head.workspace_id = NEW.workspace_id AND head.hash = ${generationHashSql("edge.value")}
109
+ JOIN ${GENERATION_TABLE} generation ON generation.generation_id = head.generation_id
110
+ WHERE generation.state <> 'verified') THEN RAISE(ABORT, 'STORAGE_GENERATION_CLAIMED') END;
111
+ END`);
112
+ }
113
+ }
114
+ const knownMetadata = `EXISTS (SELECT 1 FROM ${HEAD_TABLE} WHERE workspace_id = NEW.workspace_id
115
+ AND (hash = ${generationHashSql("NEW.id")} OR ${validGenerationHashSql("NEW.id")} IS NOT 1
116
+ OR CASE WHEN ${validGenerationObjectSql("NEW.data_json")} = 0 THEN 1
117
+ WHEN json_type(NEW.data_json, '$.hash') IS NOT NULL THEN
118
+ ${validGenerationHashSql("json_extract(NEW.data_json, '$.hash')")} IS NOT 1
119
+ OR ${generationHashSql("json_extract(NEW.data_json, '$.hash')")} IS NOT ${generationHashSql("NEW.id")}
120
+ ELSE 0 END))
121
+ OR EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(NEW.data_json) THEN NEW.data_json ELSE '{}' END) field
122
+ JOIN ${GENERATION_TABLE} generation ON generation.storage_id = field.value
123
+ WHERE field.key IN ('storage_id', 'storageId') AND field.type = 'text')`;
124
+ for (const event of ["INSERT", "UPDATE"]) {
125
+ add(`s_file_meta_generation_guard_${event.toLowerCase()}`, `BEFORE ${event} ON s_file_meta
126
+ WHEN NEW.deleted = 0 AND (${knownMetadata})
127
+ BEGIN
128
+ SELECT CASE WHEN ${validGenerationObjectSql("NEW.data_json")} = 0
129
+ THEN RAISE(ABORT, 'STORAGE_GENERATION_INVALID_METADATA') END;
130
+ SELECT CASE WHEN (json_type(NEW.data_json, '$.storage_id') IS NOT NULL AND json_type(NEW.data_json, '$.storageId') IS NOT NULL)
131
+ OR (json_type(NEW.data_json, '$.size_bytes') IS NOT NULL AND json_type(NEW.data_json, '$.sizeBytes') IS NOT NULL)
132
+ THEN RAISE(ABORT, 'STORAGE_GENERATION_AMBIGUOUS_METADATA') END;
133
+ SELECT CASE WHEN NOT EXISTS (
134
+ SELECT 1 FROM ${HEAD_TABLE} head JOIN ${GENERATION_TABLE} generation ON generation.generation_id = head.generation_id
135
+ WHERE head.workspace_id = NEW.workspace_id AND head.hash = ${generationHashSql("NEW.id")}
136
+ AND generation.state = 'verified' AND ${validGenerationHashSql("NEW.id")}
137
+ AND ${validGenerationHashSql("json_extract(NEW.data_json, '$.hash')")}
138
+ AND ${generationHashSql("json_extract(NEW.data_json, '$.hash')")} = head.hash
139
+ AND typeof(${metadataStorageSql("NEW.data_json")}) = 'text'
140
+ AND ${metadataStorageSql("NEW.data_json")} = generation.storage_id
141
+ AND typeof(coalesce(json_extract(NEW.data_json, '$.size_bytes'), json_extract(NEW.data_json, '$.sizeBytes'))) = 'integer'
142
+ AND coalesce(json_extract(NEW.data_json, '$.size_bytes'), json_extract(NEW.data_json, '$.sizeBytes')) = generation.size_bytes
143
+ ) THEN RAISE(ABORT, 'STORAGE_GENERATION_METADATA_MISMATCH') END;
144
+ END`);
145
+ add(`upload_intents_generation_guard_${event.toLowerCase()}`, `BEFORE ${event} ON upload_intents
146
+ WHEN NEW.status = 'active' AND EXISTS (SELECT 1 FROM ${HEAD_TABLE} head
147
+ JOIN ${GENERATION_TABLE} generation ON generation.generation_id = head.generation_id
148
+ WHERE head.workspace_id = NEW.workspace_id AND (${validGenerationHashSql("NEW.hash")} IS NOT 1
149
+ OR (head.hash = ${generationHashSql("NEW.hash")} AND generation.state <> 'verified')))
150
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_UPLOAD_BLOCKED'); END`);
151
+ }
152
+ add("s_file_meta_generation_identity_update", `BEFORE UPDATE ON s_file_meta
153
+ WHEN (NEW.workspace_id IS NOT OLD.workspace_id OR NEW.id IS NOT OLD.id)
154
+ AND EXISTS (SELECT 1 FROM ${HEAD_TABLE} WHERE workspace_id = OLD.workspace_id AND hash = ${generationHashSql("OLD.id")})
155
+ BEGIN SELECT RAISE(ABORT, 'STORAGE_GENERATION_METADATA_IDENTITY'); END`);
156
+ for (const table of ["s_messages", "s_posts", "s_file_meta", "upload_intents"]) {
157
+ const touch = table === "s_messages" || table === "s_posts" ? sourceTouch : keyTouch;
158
+ add(`${table}_generation_replace_activity`, `BEFORE INSERT ON ${table} BEGIN ${touch(table, "prior", true)} END`);
159
+ for (const event of ["INSERT", "UPDATE", "DELETE"]) {
160
+ const rows = event === "UPDATE" ? ["OLD", "NEW"] : event === "DELETE" ? ["OLD"] : ["NEW"];
161
+ add(`${table}_generation_activity_${event.toLowerCase()}`, `AFTER ${event} ON ${table}
162
+ BEGIN ${rows.map((row) => touch(table, row)).join("\n")} END`);
163
+ }
164
+ }
165
+ return triggers;
166
+ }
167
+ export function canonicalGuardSql(sql) {
168
+ return sql.trim().replace(/;$/, "");
169
+ }
@@ -0,0 +1,7 @@
1
+ export declare const GENERATION_UPLOAD_TABLE = "storage_generation_uploads";
2
+ /** Accounting holds have no automatic expiry. Credentials have their own deadline. */
3
+ export declare const GENERATION_UPLOAD_HOLD_EXPIRY: number;
4
+ export declare const GENERATION_UPLOAD_MAX_TTL_SECONDS = 900;
5
+ export declare const GENERATION_UPLOAD_MAX_PENDING = 128;
6
+ /** Migration 025 only: the original migration remains reproducible. */
7
+ export declare function generationUploadGuardTriggers(): Record<string, string>;