@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.
@@ -271,10 +271,70 @@ export function sortIndexBound(index: Extract<PgObjectQueryIndex, { kind: "sort"
271
271
  return `(${sizes.join(" + ")}) <= 1800`
272
272
  }
273
273
 
274
+ type PgSortIndex = Extract<PgObjectQueryIndex, { kind: "sort" }>
275
+
276
+ // How long a read of the prepared sort indexes serves queries before the catalog is read again.
277
+ const SORT_INDEX_CATALOG_TTL_MS = 60_000
278
+
279
+ /**
280
+ * The prepared sort indexes of one schema, read from their catalog comments at most once a minute.
281
+ *
282
+ * The read costs more than many of the queries it serves, so queries share one per minute.
283
+ * A stale read cannot change a result: the bounded read and its overflow branch together cover
284
+ * every row whether or not the index exists, so an index prepared since the last read is only
285
+ * used a little later. Preparing in this process refreshes at once.
286
+ */
287
+ export class PgSortIndexCatalog {
288
+ #read: { readonly at: number; readonly indexes: Promise<readonly PgSortIndex[]> } | undefined
289
+
290
+ /** Read through the caller's client, so a transaction never waits for a second connection. */
291
+ indexes(sql: SQLClient): Promise<readonly PgSortIndex[]> {
292
+ const now = Date.now()
293
+ if (this.#read && now - this.#read.at < SORT_INDEX_CATALOG_TTL_MS) return this.#read.indexes
294
+ const read = { at: now, indexes: readPgSortIndexes(sql) }
295
+ this.#read = read
296
+ // A failed read is not kept: the next query reads again.
297
+ read.indexes.catch(() => {
298
+ if (this.#read === read) this.#read = undefined
299
+ })
300
+ return read.indexes
301
+ }
302
+
303
+ invalidate(): void {
304
+ this.#read = undefined
305
+ }
306
+ }
307
+
308
+ async function readPgSortIndexes(sql: SQLClient): Promise<readonly PgSortIndex[]> {
309
+ // Joins pg_description directly: calling obj_description() for every index is far slower.
310
+ const rows = await sql<{ definition: string }[]>`
311
+ SELECT d.description AS definition
312
+ FROM pg_index i
313
+ JOIN pg_class c ON c.oid = i.indexrelid
314
+ JOIN pg_description d
315
+ ON d.objoid = c.oid AND d.classoid = 'pg_class'::regclass AND d.objsubid = 0
316
+ WHERE i.indrelid = 'objects'::regclass AND i.indisvalid
317
+ AND c.relname LIKE 'sixb_query_%'
318
+ `
319
+ const indexes: PgSortIndex[] = []
320
+ for (const row of rows) {
321
+ let candidate: unknown
322
+ try {
323
+ candidate = JSON.parse(row.definition)
324
+ } catch {
325
+ continue
326
+ }
327
+ if (!candidate || typeof candidate !== "object") continue
328
+ if ((candidate as Partial<PgSortIndex>).kind === "sort") indexes.push(candidate as PgSortIndex)
329
+ }
330
+ return indexes
331
+ }
332
+
274
333
  /** Only split a flat, bounded ordered read; joins, nested limits and projections keep the
275
334
  * general compiler. Its unrestricted fallback always preserves semantics. */
276
335
  export async function findPgSortIndexBound(
277
336
  sql: SQLClient,
337
+ catalog: PgSortIndexCatalog,
278
338
  projectId: string,
279
339
  query: ObjectQuery
280
340
  ): Promise<string | undefined> {
@@ -314,26 +374,10 @@ export async function findPgSortIndexBound(
314
374
  if (!objectTypeId || !fields?.length || fields.some((field) => field.kind !== "property"))
315
375
  return undefined
316
376
 
317
- const rows = await sql<{ definition: string }[]>`
318
- SELECT obj_description(c.oid, 'pg_class') AS definition
319
- FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
320
- WHERE i.indrelid = 'objects'::regclass AND i.indisvalid
321
- AND c.relname LIKE 'sixb_query_%'
322
- AND obj_description(c.oid, 'pg_class') IS NOT NULL
323
- `
324
- const matches: Extract<PgObjectQueryIndex, { kind: "sort" }>[] = []
325
- for (const row of rows) {
326
- let candidate: unknown
327
- try {
328
- candidate = JSON.parse(row.definition)
329
- } catch {
330
- continue
331
- }
332
- if (!candidate || typeof candidate !== "object") continue
377
+ const matches: PgSortIndex[] = []
378
+ for (const index of await catalog.indexes(sql)) {
333
379
  // Metadata is generated by this module. Verify all SQL-interpolated members before using it.
334
- const index = candidate as Partial<Extract<PgObjectQueryIndex, { kind: "sort" }>>
335
380
  if (
336
- index.kind !== "sort" ||
337
381
  index.projectId !== projectId ||
338
382
  index.objectTypeId !== objectTypeId ||
339
383
  index.where ||
@@ -360,7 +404,7 @@ export async function findPgSortIndexBound(
360
404
  )
361
405
  )
362
406
  continue
363
- matches.push(index as Extract<PgObjectQueryIndex, { kind: "sort" }>)
407
+ matches.push(index)
364
408
  }
365
409
  matches.sort((a, b) => (b.equality?.length ?? 0) - (a.equality?.length ?? 0))
366
410
  return matches[0] ? sortIndexBound(matches[0]) : undefined
@@ -32,7 +32,7 @@ import {
32
32
  type PgObjectQuerySource,
33
33
  pgObjectsOfType,
34
34
  } from "./query-compiler"
35
- import { findPgSortIndexBound } from "./query-indexes"
35
+ import { findPgSortIndexBound, type PgSortIndexCatalog } from "./query-indexes"
36
36
  import type { PgSelectedObjectReadSource } from "./read-scope"
37
37
  import {
38
38
  type FacetDatabaseRow,
@@ -54,7 +54,8 @@ export class PgObjectReader {
54
54
  constructor(
55
55
  private readonly sql: SQLClient,
56
56
  private readonly source: PgObjectQuerySource | PgSelectedObjectReadSource,
57
- private readonly aggregateAdmission?: PgAggregateAdmission
57
+ private readonly aggregateAdmission?: PgAggregateAdmission,
58
+ private readonly sortIndexes?: PgSortIndexCatalog
58
59
  ) {}
59
60
 
60
61
  private async assertVectorSearch(
@@ -115,8 +116,8 @@ export class PgObjectReader {
115
116
  const sql = this.sql
116
117
  const source = this.source
117
118
  const sortIndexBound =
118
- source === DEFAULT_OBJECT_QUERY_SOURCE
119
- ? await findPgSortIndexBound(sql, params.projectId, params.query)
119
+ source === DEFAULT_OBJECT_QUERY_SOURCE && this.sortIndexes
120
+ ? await findPgSortIndexBound(sql, this.sortIndexes, params.projectId, params.query)
120
121
  : undefined
121
122
  let compiled = compilePgObjectQuery(params.projectId, params.query, {
122
123
  sortIndexBound,
@@ -31,6 +31,7 @@ import {
31
31
  import { PgAggregateAdmission } from "./aggregate-admission"
32
32
  import { createPgConditionalReader } from "./conditional-reader"
33
33
  import { DEFAULT_OBJECT_QUERY_SOURCE } from "./query-compiler"
34
+ import { PgSortIndexCatalog } from "./query-indexes"
34
35
  import { assertLinkQueryLimit, PgObjectReader } from "./reader"
35
36
  import {
36
37
  type LinkDatabaseRow,
@@ -118,12 +119,18 @@ export class PgObjectStorage implements ObjectStorage {
118
119
 
119
120
  constructor(
120
121
  private readonly sql: PgStoreClient,
122
+ private readonly sortIndexes = new PgSortIndexCatalog(),
121
123
  maxConcurrentAggregates = 1
122
124
  ) {
123
125
  this.aggregateAdmission = canStartPgTransaction(sql)
124
126
  ? new PgAggregateAdmission(maxConcurrentAggregates)
125
127
  : undefined
126
- this.reader = new PgObjectReader(sql, DEFAULT_OBJECT_QUERY_SOURCE, this.aggregateAdmission)
128
+ this.reader = new PgObjectReader(
129
+ sql,
130
+ DEFAULT_OBJECT_QUERY_SOURCE,
131
+ this.aggregateAdmission,
132
+ sortIndexes
133
+ )
127
134
  }
128
135
 
129
136
  queryCapabilities(): ObjectQueryCapabilities {
@@ -151,7 +158,12 @@ export class PgObjectStorage implements ObjectStorage {
151
158
  async queryObjects(params: QueryObjectsInput): Promise<QueryObjectsResult> {
152
159
  if (hasVectorProfile(params.query))
153
160
  return runPgRepeatableReadTransaction(this.sql, (tx) =>
154
- new PgObjectReader(tx, DEFAULT_OBJECT_QUERY_SOURCE).queryObjects(params)
161
+ new PgObjectReader(
162
+ tx,
163
+ DEFAULT_OBJECT_QUERY_SOURCE,
164
+ undefined,
165
+ this.sortIndexes
166
+ ).queryObjects(params)
155
167
  )
156
168
  return this.reader.queryObjects(params)
157
169
  }
package/src/pg-client.ts CHANGED
@@ -137,10 +137,10 @@ type DirectTlsVerification = "none" | "ca" | "full"
137
137
 
138
138
  // `sslnegotiation=direct` is read from the connection string, as libpq reads it. Without it,
139
139
  // porsager negotiates TLS the classic way: an SSLRequest on a plain TCP socket, then an upgrade of
140
- // that socket with `tls.connect({ socket })`. Bun 1.4.0–1.4.2 keeps every byte received on such an
141
- // upgraded socket in memory for good, so a process that reads a lot grows until it is killed.
142
- // Opening the TLS connection ourselves with `tls.connect({ host, port })` avoids that path, and
143
- // saves the SSLRequest round trip on every connection.
140
+ // that socket with `tls.connect({ socket })`. Opening the TLS connection ourselves with
141
+ // `tls.connect({ host, port })` saves the SSLRequest round trip on every connection. It also
142
+ // avoids a Bun 1.4.0–1.4.2 bug (fixed by 1.4.4) that keeps every byte received on an upgraded
143
+ // socket in memory for good, so a process that reads a lot grows until it is killed.
144
144
  function tlsOptions(options: CreatePgClientOptions): Record<string, unknown> {
145
145
  const verification = directTlsVerification(options)
146
146
  if (verification === null) {