Skip to content

feat!: read a hypertable through a time bound - #39

Open
systemfsoftware-bot wants to merge 3 commits into
mainfrom
feat-bounded-reads
Open

systemfsoftware-bot wants to merge 3 commits into
mainfrom
feat-bounded-reads

Conversation

@systemfsoftware-bot

@systemfsoftware-bot systemfsoftware-bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

A query on a hypertable that names no time range plans every chunk and takes an AccessShareLock on each chunk and its indexes. At a few thousand chunks, one ORDER BY time DESC LIMIT 1 exhausts max_locks_per_transaction (SQLSTATE 53200). This makes the bounded read the only read the types allow.

API

const window = metricsHypertable.within({ gte: start, lt: end })
const rows = await db.select({ v: window.value }).from(window).where(eq(window.symbol, 'x'))

const newest = await metricsHypertable.latest(db, { where: (w) => eq(w.symbol, 'x'), maxLookbackChunks: 64 })
// { found: true, row } | { found: false, searchedFrom }

metricsHypertable.unsafeUnbounded() // the plain Drizzle table, for migrations and admin code
  • within({ gte, lt }) returns a Drizzle Subquery, not a pre-filtered builder: chaining .where() on a builder replaces the earlier one, so a caller could erase the bound. Date bounds are written as timestamptz literals, not $n, so chunk exclusion is plan-time even in a generic prepared plan; a column/table/subquery bound is refused (type and runtime). The generated SQL:
    select "time", "v" from (select "time", "v" from "m" where (("m"."time" >= '2026-01-01T00:00:00.000Z'::timestamptz) and ("m"."time" < '2026-01-02T00:00:00.000Z'::timestamptz))) "m"
  • latest probes [until-2i, until) first (until defaults to one minute past now), then windows four times wider going back, up to maxLookbackChunks intervals in total (i is chunkTimeInterval, 7 days when unset). With a 14-day interval the captured probes span 28, 112 and 448 days, newest first. A steady-state caller finds its row on the first probe. The result is tagged so "nothing recent" is not confused with "nothing".
  • unsafeUnbounded() is the named escape hatch an app can ban with a lint rule.
  • continuousAggregate(view, { bucketColumn }) gives an aggregate the same within and unsafeUnbounded. A continuous aggregate's materialization is a hypertable, so an unbounded read locks all of its chunks too. An aggregate declared without bucketColumn, or by name, has no within.
  • The hypertable's table and the aggregate's view are no longer public properties (breaking).

The compiler is the evidence (final diff)

Scratch file importing the package source, removed after the run:

export const bad  = new QueryBuilder().select().from(ht)                              // line 6
export const good = new QueryBuilder().select().from(ht.within({ gte: new Date(0), lt: new Date(1) }))
export const expr = ht.within({ gte: sql`now() - interval '1 day'`, lt: sql`now()` })
export const col  = ht.within({ gte: m.at, lt: new Date() })                          // line 9

tsc reports exactly two errors, on lines 6 and 9:

proof.ts(6,53): error TS2345: Argument of type 'Hypertable<PgTableWithColumns<{ name: "m"; ... }>, ...>' is not assignable to parameter of type 'PgTable<TableConfig> | SQL<unknown> | Subquery<string, Record<string, unknown>> | PgViewBase<ViewConfig<ColumnsSelection>>'.
proof.ts(9,32): error TS2322: Type 'PgBuildColumn<"m", SetNotNull<PgTimestampBuilder>, {...}>' is not assignable to type 'BoundExpression | Date'.

Limit

The types guard what the app imports. The app still has to export the Drizzle table for drizzle-kit, and db.select().from(thatTable) compiles. Keep the table in a schema module and import only the hypertable in application code, and ban unsafeUnbounded outside migrations.

Review

Gemini adversarial review found five P0s; fixed: literal Date bounds (plan-time exclusion), column bounds refused, per-bound validation, finite-range checks in latest, latest accepts any drizzle db. A continuous aggregate must be declared over .existing() views (as before); .as()-built views are not supported by bucketColumn.

P1s from the review that were not taken: single-query shortcut when where is absent (the first probe already hits in steady state), interval parsing (intervals are validated to N unit form before they reach it), and exporting the internal relation accessors.

hypertable() returns a declaration that is not a Drizzle table, so
db.select().from(hypertable) does not compile. within({ gte, lt }) returns a
Drizzle subquery with the time bound written into it, latest() finds the newest
row with probes that widen from the chunk interval, and unsafeUnbounded()
returns the plain table for migrations and admin code. A continuous aggregate
declared over a view with a bucketColumn gets the same within.

BREAKING CHANGE: the table property of a hypertable and the view property of a
continuous aggregate are no longer public.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant