@sixb/pg 0.1.24 → 0.1.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.
package/dist/index.js CHANGED
@@ -247,6 +247,8 @@ function rowToThreadRecord(row) {
247
247
  ...row.sandbox_params == null ? {} : {
248
248
  sandboxParams: snapshotAgentThreadSandboxParams(typeof row.sandbox_params === "string" ? JSON.parse(row.sandbox_params) : row.sandbox_params)
249
249
  },
250
+ ...row.runs_on == null ? {} : { runsOn: row.runs_on },
251
+ ...row.computer_id == null ? {} : { computerId: row.computer_id },
250
252
  status: row.status,
251
253
  activeRunId: row.active_run_id,
252
254
  lastMessageAt: row.last_message_at ? new Date(row.last_message_at) : undefined,
@@ -270,6 +272,7 @@ function rowToRunRecord(row) {
270
272
  token: row.execution_token,
271
273
  queueLeaseExpiresAt: new Date(row.execution_queue_lease_expires_at)
272
274
  } : undefined,
275
+ cancelRequestedAt: row.cancel_requested_at ? new Date(row.cancel_requested_at) : undefined,
273
276
  createdAt: new Date(row.created_at),
274
277
  startedAt: row.started_at ? new Date(row.started_at) : undefined,
275
278
  completedAt: row.completed_at ? new Date(row.completed_at) : undefined
@@ -1031,6 +1034,17 @@ class PgAgentMessageStore {
1031
1034
  }
1032
1035
  async deleteByRunId(input) {
1033
1036
  return runPgTransaction(this.sql, async (tx) => {
1037
+ if (input.fence) {
1038
+ const [owner] = await tx`
1039
+ SELECT id FROM agent_runs
1040
+ WHERE project_id = ${input.projectId} AND id = ${input.fence.runId}
1041
+ AND status = 'running' AND execution_token = ${input.fence.executionToken}
1042
+ FOR SHARE
1043
+ `;
1044
+ if (!owner) {
1045
+ throw new AgentStorageError3("execution_lost", `[SixbPg] Execution token is no longer current on agent run '${input.fence.runId}'.`);
1046
+ }
1047
+ }
1034
1048
  const [thread] = await tx`
1035
1049
  SELECT id FROM agent_threads
1036
1050
  WHERE project_id = ${input.projectId} AND id = ${input.threadId}
@@ -1382,7 +1396,10 @@ class PgAgentRunStore {
1382
1396
  }
1383
1397
  async reclaim(input) {
1384
1398
  return runPgTransaction(this.sql, async (tx) => {
1385
- await this.lockRunning(tx, input.projectId, input.id);
1399
+ const run = await this.lockRunning(tx, input.projectId, input.id);
1400
+ if (input.ifLapsedBy && run.execution_queue_lease_expires_at !== null && new Date(run.execution_queue_lease_expires_at).getTime() > input.ifLapsedBy.getTime()) {
1401
+ throw new AgentStorageError4("invalid_state", `[SixbPg] Agent run '${input.id}' is still held by its runner, whose lease has not lapsed.`);
1402
+ }
1386
1403
  const [row] = await tx`
1387
1404
  UPDATE agent_runs
1388
1405
  SET
@@ -1413,6 +1430,22 @@ class PgAgentRunStore {
1413
1430
  return rowToRunRecord(row);
1414
1431
  });
1415
1432
  }
1433
+ async requestCancel(input) {
1434
+ const [updated] = await this.sql`
1435
+ UPDATE agent_runs
1436
+ SET cancel_requested_at = ${input.at ?? new Date}
1437
+ WHERE project_id = ${input.projectId} AND id = ${input.id}
1438
+ AND status = 'running' AND cancel_requested_at IS NULL
1439
+ RETURNING *
1440
+ `;
1441
+ if (updated)
1442
+ return rowToRunRecord(updated);
1443
+ const current = await this.getById(input);
1444
+ if (!current) {
1445
+ throw new AgentStorageError4("run_not_found", `[SixbPg] Agent run '${input.id}' not found for project '${input.projectId}'.`);
1446
+ }
1447
+ return current;
1448
+ }
1416
1449
  async finish(input) {
1417
1450
  const completedAt = input.completedAt ?? new Date;
1418
1451
  const errorValue = input.status === "succeeded" || input.error === undefined ? null : serializeSixbFailure(input.error, AGENT_RUN_FAILURE_CODES2);
@@ -1688,7 +1721,10 @@ function threadNotFound(input) {
1688
1721
 
1689
1722
  // src/agents/threads.ts
1690
1723
  import {
1724
+ assertAssignableComputer,
1725
+ assertComputerId,
1691
1726
  assertConversationThreadRow as assertConversationThreadRow2,
1727
+ assertRunsOn,
1692
1728
  participantsToAdd,
1693
1729
  planAgentThreadFork,
1694
1730
  remapArtifactIds,
@@ -1720,9 +1756,11 @@ class PgAgentThreadStore {
1720
1756
  });
1721
1757
  }
1722
1758
  async create(input) {
1759
+ assertRunsOn(input.runsOn, "Agent thread", "SixbPg");
1723
1760
  const sandboxParams = input.sandboxParams === undefined ? null : JSON.stringify(snapshotAgentThreadSandboxParams2(input.sandboxParams));
1724
1761
  const createdAt = input.createdAt ?? new Date;
1725
1762
  const updatedAt = input.updatedAt ?? createdAt;
1763
+ const runsOn = input.runsOn === undefined ? { column: this.sql``, value: this.sql`` } : { column: this.sql`runs_on,`, value: this.sql`${input.runsOn},` };
1726
1764
  try {
1727
1765
  const [row] = await this.sql`
1728
1766
  INSERT INTO agent_threads (
@@ -1732,6 +1770,7 @@ class PgAgentThreadStore {
1732
1770
  owner_principal_id,
1733
1771
  title,
1734
1772
  sandbox_params,
1773
+ ${runsOn.column}
1735
1774
  status,
1736
1775
  created_at,
1737
1776
  updated_at
@@ -1742,6 +1781,7 @@ class PgAgentThreadStore {
1742
1781
  ${input.ownerPrincipal.id},
1743
1782
  ${input.title ?? null},
1744
1783
  ${sandboxParams}::text::jsonb,
1784
+ ${runsOn.value}
1745
1785
  ${input.status ?? "active"},
1746
1786
  ${createdAt},
1747
1787
  ${updatedAt}
@@ -2006,6 +2046,22 @@ class PgAgentThreadStore {
2006
2046
  `;
2007
2047
  return rows.length > 0;
2008
2048
  }
2049
+ async assignComputer(input) {
2050
+ assertComputerId(input.computerId, "SixbPg");
2051
+ const [row] = await this.sql`
2052
+ UPDATE agent_threads SET computer_id = ${input.computerId}
2053
+ WHERE project_id = ${input.projectId}
2054
+ AND id = ${input.id}
2055
+ AND runs_on = 'computer'
2056
+ ${input.ifUnassigned ? this.sql`AND computer_id IS NULL` : this.sql``}
2057
+ RETURNING *
2058
+ `;
2059
+ if (row)
2060
+ return rowToThreadRecord(row);
2061
+ const thread = await this.getById(input);
2062
+ assertAssignableComputer(thread, input.id, "SixbPg");
2063
+ return thread;
2064
+ }
2009
2065
  async listParticipants(input) {
2010
2066
  return selectParticipants(this.sql, input.projectId, [...new Set(input.threadIds)]);
2011
2067
  }
@@ -9732,6 +9788,19 @@ CREATE INDEX idx_agent_runs_paused_on_question
9732
9788
  WHERE kind = 'subagent' AND finish_reason = 'awaiting_answer';
9733
9789
  `;
9734
9790
 
9791
+ // src/migrations/082-agent-run-cancel-requests.sql
9792
+ var _082_agent_run_cancel_requests_default = `-- A cancel is recorded on the run, not only broadcast: a runner that never hears the broker learns
9793
+ -- of it at its next lease renewal, and the run token stops working at once.
9794
+ ALTER TABLE agent_runs ADD COLUMN cancel_requested_at TIMESTAMPTZ;
9795
+ `;
9796
+
9797
+ // src/migrations/083-agent-thread-runs-on.sql
9798
+ var _083_agent_thread_runs_on_default = `-- Where a conversation's turns run: NULL in the cloud, 'computer' on its owner's computer.
9799
+ ALTER TABLE agent_threads ADD COLUMN runs_on TEXT CHECK (runs_on IS NULL OR runs_on = 'computer');
9800
+ -- Which of its owner's computers runs a computer's thread: NULL until one claims its first turn.
9801
+ ALTER TABLE agent_threads ADD COLUMN computer_id TEXT;
9802
+ `;
9803
+
9735
9804
  // src/migrations.ts
9736
9805
  var POSTGRES_STORAGE_ADAPTER_ID = "SixbPostgresStorage";
9737
9806
  function pgSql(id, sqlText) {
@@ -9979,41 +10048,28 @@ var postgresStorageMigrations = defineMigrations({
9979
10048
  pgSql("078-agent-approvals", _078_agent_approvals_default),
9980
10049
  pgSql("079-agent-approval-resume", _079_agent_approval_resume_default),
9981
10050
  pgSql("080-subagent-threads", _080_subagent_threads_default),
9982
- pgSql("081-subagent-questions", _081_subagent_questions_default)
10051
+ pgSql("081-subagent-questions", _081_subagent_questions_default),
10052
+ pgSql("082-agent-run-cancel-requests", _082_agent_run_cancel_requests_default),
10053
+ pgSql("083-agent-thread-runs-on", _083_agent_thread_runs_on_default)
9983
10054
  ]
9984
10055
  });
9985
10056
 
9986
- // src/objects/storage.ts
9987
- import { hasVectorProfile as hasVectorProfile4 } from "@sixb/core/internal/query";
10057
+ // src/objects/query-indexes.ts
10058
+ import { createHash as createHash3 } from "crypto";
9988
10059
 
9989
- // src/objects/aggregate-admission.ts
9990
- class PgAggregateAdmission {
9991
- concurrency;
9992
- active = 0;
9993
- waiting = [];
9994
- constructor(concurrency = 1) {
9995
- this.concurrency = concurrency;
9996
- }
9997
- async run(compute) {
9998
- if (this.active >= this.concurrency)
9999
- await new Promise((resolve) => this.waiting.push(resolve));
10000
- else
10001
- this.active++;
10002
- try {
10003
- return await compute();
10004
- } finally {
10005
- const next = this.waiting.shift();
10006
- if (next)
10007
- next();
10008
- else
10009
- this.active--;
10010
- }
10060
+ // src/objects/preparation-lock.ts
10061
+ async function lockPgPreparation(sql, key) {
10062
+ let delay = 25;
10063
+ while (true) {
10064
+ const [row] = await sql`
10065
+ SELECT pg_try_advisory_lock(hashtextextended(${key}, 0)) AS acquired`;
10066
+ if (row?.acquired)
10067
+ return;
10068
+ await Bun.sleep(delay);
10069
+ delay = Math.min(delay * 2, 500);
10011
10070
  }
10012
10071
  }
10013
10072
 
10014
- // src/objects/conditional-reader.ts
10015
- import { hasVectorProfile as hasVectorProfile3 } from "@sixb/core/internal/query";
10016
-
10017
10073
  // src/objects/query-compiler.ts
10018
10074
  import {
10019
10075
  ObjectQueryExecutionError
@@ -10038,10 +10094,13 @@ function compilePgObjectQuery(projectId, query, options = {}) {
10038
10094
  }));
10039
10095
  if (options.sortIndexBound && source === DEFAULT_OBJECT_QUERY_SOURCE) {
10040
10096
  let bounded = query;
10041
- while (bounded.kind === "expand")
10097
+ const expansions = [];
10098
+ while (bounded.kind === "expand") {
10099
+ expansions.unshift(bounded.expansions);
10042
10100
  bounded = bounded.input;
10101
+ }
10043
10102
  if (bounded.kind === "page" || bounded.kind === "limit") {
10044
- const branches = [options.sortIndexBound, `NOT (${options.sortIndexBound})`].map((startPredicate, branch) => compileObjectQueryInternal(projectId, query, {
10103
+ const branches = [options.sortIndexBound, `NOT (${options.sortIndexBound})`].map((startPredicate, branch) => compileObjectQueryInternal(projectId, bounded, {
10045
10104
  probeLimit: options.includeTotal === false,
10046
10105
  source,
10047
10106
  startPredicate,
@@ -10049,11 +10108,17 @@ function compilePgObjectQuery(projectId, query, options = {}) {
10049
10108
  correlatedTraversal: options.correlatedTraversal
10050
10109
  }));
10051
10110
  const limit = bounded.kind === "page" ? bounded.pageSize + 1 : bounded.limit + (options.includeTotal === false ? 1 : 0);
10052
- compiled = {
10053
- ...compiled,
10111
+ let rows = {
10054
10112
  sql: `SELECT * FROM ((${branches[0].sql}) UNION ALL (${branches[1].sql})) AS input ORDER BY ${compiled.order.sql} LIMIT ?`,
10055
10113
  args: [...branches[0].args, ...branches[1].args, ...compiled.order.args, limit]
10056
10114
  };
10115
+ for (const expansion of expansions) {
10116
+ rows = expandRows({ ...rows, order: compiled.order }, expansion, {
10117
+ probeLimit: options.includeTotal === false,
10118
+ source
10119
+ });
10120
+ }
10121
+ compiled = { ...compiled, ...rows };
10057
10122
  }
10058
10123
  }
10059
10124
  const traversal = !options.correlatedTraversal && boundedTraversal(query);
@@ -10528,16 +10593,8 @@ function compileTraversalProbe(projectId, traversal, source) {
10528
10593
  }
10529
10594
  function compileExpand(projectId, inputQuery, expansions, ctx) {
10530
10595
  const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx));
10531
- const expand = compileExpansionsObject(expansions, { project: "input.project_id", type: "input.object_type_id", id: "input.primary_id" }, "", ctx);
10532
- const inputOrder = compileOrder(input.order.fields, "input", "input._cursor_properties");
10533
- const sql = `
10534
- SELECT input.*, ${expand.sql} AS _expand
10535
- FROM (${input.sql}) AS input
10536
- ORDER BY ${inputOrder.sql}
10537
- `;
10538
10596
  return {
10539
- sql,
10540
- args: [...expand.args, ...input.args, ...inputOrder.args],
10597
+ ...expandRows(input, expansions, ctx),
10541
10598
  totalSql: input.totalSql,
10542
10599
  totalArgs: input.totalArgs,
10543
10600
  vectorProbe: input.vectorProbe,
@@ -10548,6 +10605,18 @@ function compileExpand(projectId, inputQuery, expansions, ctx) {
10548
10605
  nextPageToken: input.nextPageToken
10549
10606
  };
10550
10607
  }
10608
+ function expandRows(input, expansions, ctx) {
10609
+ const expand = compileExpansionsObject(expansions, { project: "input.project_id", type: "input.object_type_id", id: "input.primary_id" }, "", ctx);
10610
+ const inputOrder = compileOrder(input.order.fields, "input", "input._cursor_properties");
10611
+ return {
10612
+ sql: `
10613
+ SELECT input.*, ${expand.sql} AS _expand
10614
+ FROM (${input.sql}) AS input
10615
+ ORDER BY ${inputOrder.sql}
10616
+ `,
10617
+ args: [...expand.args, ...input.args, ...inputOrder.args]
10618
+ };
10619
+ }
10551
10620
  function compileExpansionsObject(expansions, parent, pathPrefix, ctx) {
10552
10621
  const parts = [];
10553
10622
  const args = [];
@@ -10581,8 +10650,7 @@ function compileExpansionValue(expansion, parent, path, ctx) {
10581
10650
  whereParts.push(`${edge}.source_type_id = ?::text`);
10582
10651
  whereArgs.push(expansion.sourceObjectTypeId);
10583
10652
  }
10584
- const inner = `
10585
- SELECT ${child.sql} AS elem, row_number() OVER (ORDER BY ${order.sql}) AS _ord
10653
+ const from = `
10586
10654
  FROM ${ctx.source.linksTable} AS ${edge}
10587
10655
  JOIN ${ctx.source.objectsTable} AS ${target}
10588
10656
  ON ${target}.project_id = ${edge}.project_id
@@ -10590,17 +10658,21 @@ function compileExpansionValue(expansion, parent, path, ctx) {
10590
10658
  AND ${target}.primary_id = ${neighborId}
10591
10659
  WHERE ${whereParts.join(" AND ")}
10592
10660
  `;
10593
- const innerArgs = [...child.args, ...order.args, ...whereArgs];
10594
10661
  if (expansion.cardinality === "one") {
10595
10662
  return {
10596
- sql: `(SELECT ${ranked}.elem FROM (${inner}) AS ${ranked} WHERE ${ranked}._ord = 1)`,
10597
- args: innerArgs
10663
+ sql: `(SELECT ${child.sql} ${from} ORDER BY ${order.sql} LIMIT 1)`,
10664
+ args: [...child.args, ...whereArgs, ...order.args]
10598
10665
  };
10599
10666
  }
10600
10667
  const limit = expansion.limit ?? DEFAULT_EXPANSION_FANOUT;
10601
10668
  return {
10602
- sql: `COALESCE((SELECT jsonb_agg(${ranked}.elem ORDER BY ${ranked}._ord) FROM (${inner}) AS ${ranked} WHERE ${ranked}._ord <= ?), '[]'::jsonb)`,
10603
- args: [...innerArgs, limit]
10669
+ sql: `COALESCE((SELECT jsonb_agg(${ranked}.elem ORDER BY ${ranked}._ord) FROM (
10670
+ SELECT ${child.sql} AS elem, row_number() OVER (ORDER BY ${order.sql}) AS _ord
10671
+ ${from}
10672
+ ORDER BY ${order.sql}
10673
+ LIMIT ?
10674
+ ) AS ${ranked}), '[]'::jsonb)`,
10675
+ args: [...child.args, ...order.args, ...whereArgs, ...order.args, limit]
10604
10676
  };
10605
10677
  }
10606
10678
  function compileExpansionChildJson(expansion, edge, target, path, ctx) {
@@ -11392,6 +11464,308 @@ function isPlainObject(value) {
11392
11464
  return typeof value === "object" && value !== null && !Array.isArray(value);
11393
11465
  }
11394
11466
 
11467
+ // src/objects/query-indexes.ts
11468
+ async function ensurePgObjectQueryIndexes(sql, schema, indexes) {
11469
+ const definitions = indexes.map((index) => ({
11470
+ table: index.kind === "incomingLinks" ? "links" : "objects",
11471
+ expression: compileIndex(index),
11472
+ index
11473
+ }));
11474
+ if (indexes.some((index) => index.kind === "text")) {
11475
+ const [extension] = await sql`
11476
+ SELECT EXISTS (
11477
+ SELECT 1 FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace
11478
+ WHERE e.extname = 'pg_trgm' AND n.nspname = 'public'
11479
+ ) AS ready`;
11480
+ if (!extension?.ready) {
11481
+ throw new Error("[SixbPg] Text query indexes require pg_trgm in schema public. Run CREATE EXTENSION pg_trgm WITH SCHEMA public before ensuring indexes.");
11482
+ }
11483
+ }
11484
+ const names = [];
11485
+ await withReservedPgConnection(sql, async (connection) => {
11486
+ let connected = true;
11487
+ try {
11488
+ await lockPgPreparation(connection, `${schema}.objects.query-indexes`);
11489
+ for (const definition of definitions) {
11490
+ names.push(await createQueryIndex(connection, schema, definition));
11491
+ }
11492
+ await ensureExpressionStatistics(connection, schema, indexes);
11493
+ } catch (error) {
11494
+ connected = !isConnectionLost(error);
11495
+ throw error;
11496
+ } finally {
11497
+ if (connected)
11498
+ await connection`SELECT pg_advisory_unlock(hashtextextended(${`${schema}.objects.query-indexes`}, 0))`;
11499
+ }
11500
+ });
11501
+ return names;
11502
+ }
11503
+ async function createQueryIndex(connection, schema, definition) {
11504
+ const name = `sixb_query_${createHash3("sha256").update(definition.table === "objects" ? definition.expression : `${definition.table}:${definition.expression}`).digest("hex").slice(0, 32)}`;
11505
+ await connection.unsafe(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${identifier(name)} ON ${identifier(schema)}.${identifier(definition.table)} ${definition.expression}`);
11506
+ const [index] = await connection`
11507
+ SELECT i.indisvalid AS valid FROM pg_index i
11508
+ JOIN pg_class c ON c.oid = i.indexrelid
11509
+ JOIN pg_namespace n ON n.oid = c.relnamespace
11510
+ WHERE n.nspname = ${schema} AND c.relname = ${name}`;
11511
+ if (!index?.valid)
11512
+ throw new Error(`[SixbPg] Query index ${schema}.${name} is invalid after an interrupted build. Drop that index concurrently and retry ensureObjectQueryIndexes().`);
11513
+ if (definition.index.kind === "sort") {
11514
+ await connection.unsafe(`COMMENT ON INDEX ${identifier(schema)}.${identifier(name)} IS ${literal(JSON.stringify(definition.index))}`);
11515
+ const scope = `project_id = ${literal(definition.index.projectId)} AND object_type_id = ${literal(definition.index.objectTypeId)}`;
11516
+ await connection.unsafe(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${identifier(`${name}_overflow`)} ON ${identifier(schema)}.objects (primary_id) WHERE ${scope} AND NOT (${sortIndexBound(definition.index)})`);
11517
+ const superseded = await connection`
11518
+ SELECT c.relname AS name FROM pg_index i
11519
+ JOIN pg_class c ON c.oid = i.indexrelid
11520
+ JOIN pg_namespace n ON n.oid = c.relnamespace
11521
+ WHERE n.nspname = ${schema} AND c.relname LIKE 'sixb_query_%' AND c.relname <> ${name}
11522
+ AND obj_description(c.oid, 'pg_class') = ${JSON.stringify(definition.index)}`;
11523
+ for (const previous of superseded) {
11524
+ for (const index of [previous.name, `${previous.name}_overflow`]) {
11525
+ await connection.unsafe(`DROP INDEX CONCURRENTLY IF EXISTS ${identifier(schema)}.${identifier(index)}`);
11526
+ }
11527
+ }
11528
+ }
11529
+ return name;
11530
+ }
11531
+ async function ensureExpressionStatistics(connection, schema, indexes) {
11532
+ let statisticsChanged = false;
11533
+ const expressions = new Set(indexes.flatMap(statisticsExpressions));
11534
+ for (const expression of expressions) {
11535
+ const name = `sixb_query_stats_${createHash3("sha256").update(expression).digest("hex").slice(0, 24)}`;
11536
+ const [existing] = await connection`
11537
+ SELECT 1 FROM pg_statistic_ext s JOIN pg_namespace n ON n.oid = s.stxnamespace
11538
+ WHERE n.nspname = ${schema} AND s.stxname = ${name}`;
11539
+ if (existing)
11540
+ continue;
11541
+ await connection.unsafe(`CREATE STATISTICS ${identifier(schema)}.${identifier(name)} ON project_id, object_type_id, ${expression} FROM ${identifier(schema)}.objects`);
11542
+ statisticsChanged = true;
11543
+ }
11544
+ if (statisticsChanged)
11545
+ await connection.unsafe(`ANALYZE ${identifier(schema)}.objects`);
11546
+ }
11547
+ function statisticsExpressions(index) {
11548
+ if (index.kind === "incomingLinks")
11549
+ return [];
11550
+ const equality = new Set(Object.keys(index.where ?? {}));
11551
+ if (index.kind === "filter")
11552
+ for (const property of index.properties)
11553
+ equality.add(property);
11554
+ if (index.kind === "sort")
11555
+ for (const property of index.equality ?? [])
11556
+ equality.add(property);
11557
+ const expressions = [...equality].map((property) => `jsonb_typeof(properties -> ${literal(property)}), (properties ->> ${literal(property)}), (md5(properties ->> ${literal(property)}))`);
11558
+ if (index.kind === "value")
11559
+ expressions.push(`(properties -> ${literal(index.propertyId)})`);
11560
+ if (index.kind === "text")
11561
+ expressions.push(`lower(coalesce(properties ->> ${literal(index.propertyId)}, ''))`);
11562
+ if (index.kind === "sort")
11563
+ for (const field of index.fields)
11564
+ expressions.push(sortValue(field));
11565
+ return expressions;
11566
+ }
11567
+ function compileIndex(index) {
11568
+ if (index.kind === "incomingLinks") {
11569
+ if (index.where)
11570
+ throw new Error("[SixbPg] Incoming link indexes do not accept object property conditions");
11571
+ return `(target_id, link_id, source_type_id, source_id) INCLUDE (project_id, target_type_id) WHERE project_id = ${literal(index.projectId)} AND target_type_id = ${literal(index.objectTypeId)}`;
11572
+ }
11573
+ const predicate = [
11574
+ `project_id = ${literal(index.projectId)}`,
11575
+ `object_type_id = ${literal(index.objectTypeId)}`
11576
+ ];
11577
+ for (const [propertyId, value] of Object.entries(index.where ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
11578
+ const property = `properties -> ${literal(propertyId)}`;
11579
+ if (value === null)
11580
+ predicate.push(`jsonb_typeof(${property}) = 'null'`);
11581
+ else if (typeof value === "string") {
11582
+ predicate.push(`jsonb_typeof(${property}) = 'string'`, `properties ->> ${literal(propertyId)} = ${literal(value)}`, `md5(properties ->> ${literal(propertyId)}) = md5(${literal(value)})`);
11583
+ } else {
11584
+ if (typeof value === "number" && !Number.isFinite(value)) {
11585
+ throw new Error("[SixbPg] Query index conditions require finite numbers");
11586
+ }
11587
+ predicate.push(`${property} = ${literal(JSON.stringify(value))}::jsonb`);
11588
+ }
11589
+ }
11590
+ if (index.kind === "text") {
11591
+ return `USING gin (lower(coalesce(properties ->> ${literal(index.propertyId)}, '')) public.gin_trgm_ops) WHERE ${predicate.join(" AND ")}`;
11592
+ }
11593
+ const fields = [];
11594
+ if (index.kind === "count") {
11595
+ fields.push("project_id", "object_type_id");
11596
+ } else if (index.kind === "value") {
11597
+ fields.push(`(properties -> ${literal(index.propertyId)})`);
11598
+ }
11599
+ if (index.kind === "filter") {
11600
+ if (!index.properties.length || index.properties.length > 8)
11601
+ throw new Error("[SixbPg] A filter index requires one to eight string properties");
11602
+ for (const propertyId of index.properties)
11603
+ fields.push(`(md5(properties ->> ${literal(propertyId)}))`);
11604
+ }
11605
+ if (index.kind === "sort") {
11606
+ predicate.push(sortIndexBound(index));
11607
+ if (index.fields.length === 0 || index.fields.length + (index.equality?.length ?? 0) > 8) {
11608
+ throw new Error("[SixbPg] A sort query index requires between one and eight fields");
11609
+ }
11610
+ for (const propertyId of index.equality ?? []) {
11611
+ fields.push(`(properties ->> ${literal(propertyId)})`);
11612
+ }
11613
+ for (const field of index.fields) {
11614
+ const property = `properties -> ${literal(field.propertyId)}`;
11615
+ fields.push(`(CASE WHEN jsonb_typeof(${property}) IS NULL OR jsonb_typeof(${property}) = 'null' THEN 1 ELSE 0 END)`, `${sortValue(field)} ${field.direction === "desc" ? "DESC" : "ASC"}`);
11616
+ }
11617
+ fields.push("primary_id");
11618
+ }
11619
+ return `(${fields.join(", ")}) WHERE ${predicate.join(" AND ")}`;
11620
+ }
11621
+ function sortValue(field) {
11622
+ const text = `(properties ->> ${literal(field.propertyId)})`;
11623
+ if (field.scalarKind === "decimal")
11624
+ return `(${text}::numeric)`;
11625
+ if (isTextScalarKind(field.scalarKind))
11626
+ return `(${text} COLLATE "C")`;
11627
+ return `(NULLIF(properties -> ${literal(field.propertyId)}, 'null'::jsonb))`;
11628
+ }
11629
+ function literal(value) {
11630
+ if (value.includes("\x00"))
11631
+ throw new Error("[SixbPg] Query index names and values cannot contain NUL");
11632
+ return `E'${value.replace(/\\/g, "\\\\").replace(/'/g, "''")}'`;
11633
+ }
11634
+ function identifier(value) {
11635
+ return `"${value.replace(/"/g, '""')}"`;
11636
+ }
11637
+ function sortIndexBound(index) {
11638
+ const sizes = [
11639
+ "octet_length(primary_id)",
11640
+ ...index.fields.map((field) => `coalesce(octet_length((properties -> ${literal(field.propertyId)})::text), 0)`),
11641
+ ...(index.equality ?? []).map((property) => `coalesce(octet_length(properties ->> ${literal(property)}), 0)`)
11642
+ ];
11643
+ return `(${sizes.join(" + ")}) <= 1800`;
11644
+ }
11645
+ var SORT_INDEX_CATALOG_TTL_MS = 60000;
11646
+
11647
+ class PgSortIndexCatalog {
11648
+ #read;
11649
+ indexes(sql) {
11650
+ const now = Date.now();
11651
+ if (this.#read && now - this.#read.at < SORT_INDEX_CATALOG_TTL_MS)
11652
+ return this.#read.indexes;
11653
+ const read = { at: now, indexes: readPgSortIndexes(sql) };
11654
+ this.#read = read;
11655
+ read.indexes.catch(() => {
11656
+ if (this.#read === read)
11657
+ this.#read = undefined;
11658
+ });
11659
+ return read.indexes;
11660
+ }
11661
+ invalidate() {
11662
+ this.#read = undefined;
11663
+ }
11664
+ }
11665
+ async function readPgSortIndexes(sql) {
11666
+ const rows = await sql`
11667
+ SELECT d.description AS definition
11668
+ FROM pg_index i
11669
+ JOIN pg_class c ON c.oid = i.indexrelid
11670
+ JOIN pg_description d
11671
+ ON d.objoid = c.oid AND d.classoid = 'pg_class'::regclass AND d.objsubid = 0
11672
+ WHERE i.indrelid = 'objects'::regclass AND i.indisvalid
11673
+ AND c.relname LIKE 'sixb_query_%'
11674
+ `;
11675
+ const indexes = [];
11676
+ for (const row of rows) {
11677
+ let candidate;
11678
+ try {
11679
+ candidate = JSON.parse(row.definition);
11680
+ } catch {
11681
+ continue;
11682
+ }
11683
+ if (!candidate || typeof candidate !== "object")
11684
+ continue;
11685
+ if (candidate.kind === "sort")
11686
+ indexes.push(candidate);
11687
+ }
11688
+ return indexes;
11689
+ }
11690
+ async function findPgSortIndexBound(sql, catalog, projectId, query) {
11691
+ while (query.kind === "expand")
11692
+ query = query.input;
11693
+ if (query.kind !== "page" && query.kind !== "limit")
11694
+ return;
11695
+ let input = query.input;
11696
+ let fields;
11697
+ const equality = new Set;
11698
+ while (input.kind === "sort" || input.kind === "filter" || input.kind === "text") {
11699
+ if (input.kind === "sort") {
11700
+ if (fields)
11701
+ return;
11702
+ fields = input.fields;
11703
+ }
11704
+ if (input.kind === "filter") {
11705
+ const inspect = (predicate) => {
11706
+ if (predicate.op === "and")
11707
+ predicate.items.forEach(inspect);
11708
+ else if (predicate.op === "eq" && typeof predicate.value === "string")
11709
+ equality.add(predicate.propertyId);
11710
+ else if (predicate.op === "in" && predicate.values.length === 1 && typeof predicate.values[0] === "string")
11711
+ equality.add(predicate.propertyId);
11712
+ };
11713
+ inspect(input.predicate);
11714
+ }
11715
+ input = input.input;
11716
+ }
11717
+ let objectTypeId;
11718
+ if (input.kind === "start" && !input.includeSubtypes) {
11719
+ objectTypeId = input.objectTypeId;
11720
+ } else if (input.kind === "traverse" && input.direction === "incoming") {
11721
+ objectTypeId = input.sourceObjectTypeId;
11722
+ }
11723
+ if (!objectTypeId || !fields?.length || fields.some((field) => field.kind !== "property"))
11724
+ return;
11725
+ const matches = [];
11726
+ for (const index of await catalog.indexes(sql)) {
11727
+ if (index.projectId !== projectId || index.objectTypeId !== objectTypeId || index.where || !Array.isArray(index.fields) || index.fields.length !== fields.length)
11728
+ continue;
11729
+ if (index.equality !== undefined && (!Array.isArray(index.equality) || !index.equality.every((property) => typeof property === "string" && equality.has(property))))
11730
+ continue;
11731
+ if (!index.fields.every((field, i) => field && typeof field.propertyId === "string" && fields[i]?.kind === "property" && fields[i].propertyId === field.propertyId && (field.direction ?? "asc") === (fields[i].direction ?? "asc") && field.scalarKind === "decimal" === (fields[i].scalarKind === "decimal") && isTextScalarKind(field.scalarKind) === isTextScalarKind(fields[i].scalarKind)))
11732
+ continue;
11733
+ matches.push(index);
11734
+ }
11735
+ matches.sort((a, b) => (b.equality?.length ?? 0) - (a.equality?.length ?? 0));
11736
+ return matches[0] ? sortIndexBound(matches[0]) : undefined;
11737
+ }
11738
+ // src/objects/storage.ts
11739
+ import { hasVectorProfile as hasVectorProfile4 } from "@sixb/core/internal/query";
11740
+
11741
+ // src/objects/aggregate-admission.ts
11742
+ class PgAggregateAdmission {
11743
+ concurrency;
11744
+ active = 0;
11745
+ waiting = [];
11746
+ constructor(concurrency = 1) {
11747
+ this.concurrency = concurrency;
11748
+ }
11749
+ async run(compute) {
11750
+ if (this.active >= this.concurrency)
11751
+ await new Promise((resolve) => this.waiting.push(resolve));
11752
+ else
11753
+ this.active++;
11754
+ try {
11755
+ return await compute();
11756
+ } finally {
11757
+ const next = this.waiting.shift();
11758
+ if (next)
11759
+ next();
11760
+ else
11761
+ this.active--;
11762
+ }
11763
+ }
11764
+ }
11765
+
11766
+ // src/objects/conditional-reader.ts
11767
+ import { hasVectorProfile as hasVectorProfile3 } from "@sixb/core/internal/query";
11768
+
11395
11769
  // src/objects/read-scope.ts
11396
11770
  function compilePgSelectedObjectReadSource(projectId, scope, maxTraversalFacts) {
11397
11771
  const scopeJson = JSON.stringify({
@@ -11745,281 +12119,22 @@ function compileSelectedReadScopeCte(scopeJson, projectId) {
11745
12119
  stored.last_commit_id
11746
12120
  FROM links AS stored
11747
12121
  JOIN _sixb_scope_link_ids AS visible
11748
- ON visible.project_id = stored.project_id
11749
- AND visible.source_type_id = stored.source_type_id
11750
- AND visible.source_id = stored.source_id
11751
- AND visible.link_id = stored.link_id
11752
- AND visible.target_type_id = stored.target_type_id
11753
- AND visible.target_id = stored.target_id
11754
- )
11755
- `,
11756
- args: [scopeJson, projectId]
11757
- };
11758
- }
11759
-
11760
- // src/objects/reader.ts
11761
- import { ObjectQueryExecutionError as ObjectQueryExecutionError2 } from "@sixb/core";
11762
- import { hasVectorProfile as hasVectorProfile2 } from "@sixb/core/internal/query";
11763
- import { linkBatchKey, objectBatchKey } from "@sixb/core/storage";
11764
-
11765
- // src/objects/query-indexes.ts
11766
- import { createHash as createHash3 } from "crypto";
11767
-
11768
- // src/objects/preparation-lock.ts
11769
- async function lockPgPreparation(sql, key) {
11770
- let delay = 25;
11771
- while (true) {
11772
- const [row] = await sql`
11773
- SELECT pg_try_advisory_lock(hashtextextended(${key}, 0)) AS acquired`;
11774
- if (row?.acquired)
11775
- return;
11776
- await Bun.sleep(delay);
11777
- delay = Math.min(delay * 2, 500);
11778
- }
12122
+ ON visible.project_id = stored.project_id
12123
+ AND visible.source_type_id = stored.source_type_id
12124
+ AND visible.source_id = stored.source_id
12125
+ AND visible.link_id = stored.link_id
12126
+ AND visible.target_type_id = stored.target_type_id
12127
+ AND visible.target_id = stored.target_id
12128
+ )
12129
+ `,
12130
+ args: [scopeJson, projectId]
12131
+ };
11779
12132
  }
11780
12133
 
11781
- // src/objects/query-indexes.ts
11782
- async function ensurePgObjectQueryIndexes(sql, schema, indexes) {
11783
- const definitions = indexes.map((index) => ({
11784
- table: index.kind === "incomingLinks" ? "links" : "objects",
11785
- expression: compileIndex(index),
11786
- index
11787
- }));
11788
- if (indexes.some((index) => index.kind === "text")) {
11789
- const [extension] = await sql`
11790
- SELECT EXISTS (
11791
- SELECT 1 FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace
11792
- WHERE e.extname = 'pg_trgm' AND n.nspname = 'public'
11793
- ) AS ready`;
11794
- if (!extension?.ready) {
11795
- throw new Error("[SixbPg] Text query indexes require pg_trgm in schema public. Run CREATE EXTENSION pg_trgm WITH SCHEMA public before ensuring indexes.");
11796
- }
11797
- }
11798
- const names = [];
11799
- await withReservedPgConnection(sql, async (connection) => {
11800
- let connected = true;
11801
- try {
11802
- await lockPgPreparation(connection, `${schema}.objects.query-indexes`);
11803
- for (const definition of definitions) {
11804
- names.push(await createQueryIndex(connection, schema, definition));
11805
- }
11806
- await ensureExpressionStatistics(connection, schema, indexes);
11807
- } catch (error) {
11808
- connected = !isConnectionLost(error);
11809
- throw error;
11810
- } finally {
11811
- if (connected)
11812
- await connection`SELECT pg_advisory_unlock(hashtextextended(${`${schema}.objects.query-indexes`}, 0))`;
11813
- }
11814
- });
11815
- return names;
11816
- }
11817
- async function createQueryIndex(connection, schema, definition) {
11818
- const name = `sixb_query_${createHash3("sha256").update(definition.table === "objects" ? definition.expression : `${definition.table}:${definition.expression}`).digest("hex").slice(0, 32)}`;
11819
- await connection.unsafe(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${identifier(name)} ON ${identifier(schema)}.${identifier(definition.table)} ${definition.expression}`);
11820
- const [index] = await connection`
11821
- SELECT i.indisvalid AS valid FROM pg_index i
11822
- JOIN pg_class c ON c.oid = i.indexrelid
11823
- JOIN pg_namespace n ON n.oid = c.relnamespace
11824
- WHERE n.nspname = ${schema} AND c.relname = ${name}`;
11825
- if (!index?.valid)
11826
- throw new Error(`[SixbPg] Query index ${schema}.${name} is invalid after an interrupted build. Drop that index concurrently and retry ensureObjectQueryIndexes().`);
11827
- if (definition.index.kind === "sort") {
11828
- await connection.unsafe(`COMMENT ON INDEX ${identifier(schema)}.${identifier(name)} IS ${literal(JSON.stringify(definition.index))}`);
11829
- const scope = `project_id = ${literal(definition.index.projectId)} AND object_type_id = ${literal(definition.index.objectTypeId)}`;
11830
- await connection.unsafe(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${identifier(`${name}_overflow`)} ON ${identifier(schema)}.objects (primary_id) WHERE ${scope} AND NOT (${sortIndexBound(definition.index)})`);
11831
- const superseded = await connection`
11832
- SELECT c.relname AS name FROM pg_index i
11833
- JOIN pg_class c ON c.oid = i.indexrelid
11834
- JOIN pg_namespace n ON n.oid = c.relnamespace
11835
- WHERE n.nspname = ${schema} AND c.relname LIKE 'sixb_query_%' AND c.relname <> ${name}
11836
- AND obj_description(c.oid, 'pg_class') = ${JSON.stringify(definition.index)}`;
11837
- for (const previous of superseded) {
11838
- for (const index of [previous.name, `${previous.name}_overflow`]) {
11839
- await connection.unsafe(`DROP INDEX CONCURRENTLY IF EXISTS ${identifier(schema)}.${identifier(index)}`);
11840
- }
11841
- }
11842
- }
11843
- return name;
11844
- }
11845
- async function ensureExpressionStatistics(connection, schema, indexes) {
11846
- let statisticsChanged = false;
11847
- const expressions = new Set(indexes.flatMap(statisticsExpressions));
11848
- for (const expression of expressions) {
11849
- const name = `sixb_query_stats_${createHash3("sha256").update(expression).digest("hex").slice(0, 24)}`;
11850
- const [existing] = await connection`
11851
- SELECT 1 FROM pg_statistic_ext s JOIN pg_namespace n ON n.oid = s.stxnamespace
11852
- WHERE n.nspname = ${schema} AND s.stxname = ${name}`;
11853
- if (existing)
11854
- continue;
11855
- await connection.unsafe(`CREATE STATISTICS ${identifier(schema)}.${identifier(name)} ON project_id, object_type_id, ${expression} FROM ${identifier(schema)}.objects`);
11856
- statisticsChanged = true;
11857
- }
11858
- if (statisticsChanged)
11859
- await connection.unsafe(`ANALYZE ${identifier(schema)}.objects`);
11860
- }
11861
- function statisticsExpressions(index) {
11862
- if (index.kind === "incomingLinks")
11863
- return [];
11864
- const equality = new Set(Object.keys(index.where ?? {}));
11865
- if (index.kind === "filter")
11866
- for (const property of index.properties)
11867
- equality.add(property);
11868
- if (index.kind === "sort")
11869
- for (const property of index.equality ?? [])
11870
- equality.add(property);
11871
- const expressions = [...equality].map((property) => `jsonb_typeof(properties -> ${literal(property)}), (properties ->> ${literal(property)}), (md5(properties ->> ${literal(property)}))`);
11872
- if (index.kind === "value")
11873
- expressions.push(`(properties -> ${literal(index.propertyId)})`);
11874
- if (index.kind === "text")
11875
- expressions.push(`lower(coalesce(properties ->> ${literal(index.propertyId)}, ''))`);
11876
- if (index.kind === "sort")
11877
- for (const field of index.fields)
11878
- expressions.push(sortValue(field));
11879
- return expressions;
11880
- }
11881
- function compileIndex(index) {
11882
- if (index.kind === "incomingLinks") {
11883
- if (index.where)
11884
- throw new Error("[SixbPg] Incoming link indexes do not accept object property conditions");
11885
- return `(target_id, link_id, source_type_id, source_id) INCLUDE (project_id, target_type_id) WHERE project_id = ${literal(index.projectId)} AND target_type_id = ${literal(index.objectTypeId)}`;
11886
- }
11887
- const predicate = [
11888
- `project_id = ${literal(index.projectId)}`,
11889
- `object_type_id = ${literal(index.objectTypeId)}`
11890
- ];
11891
- for (const [propertyId, value] of Object.entries(index.where ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
11892
- const property = `properties -> ${literal(propertyId)}`;
11893
- if (value === null)
11894
- predicate.push(`jsonb_typeof(${property}) = 'null'`);
11895
- else if (typeof value === "string") {
11896
- predicate.push(`jsonb_typeof(${property}) = 'string'`, `properties ->> ${literal(propertyId)} = ${literal(value)}`, `md5(properties ->> ${literal(propertyId)}) = md5(${literal(value)})`);
11897
- } else {
11898
- if (typeof value === "number" && !Number.isFinite(value)) {
11899
- throw new Error("[SixbPg] Query index conditions require finite numbers");
11900
- }
11901
- predicate.push(`${property} = ${literal(JSON.stringify(value))}::jsonb`);
11902
- }
11903
- }
11904
- if (index.kind === "text") {
11905
- return `USING gin (lower(coalesce(properties ->> ${literal(index.propertyId)}, '')) public.gin_trgm_ops) WHERE ${predicate.join(" AND ")}`;
11906
- }
11907
- const fields = [];
11908
- if (index.kind === "count") {
11909
- fields.push("project_id", "object_type_id");
11910
- } else if (index.kind === "value") {
11911
- fields.push(`(properties -> ${literal(index.propertyId)})`);
11912
- }
11913
- if (index.kind === "filter") {
11914
- if (!index.properties.length || index.properties.length > 8)
11915
- throw new Error("[SixbPg] A filter index requires one to eight string properties");
11916
- for (const propertyId of index.properties)
11917
- fields.push(`(md5(properties ->> ${literal(propertyId)}))`);
11918
- }
11919
- if (index.kind === "sort") {
11920
- predicate.push(sortIndexBound(index));
11921
- if (index.fields.length === 0 || index.fields.length + (index.equality?.length ?? 0) > 8) {
11922
- throw new Error("[SixbPg] A sort query index requires between one and eight fields");
11923
- }
11924
- for (const propertyId of index.equality ?? []) {
11925
- fields.push(`(properties ->> ${literal(propertyId)})`);
11926
- }
11927
- for (const field of index.fields) {
11928
- const property = `properties -> ${literal(field.propertyId)}`;
11929
- fields.push(`(CASE WHEN jsonb_typeof(${property}) IS NULL OR jsonb_typeof(${property}) = 'null' THEN 1 ELSE 0 END)`, `${sortValue(field)} ${field.direction === "desc" ? "DESC" : "ASC"}`);
11930
- }
11931
- fields.push("primary_id");
11932
- }
11933
- return `(${fields.join(", ")}) WHERE ${predicate.join(" AND ")}`;
11934
- }
11935
- function sortValue(field) {
11936
- const text = `(properties ->> ${literal(field.propertyId)})`;
11937
- if (field.scalarKind === "decimal")
11938
- return `(${text}::numeric)`;
11939
- if (isTextScalarKind(field.scalarKind))
11940
- return `(${text} COLLATE "C")`;
11941
- return `(NULLIF(properties -> ${literal(field.propertyId)}, 'null'::jsonb))`;
11942
- }
11943
- function literal(value) {
11944
- if (value.includes("\x00"))
11945
- throw new Error("[SixbPg] Query index names and values cannot contain NUL");
11946
- return `E'${value.replace(/\\/g, "\\\\").replace(/'/g, "''")}'`;
11947
- }
11948
- function identifier(value) {
11949
- return `"${value.replace(/"/g, '""')}"`;
11950
- }
11951
- function sortIndexBound(index) {
11952
- const sizes = [
11953
- "octet_length(primary_id)",
11954
- ...index.fields.map((field) => `coalesce(octet_length((properties -> ${literal(field.propertyId)})::text), 0)`),
11955
- ...(index.equality ?? []).map((property) => `coalesce(octet_length(properties ->> ${literal(property)}), 0)`)
11956
- ];
11957
- return `(${sizes.join(" + ")}) <= 1800`;
11958
- }
11959
- async function findPgSortIndexBound(sql, projectId, query) {
11960
- while (query.kind === "expand")
11961
- query = query.input;
11962
- if (query.kind !== "page" && query.kind !== "limit")
11963
- return;
11964
- let input = query.input;
11965
- let fields;
11966
- const equality = new Set;
11967
- while (input.kind === "sort" || input.kind === "filter" || input.kind === "text") {
11968
- if (input.kind === "sort") {
11969
- if (fields)
11970
- return;
11971
- fields = input.fields;
11972
- }
11973
- if (input.kind === "filter") {
11974
- const inspect = (predicate) => {
11975
- if (predicate.op === "and")
11976
- predicate.items.forEach(inspect);
11977
- else if (predicate.op === "eq" && typeof predicate.value === "string")
11978
- equality.add(predicate.propertyId);
11979
- else if (predicate.op === "in" && predicate.values.length === 1 && typeof predicate.values[0] === "string")
11980
- equality.add(predicate.propertyId);
11981
- };
11982
- inspect(input.predicate);
11983
- }
11984
- input = input.input;
11985
- }
11986
- let objectTypeId;
11987
- if (input.kind === "start" && !input.includeSubtypes) {
11988
- objectTypeId = input.objectTypeId;
11989
- } else if (input.kind === "traverse" && input.direction === "incoming") {
11990
- objectTypeId = input.sourceObjectTypeId;
11991
- }
11992
- if (!objectTypeId || !fields?.length || fields.some((field) => field.kind !== "property"))
11993
- return;
11994
- const rows = await sql`
11995
- SELECT obj_description(c.oid, 'pg_class') AS definition
11996
- FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
11997
- WHERE i.indrelid = 'objects'::regclass AND i.indisvalid
11998
- AND c.relname LIKE 'sixb_query_%'
11999
- AND obj_description(c.oid, 'pg_class') IS NOT NULL
12000
- `;
12001
- const matches = [];
12002
- for (const row of rows) {
12003
- let candidate;
12004
- try {
12005
- candidate = JSON.parse(row.definition);
12006
- } catch {
12007
- continue;
12008
- }
12009
- if (!candidate || typeof candidate !== "object")
12010
- continue;
12011
- const index = candidate;
12012
- if (index.kind !== "sort" || index.projectId !== projectId || index.objectTypeId !== objectTypeId || index.where || !Array.isArray(index.fields) || index.fields.length !== fields.length)
12013
- continue;
12014
- if (index.equality !== undefined && (!Array.isArray(index.equality) || !index.equality.every((property) => typeof property === "string" && equality.has(property))))
12015
- continue;
12016
- if (!index.fields.every((field, i) => field && typeof field.propertyId === "string" && fields[i]?.kind === "property" && fields[i].propertyId === field.propertyId && (field.direction ?? "asc") === (fields[i].direction ?? "asc") && field.scalarKind === "decimal" === (fields[i].scalarKind === "decimal") && isTextScalarKind(field.scalarKind) === isTextScalarKind(fields[i].scalarKind)))
12017
- continue;
12018
- matches.push(index);
12019
- }
12020
- matches.sort((a, b) => (b.equality?.length ?? 0) - (a.equality?.length ?? 0));
12021
- return matches[0] ? sortIndexBound(matches[0]) : undefined;
12022
- }
12134
+ // src/objects/reader.ts
12135
+ import { ObjectQueryExecutionError as ObjectQueryExecutionError2 } from "@sixb/core";
12136
+ import { hasVectorProfile as hasVectorProfile2 } from "@sixb/core/internal/query";
12137
+ import { linkBatchKey, objectBatchKey } from "@sixb/core/storage";
12023
12138
 
12024
12139
  // src/objects/rows.ts
12025
12140
  function rowToObject(row) {
@@ -12404,10 +12519,12 @@ class PgObjectReader {
12404
12519
  sql;
12405
12520
  source;
12406
12521
  aggregateAdmission;
12407
- constructor(sql, source, aggregateAdmission) {
12522
+ sortIndexes;
12523
+ constructor(sql, source, aggregateAdmission, sortIndexes) {
12408
12524
  this.sql = sql;
12409
12525
  this.source = source;
12410
12526
  this.aggregateAdmission = aggregateAdmission;
12527
+ this.sortIndexes = sortIndexes;
12411
12528
  }
12412
12529
  async assertVectorSearch(params) {
12413
12530
  if (!hasVectorProfile2(params.query))
@@ -12447,7 +12564,7 @@ class PgObjectReader {
12447
12564
  async compilePageQuery(params) {
12448
12565
  const sql = this.sql;
12449
12566
  const source = this.source;
12450
- const sortIndexBound = source === DEFAULT_OBJECT_QUERY_SOURCE ? await findPgSortIndexBound(sql, params.projectId, params.query) : undefined;
12567
+ const sortIndexBound = source === DEFAULT_OBJECT_QUERY_SOURCE && this.sortIndexes ? await findPgSortIndexBound(sql, this.sortIndexes, params.projectId, params.query) : undefined;
12451
12568
  let compiled = compilePgObjectQuery(params.projectId, params.query, {
12452
12569
  sortIndexBound,
12453
12570
  includeTotal: params.includeTotal,
@@ -13089,12 +13206,14 @@ var PG_OBJECT_QUERY_CAPABILITIES = {
13089
13206
 
13090
13207
  class PgObjectStorage {
13091
13208
  sql;
13209
+ sortIndexes;
13092
13210
  aggregateAdmission;
13093
13211
  reader;
13094
- constructor(sql, maxConcurrentAggregates = 1) {
13212
+ constructor(sql, sortIndexes = new PgSortIndexCatalog, maxConcurrentAggregates = 1) {
13095
13213
  this.sql = sql;
13214
+ this.sortIndexes = sortIndexes;
13096
13215
  this.aggregateAdmission = canStartPgTransaction(sql) ? new PgAggregateAdmission(maxConcurrentAggregates) : undefined;
13097
- this.reader = new PgObjectReader(sql, DEFAULT_OBJECT_QUERY_SOURCE, this.aggregateAdmission);
13216
+ this.reader = new PgObjectReader(sql, DEFAULT_OBJECT_QUERY_SOURCE, this.aggregateAdmission, sortIndexes);
13098
13217
  }
13099
13218
  queryCapabilities() {
13100
13219
  return PG_OBJECT_QUERY_CAPABILITIES;
@@ -13110,7 +13229,7 @@ class PgObjectStorage {
13110
13229
  }
13111
13230
  async queryObjects(params) {
13112
13231
  if (hasVectorProfile4(params.query))
13113
- return runPgRepeatableReadTransaction(this.sql, (tx) => new PgObjectReader(tx, DEFAULT_OBJECT_QUERY_SOURCE).queryObjects(params));
13232
+ return runPgRepeatableReadTransaction(this.sql, (tx) => new PgObjectReader(tx, DEFAULT_OBJECT_QUERY_SOURCE, undefined, this.sortIndexes).queryObjects(params));
13114
13233
  return this.reader.queryObjects(params);
13115
13234
  }
13116
13235
  async countObjects(params) {
@@ -23874,6 +23993,7 @@ class PostgresStorage {
23874
23993
  schemaName;
23875
23994
  shutdownTimeoutSeconds;
23876
23995
  transactionScope = new AsyncLocalStorage;
23996
+ sortIndexes = new PgSortIndexCatalog;
23877
23997
  constructor(options) {
23878
23998
  if (options.maxConcurrentAggregates !== undefined && (!Number.isSafeInteger(options.maxConcurrentAggregates) || options.maxConcurrentAggregates < 1))
23879
23999
  throw new Error("[SixbPg] maxConcurrentAggregates must be a positive integer");
@@ -23897,6 +24017,7 @@ class PostgresStorage {
23897
24017
  });
23898
24018
  this.migrators = createPostgresStorageMigrators(this.sql, this.schemaName);
23899
24019
  const stores = createPostgresStores(this.sql, {
24020
+ sortIndexes: this.sortIndexes,
23900
24021
  maxConcurrentAggregates: options.maxConcurrentAggregates,
23901
24022
  runOntologyOperation: (run) => runPgTransaction(this.sql, run),
23902
24023
  transactionContext: null
@@ -23970,11 +24091,19 @@ class PostgresStorage {
23970
24091
  }
23971
24092
  async prepareObjectQueries(plan) {
23972
24093
  this.assertRootOperationAvailable();
23973
- return preparePgObjectQueries(this.sql, this.schemaName, plan);
24094
+ try {
24095
+ return await preparePgObjectQueries(this.sql, this.schemaName, plan);
24096
+ } finally {
24097
+ this.sortIndexes.invalidate();
24098
+ }
23974
24099
  }
23975
24100
  async ensureObjectQueryIndexes(indexes) {
23976
24101
  this.assertRootOperationAvailable();
23977
- return ensurePgObjectQueryIndexes(this.sql, this.schemaName, indexes);
24102
+ try {
24103
+ return await ensurePgObjectQueryIndexes(this.sql, this.schemaName, indexes);
24104
+ } finally {
24105
+ this.sortIndexes.invalidate();
24106
+ }
23978
24107
  }
23979
24108
  async prepareObjectTextCounts(indexes) {
23980
24109
  this.assertRootOperationAvailable();
@@ -23994,6 +24123,7 @@ class PostgresStorage {
23994
24123
  createTransactionStorage(client, transactionContext) {
23995
24124
  return {
23996
24125
  ...createPostgresStores(client, {
24126
+ sortIndexes: this.sortIndexes,
23997
24127
  runOntologyOperation: async (run) => run(client),
23998
24128
  transactionContext
23999
24129
  }),
@@ -24012,7 +24142,7 @@ function createPostgresStores(sql, options) {
24012
24142
  const shareSessions = new PgShareSessionStorage(sql);
24013
24143
  const executions = new PgExecutionStorage(sql, auth, shareSessions);
24014
24144
  return {
24015
- objects: new PgObjectStorage(sql, options.maxConcurrentAggregates),
24145
+ objects: new PgObjectStorage(sql, options.sortIndexes, options.maxConcurrentAggregates),
24016
24146
  ontology: new PgOntologyStorage({
24017
24147
  sql,
24018
24148
  runRootOperation: options.runOntologyOperation,
@@ -24056,4 +24186,4 @@ export {
24056
24186
  migratePostgresStorage
24057
24187
  };
24058
24188
 
24059
- //# debugId=870DEE018612039C64756E2164756E21
24189
+ //# debugId=E730661135685C6D64756E2164756E21