fix(server): bound active-sessions cost, index hot paths, no phantom relay timeouts
Build & push images / images (push) Successful in 3m45s

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.
This commit is contained in:
2026-10-24 11:17:30 +02:00
parent 6eb65361a8
commit 73ada89a13
7 changed files with 142 additions and 26 deletions
+21
View File
@@ -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();
});
});
+56 -20
View File
@@ -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<LedgerRow, "type" | "occurredAt" | "payload">[],
): { 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<string, Acc>();
// 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<string, LedgerRow[]>();
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;
}
}
+12 -5
View File
@@ -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<void> {
// 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 {
+21
View File
@@ -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<string>();
const consumedBy = new Map<string, string>();
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 {