From 73ada89a13ed8ecff4c8b2f6cae6de298f2ac52e Mon Sep 17 00:00:00 2001 From: Julian Cuni Date: Sat, 24 Oct 2026 11:17:30 +0200 Subject: [PATCH] fix(server): bound active-sessions cost, index hot paths, no phantom relay timeouts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit park-2 (2026-10-24): GET /api/sessions/active ran ~2 s synchronously — PayStation.activeSessions called quote() per open unpaid transient (664 rows), each 3-4 unindexed ledger_events scans by identity — 2234x/day. The frozen event loop made the Dingtian driver's 2 s timer fire before the already-received UDP reply (timers run before poll I/O), so healthy pulses logged "timeout"; the subscription flow then unwound before firing the camera or writing the sessions row, leaving signed entries with no snapshot. Cost grew ~120 ms/day with the operator's open-ticket count. - pay-station: price every list row from the one ledger scan (rows grouped per identity -> #quoteFromRows); tariff resolver built once per request; quote(identity) wraps the same core. validations: sessionValidationsFromRows / liveValidationsFromRows. Test pins list == quote(). - db 0032_hot_path_indexes: ledger_events(identity,index), device_events(category,kind, occurred_at), device_events(kind,occurred_at), snapshots(identity), sessions(state), sessions(subscription_id,state). Additive. - access-dingtian binaryUdp: defer the timeout rejection with setImmediate so a datagram that already arrived wins over an expired timer. - subscription-flow: snapshot fired and session cache written/closed BEFORE the pulse. wiki/concepts/park-2-event-loop-stall.md has the full analysis. --- apps/server/src/pay-station.test.ts | 21 +++++ apps/server/src/pay-station.ts | 76 ++++++++++++++----- apps/server/src/subscription-flow.ts | 17 +++-- apps/server/src/validations.ts | 21 +++++ packages/db/drizzle/0032_hot_path_indexes.sql | 18 +++++ packages/db/drizzle/meta/_journal.json | 7 ++ .../devices/src/drivers/access-dingtian.ts | 8 +- 7 files changed, 142 insertions(+), 26 deletions(-) create mode 100644 packages/db/drizzle/0032_hot_path_indexes.sql diff --git a/apps/server/src/pay-station.test.ts b/apps/server/src/pay-station.test.ts index 159d43a..26ea81d 100644 --- a/apps/server/src/pay-station.test.ts +++ b/apps/server/src/pay-station.test.ts @@ -152,4 +152,25 @@ describe("PayStation.activeSessions", () => { expect(list.map((s) => s.identity)).toEqual(["NEW", "OLD"]); expect(list.every((s) => s.open)).toBe(true); }); + + // The list prices each open transient from ONE whole-ledger scan (no per-row ledger + // reads — those froze park-2's server, 2026-10-24). The amounts must match the + // single-session quote() exactly, including after a payment (overstay repricing) and + // for a subscription (never quoted). + it("prices every row identically to quote() without per-session ledger reads", async () => { + seedTariff(db, { pricePerIncrementMinor: 10000, incrementMin: 60, gracePeriodExitMin: 0 }); + await enter("UNPAID", minutesAgo(150)); + await enter("PAID", minutesAgo(300)); + await pay.pay("PAID", "cash"); // grace 0 → paid-but-open ⇒ overstay, re-priced from now + await enter("SUB", minutesAgo(10), { permit: true, permitId: "sub-1" }); + + const list = pay.activeSessions(); + const by = new Map(list.map((s) => [s.identity, s])); + expect(by.get("UNPAID")!.amountMinor).toBe(pay.quote("UNPAID").amountMinor); + expect(by.get("UNPAID")!.currency).toBe(pay.quote("UNPAID").currency); + expect(by.get("PAID")!.overstay).toBe(true); + expect(by.get("PAID")!.amountMinor).toBe(pay.quote("PAID").amountMinor); + expect(by.get("SUB")!.subscription).toBe(true); + expect(by.get("SUB")!.amountMinor).toBeNull(); + }); }); diff --git a/apps/server/src/pay-station.ts b/apps/server/src/pay-station.ts index 0105ace..aad1275 100644 --- a/apps/server/src/pay-station.ts +++ b/apps/server/src/pay-station.ts @@ -4,7 +4,13 @@ import type { FastifyBaseLogger } from "fastify"; import type { EventLog } from "./event-log.js"; import { plateForIdentity, platesForIdentities } from "./plate-lookup.js"; import { windowOwedBetween } from "./subscription-window.js"; -import { liveValidations } from "./validations.js"; +import { liveValidationsFromRows } from "./validations.js"; + +/** A `ledger_events` row as the pricing fold reads it. */ +type LedgerRow = typeof ledgerEvents.$inferSelect; +/** Resolves the tariff version in force at an instant. Built once per request so a list + * view does not re-read the tariff tables for every row. */ +type TariffResolver = (at: string) => typeof tariffVersions.$inferSelect | null; // The PAY STATION: a customer pays for an open session BEFORE walking back to the // car (pay-on-foot — payment is decoupled from exit). Two steps: @@ -200,12 +206,23 @@ export class PayStation { * 0 and a multi-day overstay would exit free (ticket 1245791632490). A new period * reflects the reality and re-accrues the fee. No side effect. */ quote(identity: string): Quote { - const entry = this.#openEntry(identity); + return this.#quoteFromRows(identity, this.#identityRows(identity), this.#tariffResolver()); + } + + /** `quote` over the identity's ledger rows the caller already holds (oldest first) and + * a prebuilt tariff resolver. The single-session `quote()` wraps this with one + * identity-scoped read; `activeSessions()` feeds it per-identity groups of ONE whole- + * ledger scan. Both paths MUST price identically — pinned by pay-station.test.ts. + * Why: the list view used to call `quote()` per open unpaid row, each doing 3–4 + * ledger scans; with ~660 such rows at park-2 the synchronous handler ran ~2 s and + * froze the event loop — relay replies then "timed out" (2026-10-24). */ + #quoteFromRows(identity: string, rows: readonly LedgerRow[], tariffFor: TariffResolver): Quote { + const entry = PayStation.#openEntryFromRows(rows); if (!entry) throw new NoOpenSessionError(identity); // The tariff in force is keyed to ENTRY (the version frozen for this session), even // for an overstay period — the customer keeps the rate card they entered under. - const tv = this.#tariffVersionFor(entry.occurredAt); + const tv = tariffFor(entry.occurredAt); if (!tv) throw new NoTariffError(); const structure = tv.structure as unknown as TariffStructure; @@ -220,8 +237,8 @@ export class PayStation { // Merchant validations: fold the LIVE ones (applied, unvoided, not consumed by a // prior payment) so the quote is NET — the payment then stamps their ids as // consumed. See wiki/concepts/validation-discounts.md. - const last = this.#lastPayment(identity); - const validations = liveValidations(this.#db, identity); + const last = PayStation.#lastPaymentFromRows(rows); + const validations = liveValidationsFromRows(rows); const p = priceSession( entry.occurredAt, new Date().toISOString(), @@ -254,12 +271,17 @@ export class PayStation { /** The latest signed `payment` for this session (time + the grace window it granted), * or null if never paid. Folds the append-only ledger. */ #lastPayment(identity: string): { paidAt: string; graceExitMin: number | null } | null { - const rows = this.#db - .select({ type: ledgerEvents.type, occurredAt: ledgerEvents.occurredAt, payload: ledgerEvents.payload }) - .from(ledgerEvents) - .where(eq(ledgerEvents.identity, identity)) - .orderBy(ledgerEvents.index) - .all(); + return PayStation.#lastPaymentFromRows(this.#identityRows(identity)); + } + + /** All ledger rows of one identity, oldest first (the fold order every helper expects). */ + #identityRows(identity: string): LedgerRow[] { + return this.#db.select().from(ledgerEvents).where(eq(ledgerEvents.identity, identity)).orderBy(ledgerEvents.index).all(); + } + + static #lastPaymentFromRows( + rows: readonly Pick[], + ): { paidAt: string; graceExitMin: number | null } | null { let last: { paidAt: string; graceExitMin: number | null } | null = null; for (const r of rows) { if (r.type !== "payment") continue; @@ -541,9 +563,15 @@ export class PayStation { subscriptionId?: string | null; }; const byId = new Map(); + // Every row per identity (oldest first — `rows` is index-ordered), so the quotes + // below price from THIS scan instead of re-reading the ledger per session. + const rowsById = new Map(); for (const r of rows) { const id = r.identity; if (!id) continue; + const group = rowsById.get(id); + if (group) group.push(r); + else rowsById.set(id, [r]); if (r.type === "vehicle_entry") { const a = byId.get(id) ?? { source: r.source ?? null }; a.enteredAt = r.occurredAt; @@ -570,6 +598,8 @@ export class PayStation { // Resolve advisory plates for all candidate identities in ONE device_events scan // (cheaper than one lookup per row). const plates = platesForIdentities(this.#db, byId.keys()); + // One tariff read for the whole list (quotes below reuse it). + const tariffFor = this.#tariffResolver(); const now = Date.now(); const out: ActiveSession[] = []; @@ -607,7 +637,9 @@ export class PayStation { let currency: string | null = null; if (open && !isSubscription && (a.paidAt == null || overstay)) { try { - const q = this.quote(identity); + // Priced from the rows already in hand — no per-session ledger reads. The + // charge providers (car wash) still run one indexed lookup per row. + const q = this.#quoteFromRows(identity, rowsById.get(identity) ?? [], tariffFor); amountMinor = q.amountMinor; currency = q.currency; } catch { @@ -710,12 +742,10 @@ export class PayStation { /** The vehicle_entry of an OPEN session for this identity (no later exit), or null. */ #openEntry(identity: string) { - const rows = this.#db - .select() - .from(ledgerEvents) - .where(eq(ledgerEvents.identity, identity)) - .orderBy(ledgerEvents.index) - .all(); + return PayStation.#openEntryFromRows(this.#identityRows(identity)); + } + + static #openEntryFromRows(rows: readonly LedgerRow[]): LedgerRow | null { const entry = rows.find((r) => r.type === "vehicle_entry"); if (!entry) return null; if (rows.some((r) => r.type === "vehicle_exit")) return null; // already closed @@ -725,14 +755,20 @@ export class PayStation { /** The tariff version in force at `at` — latest effectiveFrom ≤ at, for the * (single, for now) active site tariff. */ #tariffVersionFor(at: string) { + return this.#tariffResolver()(at); + } + + /** Read the site tariff + its versions ONCE and return a resolver over them. A list + * view builds one resolver per request instead of two tariff reads per row. */ + #tariffResolver(): TariffResolver { const tariff = this.#db.select().from(tariffs).where(eq(tariffs.scope, "site")).get(); - if (!tariff) return null; + if (!tariff) return () => null; const versions = this.#db .select() .from(tariffVersions) .where(eq(tariffVersions.tariffId, tariff.id)) .orderBy(desc(tariffVersions.effectiveFrom)) .all(); - return versions.find((v) => v.effectiveFrom <= at) ?? null; + return (at) => versions.find((v) => v.effectiveFrom <= at) ?? null; } } diff --git a/apps/server/src/subscription-flow.ts b/apps/server/src/subscription-flow.ts index 5f32290..02b4d6b 100644 --- a/apps/server/src/subscription-flow.ts +++ b/apps/server/src/subscription-flow.ts @@ -212,8 +212,9 @@ export class SubscriptionFlow { // `permitId` carries the subscription id; `via` records which credential left. payload: { sessionRef: occurrenceId, permitId: m.subscriptionId, via: m.via }, }); - await this.#open(resolved, "exit", occurrenceId, "subscription exit"); + // Cache close before the pulse, for the same reason as the entry-side insert. this.#closeCache(occurrenceId); + await this.#open(resolved, "exit", occurrenceId, "subscription exit"); return { accepted: true, direction: "exit" }; } @@ -269,7 +270,9 @@ export class SubscriptionFlow { `subscription out-of-window entry marked on ${occurrenceId} (charge priced from parked minutes at exit)`, ); } - await this.#open(resolved, "entry", occurrenceId, "subscription entry"); + // Session cache BEFORE the pulse: the entry is already signed, so the projection must + // reflect it even if the relay call throws (otherwise the ledger and the sessions + // table disagree about the same read — seen at park-2, 2026-10-24). try { this.#db .insert(sessions) @@ -285,6 +288,7 @@ export class SubscriptionFlow { } catch (err) { this.#logger.error(`session-cache insert failed for ${occurrenceId}: ${(err as Error).message}`); } + await this.#open(resolved, "entry", occurrenceId, "subscription entry"); // BEST-EFFORT: print the out-of-window TICKET so the subscriber has the paper the // operator scans to settle at the booth. It carries the occurrence id as a scannable // code; the amount is computed at settlement from the minutes actually parked @@ -410,13 +414,16 @@ export class SubscriptionFlow { } async #open(resolved: ResolvedRelay, dir: FlowDirection, carKey: string, what: string): Promise { + // SNAPSHOT FIRST — fire the directional camera(s), never awaited (evidence, not a + // gate). Before the pulse, so a pulse failure (the pulse helper rethrows) still leaves + // an image for the signed event: at park-2 four signed entries had no snapshot because + // the relay timed out and this method unwound before reaching the camera (2026-10-24). + this.#fireSnapshot(dir, carKey); + const access = this.#buildAccess(resolved.controller); if (access) { await pulseBarrier(this.#db, this.#logger, access, resolved, { direction: dir, identity: carKey, source: "subscription" }); } else this.#logger.warn(`${what} signed for ${carKey} but the ${dir} relay won't build`); - - // SNAPSHOT — fire the directional camera(s), never awaited (evidence, not a gate). - this.#fireSnapshot(dir, carKey); } #closeCache(carKey: string): void { diff --git a/apps/server/src/validations.ts b/apps/server/src/validations.ts index 269ca5f..fb6b06a 100644 --- a/apps/server/src/validations.ts +++ b/apps/server/src/validations.ts @@ -21,6 +21,16 @@ export interface AppliedValidation extends SessionValidation { readonly consumedBy: string | null; } +/** The ledger columns the validation fold reads. Any identity-scoped, index-ordered + * slice of `ledger_events` satisfies it (a direct query, or the per-identity group of a + * whole-ledger scan — see PayStation.activeSessions). */ +export interface LedgerRowLike { + readonly id: string; + readonly type: string; + readonly occurredAt: string; + readonly payload: unknown; +} + /** All validations ever applied to a session (newest last), with voided/consumed * state folded from the chain. One identity-scoped ledger scan. */ export function sessionValidations(db: Db, identity: string): AppliedValidation[] { @@ -35,7 +45,13 @@ export function sessionValidations(db: Db, identity: string): AppliedValidation[ .where(eq(ledgerEvents.identity, identity)) .orderBy(ledgerEvents.index) .all(); + return sessionValidationsFromRows(rows); +} +/** Same fold over rows the caller already holds (identity-scoped, oldest first). Lets a + * list view price hundreds of sessions from ONE ledger scan instead of one per row — + * the per-row scans were what froze the booth server (park-2, 2026-10-24). */ +export function sessionValidationsFromRows(rows: readonly LedgerRowLike[]): AppliedValidation[] { const voided = new Set(); const consumedBy = new Map(); const applies: AppliedValidation[] = []; @@ -88,6 +104,11 @@ export function liveValidations(db: Db, identity: string): AppliedValidation[] { return sessionValidations(db, identity).filter((v) => !v.voided && v.consumedBy == null); } +/** `liveValidations` over rows the caller already holds (see sessionValidationsFromRows). */ +export function liveValidationsFromRows(rows: readonly LedgerRowLike[]): AppliedValidation[] { + return sessionValidationsFromRows(rows).filter((v) => !v.voided && v.consumedBy == null); +} + // --- Apply (shared by the merchant route and the Car Wash module) ---------------- export interface ApplyValidationInput { diff --git a/packages/db/drizzle/0032_hot_path_indexes.sql b/packages/db/drizzle/0032_hot_path_indexes.sql new file mode 100644 index 0000000..7235d21 --- /dev/null +++ b/packages/db/drizzle/0032_hot_path_indexes.sql @@ -0,0 +1,18 @@ +-- Hot-path indexes (park-2, 2026-10-24). Every per-session read of the ledger was a full +-- scan (no index on identity), and the camera/relay telemetry queries scanned +-- device_events (no index beyond the PK). Both tables grow with the operator's traffic, +-- so request time grew with it: the booth's active-sessions call reached ~2 s and froze +-- the event loop, which surfaced as relay "timeouts". The handler was also rewritten to +-- avoid per-row reads; these indexes make the remaining identity/telemetry lookups O(log n) +-- whatever the data volume. All additive; the previous image ignores them on rollback. +CREATE INDEX IF NOT EXISTS `ledger_events_identity_idx` ON `ledger_events` (`identity`,`index`); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS `device_events_cat_kind_time_idx` ON `device_events` (`category`,`kind`,`occurred_at`); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS `device_events_kind_time_idx` ON `device_events` (`kind`,`occurred_at`); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS `snapshots_identity_idx` ON `snapshots` (`identity`); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS `sessions_state_idx` ON `sessions` (`state`); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS `sessions_subscription_idx` ON `sessions` (`subscription_id`,`state`); diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index d153a39..cf4c870 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -225,6 +225,13 @@ "when": 1788710000000, "tag": "0031_carwash_review_outbox", "breakpoints": true + }, + { + "idx": 32, + "version": "6", + "when": 1788720000000, + "tag": "0032_hot_path_indexes", + "breakpoints": true } ] } diff --git a/packages/devices/src/drivers/access-dingtian.ts b/packages/devices/src/drivers/access-dingtian.ts index 5b913a9..97519e7 100644 --- a/packages/devices/src/drivers/access-dingtian.ts +++ b/packages/devices/src/drivers/access-dingtian.ts @@ -77,7 +77,13 @@ function binaryUdp( sock.close(); err ? reject(err) : resolve(val!); }; - const timer = setTimeout(() => done(new Error("timeout"), null), timeoutMs); + // On expiry, defer the rejection by one loop turn. Node runs expired timers BEFORE + // it drains pending socket I/O, so if the event loop was blocked (a long synchronous + // handler) while the device's reply sat in the kernel buffer, the timer would win + // and report "timeout" for a relay that answered. The setImmediate lands in the + // check phase, after the poll phase has delivered that datagram to `message`. + // (park-2, 2026-10-24: ~2 s handler stalls produced exactly these phantom timeouts.) + const timer = setTimeout(() => setImmediate(() => done(new Error("timeout"), null)), timeoutMs); sock.on("error", (e) => done(e, null)); sock.on("message", (m) => done(null, m)); // Bind to a specific local address (the device-facing NIC) on multi-homed