@sixb/pg 0.1.25 → 0.2.0
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.
- package/README.md +25 -1
- package/dist/agents/agent-storage.d.ts +8 -3
- package/dist/agents/agent-storage.d.ts.map +1 -1
- package/dist/agents/computers.d.ts +22 -0
- package/dist/agents/computers.d.ts.map +1 -0
- package/dist/agents/messages.d.ts.map +1 -1
- package/dist/agents/rows.d.ts +6 -0
- package/dist/agents/rows.d.ts.map +1 -1
- package/dist/agents/runs.d.ts +2 -1
- package/dist/agents/runs.d.ts.map +1 -1
- package/dist/agents/threads.d.ts +3 -1
- package/dist/agents/threads.d.ts.map +1 -1
- package/dist/agents/token-rates.d.ts +13 -0
- package/dist/agents/token-rates.d.ts.map +1 -0
- package/dist/ai-accounting-filters.d.ts +12 -0
- package/dist/ai-accounting-filters.d.ts.map +1 -0
- package/dist/ai-cost-groups.d.ts +1 -1
- package/dist/ai-cost-groups.d.ts.map +1 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1446 -588
- package/dist/index.js.map +30 -25
- package/dist/migrations.d.ts.map +1 -1
- package/dist/objects/index.d.ts +1 -0
- package/dist/objects/index.d.ts.map +1 -1
- package/dist/objects/partitions.d.ts +10 -0
- package/dist/objects/partitions.d.ts.map +1 -0
- package/dist/objects/prepare-queries.d.ts.map +1 -1
- package/dist/objects/query-compiler.d.ts +5 -0
- package/dist/objects/query-compiler.d.ts.map +1 -1
- package/dist/objects/query-indexes.d.ts +19 -1
- package/dist/objects/query-indexes.d.ts.map +1 -1
- package/dist/objects/reader.d.ts +3 -1
- package/dist/objects/reader.d.ts.map +1 -1
- package/dist/objects/sql-text.d.ts +3 -0
- package/dist/objects/sql-text.d.ts.map +1 -0
- package/dist/objects/storage.d.ts +3 -1
- package/dist/objects/storage.d.ts.map +1 -1
- package/dist/objects/text-count-index.d.ts.map +1 -1
- package/dist/ontology-storage/commits.d.ts.map +1 -1
- package/dist/ontology-storage/materialization-session.d.ts +7 -1
- package/dist/ontology-storage/materialization-session.d.ts.map +1 -1
- package/dist/ontology-storage/materialization-writer.d.ts +2 -0
- package/dist/ontology-storage/materialization-writer.d.ts.map +1 -1
- package/dist/ontology-storage/materializations.d.ts +2 -1
- package/dist/ontology-storage/materializations.d.ts.map +1 -1
- package/dist/pg-ai-cost-storage.d.ts.map +1 -1
- package/dist/pg-client.d.ts +1 -1
- package/dist/pg-client.d.ts.map +1 -1
- package/dist/storage-errors.d.ts +4 -1
- package/dist/storage-errors.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/agents/agent-storage.ts +10 -3
- package/src/agents/computers.ts +95 -0
- package/src/agents/messages.ts +15 -0
- package/src/agents/rows.ts +14 -0
- package/src/agents/runs.ts +56 -4
- package/src/agents/threads.ts +123 -2
- package/src/agents/token-rates.ts +76 -0
- package/src/ai-accounting-filters.ts +48 -0
- package/src/ai-cost-groups.ts +37 -12
- package/src/index.ts +21 -8
- package/src/migrations/082-agent-run-cancel-requests.sql +3 -0
- package/src/migrations/083-agent-thread-runs-on.sql +4 -0
- package/src/migrations/084-agent-token-rates.sql +16 -0
- package/src/migrations/085-agent-computer-sessions.sql +27 -0
- package/src/migrations/086-partition-objects.sql +93 -0
- package/src/migrations.ts +14 -0
- package/src/objects/index.ts +1 -0
- package/src/objects/partitions.ts +163 -0
- package/src/objects/prepare-queries.ts +50 -2
- package/src/objects/query-compiler.ts +136 -96
- package/src/objects/query-indexes.ts +120 -63
- package/src/objects/reader.ts +5 -4
- package/src/objects/sql-text.ts +8 -0
- package/src/objects/storage.ts +14 -2
- package/src/objects/text-count-index.ts +17 -12
- package/src/ontology-storage/commits.ts +11 -2
- package/src/ontology-storage/materialization-session.ts +10 -1
- package/src/ontology-storage/materialization-writer.ts +14 -0
- package/src/ontology-storage/materializations.ts +81 -7
- package/src/pg-ai-cost-storage.ts +119 -15
- package/src/pg-client.ts +13 -6
- package/src/storage-errors.ts +28 -1
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
-- Where a conversation's turns run: NULL in the cloud, 'computer' on its owner's computer.
|
|
2
|
+
ALTER TABLE agent_threads ADD COLUMN runs_on TEXT CHECK (runs_on IS NULL OR runs_on = 'computer');
|
|
3
|
+
-- Which of its owner's computers runs a computer's thread: NULL until one claims its first turn.
|
|
4
|
+
ALTER TABLE agent_threads ADD COLUMN computer_id TEXT;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
-- What each model's tokenizer measured on a project's agent runs, one row per run: the bytes of a
|
|
2
|
+
-- request's text as the Agent's context estimator weighs them, against the text tokens the
|
|
3
|
+
-- provider counted. A record deletes the model's rows past its newest 20, so the table stays small.
|
|
4
|
+
CREATE TABLE agent_token_rates (
|
|
5
|
+
project_id TEXT NOT NULL CHECK (length(trim(project_id)) > 0),
|
|
6
|
+
run_id TEXT NOT NULL CHECK (length(trim(run_id)) > 0),
|
|
7
|
+
provider_id TEXT NOT NULL CHECK (length(trim(provider_id)) > 0),
|
|
8
|
+
model_id TEXT NOT NULL CHECK (length(trim(model_id)) > 0),
|
|
9
|
+
bytes INTEGER NOT NULL CHECK (bytes > 0),
|
|
10
|
+
tokens INTEGER NOT NULL CHECK (tokens > 0),
|
|
11
|
+
measured_at TIMESTAMPTZ NOT NULL,
|
|
12
|
+
PRIMARY KEY (project_id, run_id)
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
CREATE INDEX idx_agent_token_rates_model
|
|
16
|
+
ON agent_token_rates (project_id, provider_id, model_id, measured_at DESC, run_id DESC);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
-- Where a computer's thread runs: the computer's name and the folder there, beside its id. A
|
|
2
|
+
-- computer kept before folders were has none until its owner moves the thread.
|
|
3
|
+
ALTER TABLE agent_threads ADD COLUMN computer_name TEXT;
|
|
4
|
+
ALTER TABLE agent_threads ADD COLUMN computer_folder TEXT;
|
|
5
|
+
UPDATE agent_threads SET computer_id = NULL WHERE computer_id IS NOT NULL;
|
|
6
|
+
-- When its turns last moved to where they run now: the files earlier turns used are not there.
|
|
7
|
+
ALTER TABLE agent_threads ADD COLUMN moved_at TIMESTAMPTZ;
|
|
8
|
+
|
|
9
|
+
-- Each open sixb on its owner's computers, a lease it renews: while one is live, the threads that
|
|
10
|
+
-- run on its computer in its folder are reachable there.
|
|
11
|
+
CREATE TABLE agent_computer_sessions (
|
|
12
|
+
project_id TEXT NOT NULL,
|
|
13
|
+
owner_principal_type TEXT NOT NULL CHECK (owner_principal_type IN ('user', 'serviceAccount', 'system')),
|
|
14
|
+
owner_principal_id TEXT NOT NULL CHECK (length(owner_principal_id) > 0),
|
|
15
|
+
id TEXT NOT NULL CHECK (length(id) > 0),
|
|
16
|
+
computer_id TEXT NOT NULL,
|
|
17
|
+
computer_name TEXT NOT NULL,
|
|
18
|
+
folder TEXT NOT NULL,
|
|
19
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
20
|
+
PRIMARY KEY (project_id, owner_principal_type, owner_principal_id, id)
|
|
21
|
+
);
|
|
22
|
+
CREATE INDEX agent_computer_sessions_by_expiry ON agent_computer_sessions (project_id, expires_at);
|
|
23
|
+
|
|
24
|
+
-- Each open sixb asks every 20 seconds which of its owner's threads here have a turn active.
|
|
25
|
+
CREATE INDEX agent_threads_active_on_computer
|
|
26
|
+
ON agent_threads (project_id, owner_principal_type, owner_principal_id, computer_id, computer_folder)
|
|
27
|
+
WHERE active_run_id IS NOT NULL;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
-- Partition objects by object type, so a query plans against its own type's indexes alone instead
|
|
2
|
+
-- of every index of every type. Query indexes and extended statistics go with the old table:
|
|
3
|
+
-- preparation builds them again on the new partitions, right after this migration.
|
|
4
|
+
DO $$
|
|
5
|
+
DECLARE
|
|
6
|
+
item record;
|
|
7
|
+
columns_list text;
|
|
8
|
+
restore_constraints text[] := '{}';
|
|
9
|
+
restore_indexes text[] := '{}';
|
|
10
|
+
statement text;
|
|
11
|
+
BEGIN
|
|
12
|
+
-- Copying the rows takes as long as it takes, whatever timeout this role's queries run under.
|
|
13
|
+
-- Waiting for the lock does not: while this waits, every other query waits behind it, so it gives
|
|
14
|
+
-- way to a long query, and the migration fails cleanly if that query outlasts every attempt.
|
|
15
|
+
PERFORM set_config('statement_timeout', '0', true);
|
|
16
|
+
PERFORM set_config('lock_timeout', '3s', true);
|
|
17
|
+
FOR attempt IN 1..5 LOOP
|
|
18
|
+
BEGIN
|
|
19
|
+
LOCK TABLE objects IN ACCESS EXCLUSIVE MODE;
|
|
20
|
+
EXIT;
|
|
21
|
+
EXCEPTION WHEN lock_not_available THEN
|
|
22
|
+
IF attempt = 5 THEN RAISE; END IF;
|
|
23
|
+
PERFORM pg_sleep(attempt * 0.5);
|
|
24
|
+
END;
|
|
25
|
+
END LOOP;
|
|
26
|
+
|
|
27
|
+
-- objects is held now. Tables that reference it may have readers, so wait for those a little
|
|
28
|
+
-- longer, and fail cleanly rather than hold every query behind objects for good.
|
|
29
|
+
PERFORM set_config('lock_timeout', '30s', true);
|
|
30
|
+
|
|
31
|
+
FOR item IN
|
|
32
|
+
SELECT conrelid::regclass::text AS table_name, conname, pg_get_constraintdef(oid) AS definition
|
|
33
|
+
FROM pg_constraint
|
|
34
|
+
WHERE confrelid = 'objects'::regclass AND contype = 'f' AND conparentid = 0
|
|
35
|
+
LOOP
|
|
36
|
+
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', item.table_name, item.conname);
|
|
37
|
+
restore_constraints := restore_constraints || format(
|
|
38
|
+
'ALTER TABLE %s ADD CONSTRAINT %I %s', item.table_name, item.conname, item.definition
|
|
39
|
+
);
|
|
40
|
+
END LOOP;
|
|
41
|
+
|
|
42
|
+
SELECT string_agg(quote_ident(attname), ', ' ORDER BY attnum) INTO columns_list
|
|
43
|
+
FROM pg_attribute
|
|
44
|
+
WHERE attrelid = 'objects'::regclass AND attnum > 0 AND NOT attisdropped AND attgenerated = '';
|
|
45
|
+
|
|
46
|
+
-- The table's general indexes stay on the parent under their names; prepared ones do not.
|
|
47
|
+
FOR item IN
|
|
48
|
+
SELECT c.relname AS name, pg_get_indexdef(c.oid) AS definition
|
|
49
|
+
FROM pg_index i
|
|
50
|
+
JOIN pg_class c ON c.oid = i.indexrelid
|
|
51
|
+
WHERE i.indrelid = 'objects'::regclass
|
|
52
|
+
AND NOT i.indisprimary
|
|
53
|
+
AND c.relname NOT LIKE 'sixb\_query\_%'
|
|
54
|
+
AND c.relname NOT LIKE 'sixb\_text\_count\_%'
|
|
55
|
+
LOOP
|
|
56
|
+
restore_indexes := restore_indexes || item.definition;
|
|
57
|
+
EXECUTE format('DROP INDEX %I', item.name);
|
|
58
|
+
END LOOP;
|
|
59
|
+
|
|
60
|
+
ALTER TABLE objects RENAME TO objects_unpartitioned;
|
|
61
|
+
ALTER INDEX objects_pkey RENAME TO objects_unpartitioned_pkey;
|
|
62
|
+
|
|
63
|
+
CREATE TABLE objects (
|
|
64
|
+
LIKE objects_unpartitioned
|
|
65
|
+
INCLUDING DEFAULTS INCLUDING GENERATED INCLUDING CONSTRAINTS INCLUDING STORAGE INCLUDING COMMENTS,
|
|
66
|
+
PRIMARY KEY (project_id, object_type_id, primary_id)
|
|
67
|
+
) PARTITION BY LIST (object_type_id);
|
|
68
|
+
|
|
69
|
+
-- Holds a type until its first preparation gives it a partition.
|
|
70
|
+
CREATE TABLE objects_default PARTITION OF objects DEFAULT;
|
|
71
|
+
|
|
72
|
+
FOR item IN SELECT DISTINCT object_type_id AS id FROM objects_unpartitioned LOOP
|
|
73
|
+
EXECUTE format(
|
|
74
|
+
'CREATE TABLE %I PARTITION OF objects FOR VALUES IN (%L)',
|
|
75
|
+
'objects_' || left(md5(item.id), 24),
|
|
76
|
+
item.id
|
|
77
|
+
);
|
|
78
|
+
END LOOP;
|
|
79
|
+
|
|
80
|
+
EXECUTE format(
|
|
81
|
+
'INSERT INTO objects (%s) SELECT %s FROM objects_unpartitioned', columns_list, columns_list
|
|
82
|
+
);
|
|
83
|
+
DROP TABLE objects_unpartitioned;
|
|
84
|
+
|
|
85
|
+
FOREACH statement IN ARRAY restore_indexes LOOP
|
|
86
|
+
EXECUTE statement;
|
|
87
|
+
END LOOP;
|
|
88
|
+
FOREACH statement IN ARRAY restore_constraints LOOP
|
|
89
|
+
EXECUTE statement;
|
|
90
|
+
END LOOP;
|
|
91
|
+
END $$;
|
|
92
|
+
|
|
93
|
+
ANALYZE objects;
|
package/src/migrations.ts
CHANGED
|
@@ -452,6 +452,11 @@ export const postgresStorageMigrations = defineMigrations<PostgresMigrationConte
|
|
|
452
452
|
pgSql("079-agent-approval-resume", agentApprovalResumeSql),
|
|
453
453
|
pgSql("080-subagent-threads", subagentThreadsSql),
|
|
454
454
|
pgSql("081-subagent-questions", subagentQuestionsSql),
|
|
455
|
+
pgSql("082-agent-run-cancel-requests", agentRunCancelRequestsSql),
|
|
456
|
+
pgSql("083-agent-thread-runs-on", agentThreadRunsOnSql),
|
|
457
|
+
pgSql("084-agent-token-rates", agentTokenRatesSql),
|
|
458
|
+
pgSql("085-agent-computer-sessions", agentComputerSessionsSql),
|
|
459
|
+
pgSql("086-partition-objects", partitionObjectsSql),
|
|
455
460
|
],
|
|
456
461
|
})
|
|
457
462
|
|
|
@@ -515,3 +520,12 @@ import agentApprovalResumeSql from "./migrations/079-agent-approval-resume.sql"
|
|
|
515
520
|
}
|
|
516
521
|
import subagentThreadsSql from "./migrations/080-subagent-threads.sql" with { type: "text" }
|
|
517
522
|
import subagentQuestionsSql from "./migrations/081-subagent-questions.sql" with { type: "text" }
|
|
523
|
+
import agentRunCancelRequestsSql from "./migrations/082-agent-run-cancel-requests.sql" with {
|
|
524
|
+
type: "text",
|
|
525
|
+
}
|
|
526
|
+
import agentThreadRunsOnSql from "./migrations/083-agent-thread-runs-on.sql" with { type: "text" }
|
|
527
|
+
import agentTokenRatesSql from "./migrations/084-agent-token-rates.sql" with { type: "text" }
|
|
528
|
+
import agentComputerSessionsSql from "./migrations/085-agent-computer-sessions.sql" with {
|
|
529
|
+
type: "text",
|
|
530
|
+
}
|
|
531
|
+
import partitionObjectsSql from "./migrations/086-partition-objects.sql" with { type: "text" }
|
package/src/objects/index.ts
CHANGED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import type { ReservedSQL } from "../pg-client"
|
|
3
|
+
import { isLockConflict } from "../storage-errors"
|
|
4
|
+
import { runPgTransactionOn } from "../transactions"
|
|
5
|
+
import { identifier, literal } from "./sql-text"
|
|
6
|
+
|
|
7
|
+
// A query reading every partition, and any publication, holds the default partition until it
|
|
8
|
+
// commits, which can take minutes. While this waits such queries queue behind it, so it waits a
|
|
9
|
+
// moment at a time and steps aside between attempts: about four minutes in all.
|
|
10
|
+
const LOCK_TIMEOUT = "1s"
|
|
11
|
+
const LOCK_ATTEMPTS = 120
|
|
12
|
+
const LOCK_RETRY_MS = 1_000
|
|
13
|
+
|
|
14
|
+
/** Migration 086 derives the same name in SQL: `'objects_' || left(md5(type), 24)`. */
|
|
15
|
+
export function objectPartitionName(objectTypeId: string): string {
|
|
16
|
+
return `objects_${createHash("md5").update(objectTypeId).digest("hex").slice(0, 24)}`
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The object type's partition, created on first use. Reads that name another type never wait. A
|
|
21
|
+
* short lock timeout and retries mean this gives way to long queries and publications instead of
|
|
22
|
+
* queuing other work behind itself, and preparation fails cleanly if they outlast every attempt.
|
|
23
|
+
*/
|
|
24
|
+
export async function ensureObjectPartition(
|
|
25
|
+
connection: ReservedSQL,
|
|
26
|
+
schema: string,
|
|
27
|
+
objectTypeId: string
|
|
28
|
+
): Promise<string> {
|
|
29
|
+
const name = objectPartitionName(objectTypeId)
|
|
30
|
+
const partition = `${identifier(schema)}.${identifier(name)}`
|
|
31
|
+
const [existing] = await connection<{ found: string | null }[]>`
|
|
32
|
+
SELECT to_regclass(${partition})::text AS found`
|
|
33
|
+
if (existing?.found) return name
|
|
34
|
+
|
|
35
|
+
for (let attempt = 1; ; attempt++) {
|
|
36
|
+
try {
|
|
37
|
+
await createObjectPartition(connection, schema, partition, objectTypeId)
|
|
38
|
+
return name
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (!isLockConflict(error)) throw error
|
|
41
|
+
if (attempt === LOCK_ATTEMPTS) {
|
|
42
|
+
throw new Error(
|
|
43
|
+
`[SixbPg] Could not add a partition for object type '${objectTypeId}': other queries held their locks through ${LOCK_ATTEMPTS} attempts. Retry when they finish.`,
|
|
44
|
+
{ cause: error }
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
await Bun.sleep(LOCK_RETRY_MS)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function createObjectPartition(
|
|
53
|
+
connection: ReservedSQL,
|
|
54
|
+
schema: string,
|
|
55
|
+
partition: string,
|
|
56
|
+
objectTypeId: string
|
|
57
|
+
): Promise<void> {
|
|
58
|
+
const parent = `${identifier(schema)}.objects`
|
|
59
|
+
const fallback = `${identifier(schema)}.objects_default`
|
|
60
|
+
const type = literal(objectTypeId)
|
|
61
|
+
const hasRows = async () => {
|
|
62
|
+
const [row] = await connection.unsafe(
|
|
63
|
+
`SELECT 1 FROM ${fallback} WHERE object_type_id = ${type} LIMIT 1`
|
|
64
|
+
)
|
|
65
|
+
return row !== undefined
|
|
66
|
+
}
|
|
67
|
+
const guarded = (run: () => Promise<void>) =>
|
|
68
|
+
runPgTransactionOn(connection, async () => {
|
|
69
|
+
await connection.unsafe(`SET LOCAL lock_timeout = '${LOCK_TIMEOUT}'`)
|
|
70
|
+
// Copying rows takes as long as it takes, whatever timeout this role's queries run under.
|
|
71
|
+
await connection.unsafe("SET LOCAL statement_timeout = 0")
|
|
72
|
+
await run()
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
let moving = false
|
|
76
|
+
await guarded(async () => {
|
|
77
|
+
moving = await hasRows()
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
// Moving rows must drop foreign keys, which takes the parent exclusively, so it asks for that from
|
|
81
|
+
// the start rather than upgrading a lock while queries wait behind it. Otherwise attaching only
|
|
82
|
+
// needs SHARE UPDATE EXCLUSIVE on the parent, so reads and writes of other types carry on.
|
|
83
|
+
await guarded(async () => {
|
|
84
|
+
const references = await referencesToObjects(connection, parent)
|
|
85
|
+
await connection.unsafe(
|
|
86
|
+
`LOCK TABLE ONLY ${parent} IN ${moving ? "ACCESS EXCLUSIVE" : "SHARE UPDATE EXCLUSIVE"} MODE`
|
|
87
|
+
)
|
|
88
|
+
// Before the default partition: a writer on these tables goes on to check objects, so taking
|
|
89
|
+
// them in this order leaves no cycle for it to be killed in.
|
|
90
|
+
for (const { table_name: table } of references) {
|
|
91
|
+
await connection.unsafe(`LOCK TABLE ${table} IN SHARE ROW EXCLUSIVE MODE`)
|
|
92
|
+
}
|
|
93
|
+
await connection.unsafe(`LOCK TABLE ${fallback} IN ACCESS EXCLUSIVE MODE`)
|
|
94
|
+
|
|
95
|
+
// A row arrived since the check above, so its type needs the moving path. The next attempt takes it.
|
|
96
|
+
if (!moving && (await hasRows())) {
|
|
97
|
+
throw Object.assign(new Error("[SixbPg] A row arrived while adding its partition."), {
|
|
98
|
+
code: "55P03",
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
await connection.unsafe(
|
|
103
|
+
`CREATE TABLE ${partition} (LIKE ${parent} INCLUDING DEFAULTS INCLUDING GENERATED INCLUDING CONSTRAINTS INCLUDING STORAGE)`
|
|
104
|
+
)
|
|
105
|
+
if (moving) await moveRowsFromDefault(connection, parent, fallback, partition, type, references)
|
|
106
|
+
await connection.unsafe(
|
|
107
|
+
`ALTER TABLE ${parent} ATTACH PARTITION ${partition} FOR VALUES IN (${type})`
|
|
108
|
+
)
|
|
109
|
+
if (moving) {
|
|
110
|
+
for (const reference of references) {
|
|
111
|
+
await connection.unsafe(
|
|
112
|
+
`ALTER TABLE ${reference.table_name} ADD CONSTRAINT ${identifier(reference.name)} ${reference.definition}`
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
// Not under the locks above: every query on every type is waiting behind them.
|
|
119
|
+
if (moving) await guarded(() => connection.unsafe(`ANALYZE ${partition}`).then(() => undefined))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
interface ObjectReference {
|
|
123
|
+
readonly table_name: string
|
|
124
|
+
readonly name: string
|
|
125
|
+
readonly definition: string
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function referencesToObjects(connection: ReservedSQL, parent: string) {
|
|
129
|
+
return connection<ObjectReference[]>`
|
|
130
|
+
SELECT conrelid::regclass::text AS table_name, conname AS name,
|
|
131
|
+
pg_get_constraintdef(oid) AS definition
|
|
132
|
+
FROM pg_constraint
|
|
133
|
+
WHERE confrelid = ${parent}::regclass AND contype = 'f' AND conparentid = 0`
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Nothing about the rows changes, so foreign keys that reference objects must not see a delete:
|
|
138
|
+
* ON DELETE CASCADE would remove what they protect. The caller adds them back.
|
|
139
|
+
*/
|
|
140
|
+
async function moveRowsFromDefault(
|
|
141
|
+
connection: ReservedSQL,
|
|
142
|
+
parent: string,
|
|
143
|
+
fallback: string,
|
|
144
|
+
partition: string,
|
|
145
|
+
type: string,
|
|
146
|
+
references: readonly ObjectReference[]
|
|
147
|
+
): Promise<void> {
|
|
148
|
+
for (const reference of references) {
|
|
149
|
+
await connection.unsafe(
|
|
150
|
+
`ALTER TABLE ${reference.table_name} DROP CONSTRAINT ${identifier(reference.name)}`
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const columns = await connection<{ name: string }[]>`
|
|
155
|
+
SELECT attname AS name FROM pg_attribute
|
|
156
|
+
WHERE attrelid = ${parent}::regclass AND attnum > 0 AND NOT attisdropped AND attgenerated = ''
|
|
157
|
+
ORDER BY attnum`
|
|
158
|
+
const list = columns.map((column) => identifier(column.name)).join(", ")
|
|
159
|
+
await connection.unsafe(
|
|
160
|
+
`INSERT INTO ${partition} (${list}) SELECT ${list} FROM ${fallback} WHERE object_type_id = ${type}`
|
|
161
|
+
)
|
|
162
|
+
await connection.unsafe(`DELETE FROM ${fallback} WHERE object_type_id = ${type}`)
|
|
163
|
+
}
|
|
@@ -2,7 +2,9 @@ import { createHash } from "node:crypto"
|
|
|
2
2
|
import type { ObjectQueryIndexDefinition } from "@sixb/core"
|
|
3
3
|
import type { ObjectQueryPreparationPlan, ObjectQueryPreparationResult } from "@sixb/core/storage"
|
|
4
4
|
import type { ReservedSQL, SQL, SQLClient } from "../pg-client"
|
|
5
|
+
import { isConnectionLost } from "../storage-errors"
|
|
5
6
|
import { undoOnFailure, withReservedPgConnection } from "../transactions"
|
|
7
|
+
import { ensureObjectPartition } from "./partitions"
|
|
6
8
|
import { lockPgPreparation } from "./preparation-lock"
|
|
7
9
|
import { ensurePgObjectQueryIndexes, type PgObjectQueryIndex } from "./query-indexes"
|
|
8
10
|
import { type PgObjectTextCountIndex, preparePgObjectTextCounts } from "./text-count-index"
|
|
@@ -43,7 +45,10 @@ export async function preparePgObjectQueries(
|
|
|
43
45
|
}, unlock)
|
|
44
46
|
await unlock()
|
|
45
47
|
|
|
46
|
-
|
|
48
|
+
// Advice, so it runs after the lock: other instances starting up need not wait for this scan.
|
|
49
|
+
return result.status === "current"
|
|
50
|
+
? result
|
|
51
|
+
: { ...result, warnings: [...result.warnings, ...(await linkWarnings(connection, plan))] }
|
|
47
52
|
})
|
|
48
53
|
}
|
|
49
54
|
|
|
@@ -55,11 +60,12 @@ function preparationFingerprint(plan: ObjectQueryPreparationPlan): string {
|
|
|
55
60
|
indexes: type.indexes
|
|
56
61
|
.map(normalizeIndex)
|
|
57
62
|
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
|
|
63
|
+
links: [...type.links].sort((a, b) => a.linkId.localeCompare(b.linkId)),
|
|
58
64
|
}))
|
|
59
65
|
.sort((a, b) => a.objectTypeId.localeCompare(b.objectTypeId))
|
|
60
66
|
|
|
61
67
|
// Bump the version when physical generation changes, even if the ontology stays the same.
|
|
62
|
-
const definition = { version:
|
|
68
|
+
const definition = { version: 3, projectId: plan.projectId, objectTypes }
|
|
63
69
|
return createHash("sha256").update(JSON.stringify(definition)).digest("hex")
|
|
64
70
|
}
|
|
65
71
|
|
|
@@ -106,6 +112,9 @@ async function prepareStructures(
|
|
|
106
112
|
await ensureTrigrams(sql)
|
|
107
113
|
}
|
|
108
114
|
|
|
115
|
+
// Every ontology type gets its partition, whether or not it declares an index.
|
|
116
|
+
for (const type of plan.objectTypes) await ensureObjectPartition(sql, schema, type.objectTypeId)
|
|
117
|
+
|
|
109
118
|
const names = await ensurePgObjectQueryIndexes(sql, schema, indexes)
|
|
110
119
|
const texts = await preparePgObjectTextCounts(sql, schema, textCounts)
|
|
111
120
|
return {
|
|
@@ -116,6 +125,45 @@ async function prepareStructures(
|
|
|
116
125
|
}
|
|
117
126
|
}
|
|
118
127
|
|
|
128
|
+
/**
|
|
129
|
+
* Queries read a link as the ontology declares it, so narrowing or removing one hides its older
|
|
130
|
+
* edges. Told once, when the ontology changes: not stored with the plan, so it cannot outlive the
|
|
131
|
+
* edges. This is advice, so failing to work it out does not fail the preparation.
|
|
132
|
+
*/
|
|
133
|
+
async function linkWarnings(
|
|
134
|
+
sql: ReservedSQL,
|
|
135
|
+
plan: ObjectQueryPreparationPlan
|
|
136
|
+
): Promise<readonly string[]> {
|
|
137
|
+
const declared = new Map(
|
|
138
|
+
plan.objectTypes.flatMap((type) =>
|
|
139
|
+
type.links.map((link) => [`${type.objectTypeId}\0${link.linkId}`, link] as const)
|
|
140
|
+
)
|
|
141
|
+
)
|
|
142
|
+
try {
|
|
143
|
+
const edges = await sql<
|
|
144
|
+
{ source_type_id: string; link_id: string; target_type_id: string; edges: string }[]
|
|
145
|
+
>`
|
|
146
|
+
SELECT source_type_id, link_id, target_type_id, COUNT(*) AS edges
|
|
147
|
+
FROM links WHERE project_id = ${plan.projectId}
|
|
148
|
+
GROUP BY source_type_id, link_id, target_type_id`
|
|
149
|
+
|
|
150
|
+
return edges.flatMap((edge) => {
|
|
151
|
+
const name = `${edge.source_type_id}.${edge.link_id}`
|
|
152
|
+
const link = declared.get(`${edge.source_type_id}\0${edge.link_id}`)
|
|
153
|
+
if (!link) {
|
|
154
|
+
return `${name}: ${edge.edges} stored edges to ${edge.target_type_id} belong to a link the ontology no longer declares. Queries may not return them.`
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return !link.targetObjectTypeIds || link.targetObjectTypeIds.includes(edge.target_type_id)
|
|
158
|
+
? []
|
|
159
|
+
: `${name}: ${edge.edges} stored edges point to ${edge.target_type_id}, which this link no longer allows. Queries may not return them.`
|
|
160
|
+
})
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (isConnectionLost(error)) throw error
|
|
163
|
+
return [`Could not check stored links against the ontology: ${String(error)}`]
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
119
167
|
function compilePreparationPlan(plan: ObjectQueryPreparationPlan) {
|
|
120
168
|
const indexes: PgObjectQueryIndex[] = []
|
|
121
169
|
const textCounts: PgObjectTextCountIndex[] = []
|