@ultimat3/action 31.47.1 → 31.49.0

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/CLAUDE.md CHANGED
@@ -31,10 +31,10 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
31
31
  | `errors-http.ts` | the three HTTP-declaration refusals |
32
32
  | `error-titles.ts` | every code's title, the one `registerErrorCodes` |
33
33
  | `client.ts` | typed RPC client (browser-safe: no server imports) — dispatches through core's `clientTransport` |
34
- | `record-wire.ts` | the record envelope on the HTTP projection: `carriesRecords` (from the output schema), the enveloped 200, and its OpenAPI shape. Server-only — `client.ts` never imports it |
34
+ | `record-wire.ts` | the action's 200 on the HTTP projection: `carriesRecords` (from the output schema), either body + `x-ultimate-dates`. Server-only — `client.ts` never imports it |
35
35
  | `wire-issues.ts` | the ONE reader of a problem document's `issues` member — an untrusted array back into `@ultimat3/schema`'s `ValidationIssue` shape |
36
36
  | `action-stream.ts` | `streamingDef`: a `stream`-declaring `handle` (an async generator) DRAINED, each chunk parsed by `stream` (`X_ACTION_STREAM_INVALID`, `errors-stream.ts`); `chunksRead()` |
37
- | `http-stream.ts` | `accept: text/event-stream` → `event: chunk`… then ONE `done` or `error`; a refusal before the handler is the ordinary problem response |
37
+ | `http-stream.ts` | SSE: `chunk`s then ONE `done` (both with `dates:`) or `error`; a late fault reported once, a cancel never; a refusal pre-handler is the plain problem |
38
38
  | `audit-subject-target.ts` | `auditSubjectTarget()`: `x_audit` as a subject-erase target — overwrites who acted and the input, never deletes the row |
39
39
  | `transition.ts` | `transition()`: a MUTATOR factory over one entity column's state machine. Declares no error code — entity's three propagate |
40
40
  | `upload-flow.ts` | `uploadFlow()`: an ACTION factory, `{ request, confirm }` over storage's `grantUpload` (pending only) and `promoteAttachment`. No code of its own |
@@ -63,10 +63,10 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
63
63
  | `meter*.ts`, `errors-meter.ts` | `meter:` — declaration (`meter.ts`), UTC window, store seam + memory + Postgres (`x_meter`), and `meter-gate.ts`, **the one place** it is drawn |
64
64
  | `request-deadline.ts` | `requestDeadlineMs` — the app's `requestTimeoutMs`, resolved by http's own `defineHttpConfig` |
65
65
  | `audit.ts` | the audit seam's TYPES, re-exported from `@ultimat3/core` (shared with `query`); the slot (`installAuditSink`, `@ultimat3/core/adapter`) is core's alone |
66
- | `audit-memory.ts` | the process default: a bounded ring that DROPS, and counts what it dropped |
67
- | `audit-postgres.ts` | the DURABLE sink — append-only `x_audit`; one insert per record, or per batch (`groupCommit`) |
66
+ | `audit-memory.ts` | the process default: a bounded ring that DROPS, counting the drops |
67
+ | `audit-postgres.ts` | the DURABLE sink — append-only `x_audit`, an insert per record or per batch |
68
68
  | `audit-postgres-row.ts` | a record as its row — the ONE projection both inserts bind |
69
- | `audit-batch.ts` | `batchedAuditSink`: group commit, per-write verdict, flush on drain |
69
+ | `audit-batch.ts`, `audit-accepted.ts` | `batchedAuditSink`: group commit, per-write verdict, one id per write, flush on drain |
70
70
  | `audit-input.ts` | what may be written DOWN: an `input` redacted through core's table and made JSON-representable on every path |
71
71
  | `audit-gate.ts` | **the only** file that calls a sink, and where the two failure policies live |
72
72
  | `type-pins.ts` | compile-time assertions `tsc` checks — what the erased view projects, and why `client()` is not part of it |
@@ -195,9 +195,9 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
195
195
  `bun build --target=browser --minify`, one entry importing from `@ultimat3/action` — **the ONE
196
196
  table for these figures** (`packages/core/CLAUDE.md` points here):
197
197
 
198
- | Entry | `As of 2026-11-15`, Bun 1.4.4, one entry over the working tree |
198
+ | Entry | `As of 2026-11-19`, Bun 1.4.4, one entry over the working tree |
199
199
  |---|---|
200
- | `rpc` | 24,655 B, pinned ≤ 25,000 (`client-bundle.test.ts`); 29,972 B while it read core's barrel; 25,395 B while `@ultimat3/db` held a dynamic `import()` (Bun wraps every module of a graph holding one in lazy-init code) |
200
+ | `rpc` | 25,281 B, pinned ≤ 25,303 (`client-bundle.test.ts`); 29,972 B while it read core's barrel; 25,395 B while `@ultimat3/db` held a dynamic `import()` (Bun wraps every module of a graph holding one in lazy-init code) |
201
201
  | `rpc` + `clientFlight` from `@ultimat3/core/page` | 32,929 B (38,416 B from the barrel) |
202
202
 
203
203
  - `isTransientFailure`'s inversion, the client graph's import rule, `sideEffects`: still rules, in
package/README.md CHANGED
@@ -168,6 +168,19 @@ returned none, so one operation has one wire shape. Every other action's body is
168
168
  what it was before the envelope existed, and its OpenAPI operation is unchanged; an enveloped one
169
169
  documents `data`, `records` and `removed`, and the header, generated from the declaration.
170
170
 
171
+ ### Instants — a `Date` output is a `Date` on the client
172
+
173
+ An output holding a `Date` (`t.date`, an entity `timestamp()` row) names each one by path in
174
+ `x-ultimate-dates`, on the plain and the enveloped 200 alike — `@ultimat3/query`'s rule — and the
175
+ typed client hands back the `Date` the output type promises (`As of 2026-11`). The body and the
176
+ OpenAPI document are unchanged: a client that ignores the header reads the ISO string it always
177
+ read. Each streamed `chunk` and the `done` frame carry their instants on a `dates:` field, which an
178
+ SSE reader that does not know it ignores. The header is capped at 1,536 bytes
179
+ (`WIRE_DATES_MAX_BYTES`): an answer whose instants need one path each — a `string | Date` column, a
180
+ `[label, instant]` tuple — past that is sent with no `x-ultimate-dates` (and no `dates:` line), the
181
+ client reads those instants as ISO strings, and the operation is logged once at `warn` as
182
+ `http.wire_dates_dropped`. `As of 2026-11-19`.
183
+
171
184
  ### Flight control — `clientFlight`, opt-in
172
185
 
173
186
  Same object as `@ultimat3/query`'s, installed the same way (`rpc({ baseUrl, flight })`), and the
@@ -208,7 +221,7 @@ An action may answer in pieces before it answers. `stream: <chunk schema>` besid
208
221
 
209
222
  | Caller | Gets |
210
223
  |---|---|
211
- | `accept: text/event-stream` on its route | `event: chunk` per yield (each parsed by `stream` first), then one `done` (the output) or `error` (the problem document); `x-accel-buffering: no`, never compressed |
224
+ | `accept: text/event-stream` on its route | `event: chunk` per yield (each parsed by `stream` first), then one `done` (the output) or `error` (the problem document); each `chunk` and the `done` frame carry their instants on a `dates:` field; a fault after the first chunk is recorded as the JSON path's is — monitor (5xx), `hooks.onError`, log line — once; a reader's cancel is not a fault; `x-accel-buffering: no`, never compressed |
212
225
  | JSON, MCP, `.job()`, `.as()`, a direct call | the generator drained: the output alone, one contract |
213
226
  | the typed client | `api.sayWords.stream(input)` — an `AsyncGenerator` of chunks whose return is the output, through core's `clientStream` (POST, the page's credentials, the same problem decode). Typed on a stream-declaring method only (`StreamClientMethod`); never retried |
214
227
  | the handler itself | `chunksRead()` — `true` only while a caller reads the chunks; `llm()` streams its one-attempt turn then, and is the repairing call otherwise |
@@ -980,6 +993,19 @@ joins the caller's open transaction, as it always has. A sink of your own with a
980
993
  `writeMany(records)` gets the batching through `batchedAuditSink(sink, { maxRecords, maxDelayMs })`
981
994
  from `@ultimat3/action/adapter` — and sends outside the ambient transaction itself.
982
995
 
996
+ **A batch whose reply is lost stores nothing twice.** A failed `writeMany` is retried one record at
997
+ a time, and the batch may have committed before its reply was lost. Each accepted `write()` is one
998
+ record object, the same one handed to `writeMany` and to its retry, carrying the row id minted when
999
+ it was accepted. Both inserts skip a row whose id is already stored with the same facts. A
1000
+ DIFFERENT row under that id still raises the driver's `unique_violation`, so a collision is never
1001
+ silently dropped. A retry that meets its own batch still committing draws `unique_violation` once
1002
+ (it waited on the key); `postgresAuditSink` sends that record once more, and the second statement
1003
+ sees the committed row and skips it. `memoryAuditSink` keeps an accepted record once, too. Two attempts with identical
1004
+ facts are still two records: one object written twice is two acceptances. A sink of your own reads
1005
+ the same id with `acceptedIdOf(record)` from `@ultimat3/action/adapter` (a string for every record
1006
+ `batchedAuditSink` handed it, `undefined` for one written unbatched) and keys its idempotent insert
1007
+ on it.
1008
+
983
1009
  `x_audit` carries the framework's own facts as columns — the action, the surface, the outcome,
984
1010
  the actor, the correlation ids, the idempotency key — and the parsed `input` as `jsonb`, redacted
985
1011
  through **core's own** `isRedactedKey` table, the one `defineEnv({ secret: true })` extends. So a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/action",
3
- "version": "31.47.1",
3
+ "version": "31.49.0",
4
4
  "description": "The action primitive: one declaration projected to route, OpenAPI, client, MCP tool, job handle, tests",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -48,13 +48,13 @@
48
48
  "test": "bun test"
49
49
  },
50
50
  "dependencies": {
51
- "@ultimat3/cache": "31.47.1",
52
- "@ultimat3/core": "31.47.1",
53
- "@ultimat3/db": "31.47.1",
54
- "@ultimat3/entity": "31.47.1",
55
- "@ultimat3/http": "31.47.1",
56
- "@ultimat3/policy": "31.47.1",
57
- "@ultimat3/schema": "31.47.1",
58
- "@ultimat3/storage": "31.47.1"
51
+ "@ultimat3/cache": "31.49.0",
52
+ "@ultimat3/core": "31.49.0",
53
+ "@ultimat3/db": "31.49.0",
54
+ "@ultimat3/entity": "31.49.0",
55
+ "@ultimat3/http": "31.49.0",
56
+ "@ultimat3/policy": "31.49.0",
57
+ "@ultimat3/schema": "31.49.0",
58
+ "@ultimat3/storage": "31.49.0"
59
59
  }
60
60
  }
package/src/action.ts CHANGED
@@ -417,7 +417,8 @@ function build<TInput extends StandardSchemaV1, TOutput extends StandardSchemaV1
417
417
  // stream-declaring one is stored draining (`action-stream.ts`), so `invoke` stays one path.
418
418
  stashDef(
419
419
  self,
420
- streamingDef(def as ActionDef<TInput, TOutput, TRow> & StreamFields, () => name),
420
+ // `self.name`, read per refusal: `nameAction` names in place after this line has run.
421
+ streamingDef(def as ActionDef<TInput, TOutput, TRow> & StreamFields, () => self.name),
421
422
  );
422
423
  return self;
423
424
  }
package/src/adapter.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // and group commit for a sink author's own `writeMany`. Never the `.` barrel: an app swaps a store
4
4
  // in `apps/<app>/runtime.ts`, so the callers here are the cli boot, `@ultimat3/testing` and authors.
5
5
 
6
+ export { acceptedIdOf } from './audit-accepted';
6
7
  export type { BatchAuditSink, BatchedAuditSink, BatchedAuditSinkOptions } from './audit-batch';
7
8
  export {
8
9
  batchedAuditSink,
@@ -0,0 +1,25 @@
1
+ // A record group commit has ACCEPTED: one object per `write()`, carrying the row id minted at that
2
+ // moment, handed to `writeMany` and to the single retry alike — so a sink can tell "this record
3
+ // again" (a batch that stored its rows and lost its reply) from "another attempt with the same facts".
4
+
5
+ import { uuidV7 } from '@ultimat3/core';
6
+ import type { AuditRecord } from './audit';
7
+
8
+ /**
9
+ * Keyed by the accepted COPY, never the caller's record: the conformance contract
10
+ * (`auditSinkConformance`, "two identical attempts are two records") writes one object twice and
11
+ * expects two rows, so the caller's object is not an identity. Each acceptance is a fresh copy.
12
+ */
13
+ const accepted = new WeakMap<AuditRecord, string>();
14
+
15
+ /** One accepted write: a shallow copy of `record` and its row id, minted here and only here. */
16
+ export function acceptRecord(record: AuditRecord): AuditRecord {
17
+ const copy: AuditRecord = { ...record };
18
+ accepted.set(copy, uuidV7());
19
+ return copy;
20
+ }
21
+
22
+ /** The id minted when `record` was accepted, or `undefined` for a record no batch accepted. */
23
+ export function acceptedIdOf(record: AuditRecord): string | undefined {
24
+ return accepted.get(record);
25
+ }
@@ -7,6 +7,7 @@
7
7
 
8
8
  import { finiteCount, MAX_TIMER_MS, onShutdown } from '@ultimat3/core';
9
9
  import type { AuditRecord, AuditSink } from './audit';
10
+ import { acceptRecord } from './audit-accepted';
10
11
 
11
12
  /** Records per batch, by default: one statement's worth, well under any driver's message limit. */
12
13
  export const DEFAULT_AUDIT_BATCH_MAX_RECORDS = 256;
@@ -126,7 +127,8 @@ export function batchedAuditSink(
126
127
 
127
128
  const write = (record: AuditRecord): Promise<void> =>
128
129
  new Promise<void>((resolve, reject) => {
129
- queue.push({ record, resolve, reject });
130
+ // Accepted once, here: the batch and its single retry hand the sink this same object.
131
+ queue.push({ record: acceptRecord(record), resolve, reject });
130
132
  if (queue.length >= maxRecords) send();
131
133
  // Ref'd on purpose: a queued record is an audit row owed, and the process stays up to pay it.
132
134
  else if (timer === undefined) timer = setTimeout(send, maxDelayMs);
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import type { AuditRecord, AuditSink } from './audit';
8
+ import { acceptedIdOf } from './audit-accepted';
8
9
 
9
10
  /**
10
11
  * Records held at once. A record pins a whole `Ctx` — the actor, the service bag, the parsed
@@ -59,9 +60,16 @@ export function memoryAuditSink(options: MemoryAuditSinkOptions = {}): MemoryAud
59
60
  : DEFAULT_MAX_AUDIT_RECORDS;
60
61
  const log: AuditRecord[] = [];
61
62
  let dropped = 0;
63
+ // Group commit's accepted records already held: the memory twin of the Postgres sink skipping a
64
+ // row it stored under the same id, so a batch that stored and then rejected is not kept twice.
65
+ let held = new WeakSet<AuditRecord>();
62
66
 
63
67
  return {
64
68
  write(record: AuditRecord): void {
69
+ if (acceptedIdOf(record) !== undefined) {
70
+ if (held.has(record)) return;
71
+ held.add(record);
72
+ }
65
73
  log.push(record);
66
74
  // `shift` in a loop, not a slice: the cap is only ever exceeded by one per write, so this
67
75
  // runs at most once — and it releases the evicted record's `Ctx` rather than copying the
@@ -81,6 +89,7 @@ export function memoryAuditSink(options: MemoryAuditSinkOptions = {}): MemoryAud
81
89
  clear: (): void => {
82
90
  log.length = 0;
83
91
  dropped = 0;
92
+ held = new WeakSet();
84
93
  },
85
94
  };
86
95
  }
@@ -4,6 +4,7 @@
4
4
  import type { Actor } from '@ultimat3/core';
5
5
  import { uuidV7 } from '@ultimat3/core';
6
6
  import type { AuditRecord } from './audit';
7
+ import { acceptedIdOf } from './audit-accepted';
7
8
  import { auditableInput } from './audit-input';
8
9
 
9
10
  /**
@@ -44,7 +45,9 @@ export function rowOf(record: AuditRecord): AuditRow {
44
45
  const onBehalfOf = onBehalfOfOf(actor);
45
46
  const input = auditableInput(record.input);
46
47
  return {
47
- id: uuidV7(),
48
+ // A record group commit accepted keeps the id it was accepted with, so its single retry
49
+ // re-binds the row its batch may already have stored; any other write is a new row.
50
+ id: acceptedIdOf(record) ?? uuidV7(),
48
51
  at: at === null ? null : at.toISOString(),
49
52
  // `name`, into the column the seam named before reads were audited: renaming it is a data
50
53
  // migration for every installed table, and the value it holds is the same.
@@ -6,10 +6,11 @@
6
6
 
7
7
  import type { PgExecutor } from '@ultimat3/core';
8
8
  import type { AuditRecord } from './audit';
9
+ import { acceptedIdOf } from './audit-accepted';
9
10
  import type { BatchAuditSink, BatchedAuditSink, BatchedAuditSinkOptions } from './audit-batch';
10
11
  import { batchedAuditSink } from './audit-batch';
11
12
  import { rowOf } from './audit-postgres-row';
12
- import { outsideTransactions } from './tx-scope';
13
+ import { isUniqueViolation, outsideTransactions } from './tx-scope';
13
14
 
14
15
  /**
15
16
  * Applied by the boot, never by an app migration — the rule `SQL_IDEMPOTENCY_TABLE` follows, and
@@ -74,11 +75,33 @@ create index if not exists x_audit_actor_at_idx on x_audit (actor_id, at desc);
74
75
  `;
75
76
 
76
77
  /**
77
- * `id` is generated per ROW and is not an idempotency key: two identical attempts are two events
78
- * and an audit trail that collapsed them would be lying about how many times something was tried.
79
- * There is deliberately no `on conflict` — an append-only table has nothing to reconcile.
78
+ * `id` is minted per RECORD and is not an idempotency key: two identical attempts are two records,
79
+ * two ids, two events — a trail that collapsed them would lie about how many times something was
80
+ * tried. A record keeps its id across sends (`rowOf`), so group commit's single retry after a lost
81
+ * reply re-binds the id its batch already stored.
80
82
  *
81
- * `recorded_at` defaults to `now()` and is not a parameter: `at` is the caller's clock
83
+ * **Why not `on conflict (id) do nothing`**: it would also swallow a DIFFERENT record that drew a
84
+ * stored id, and an append-only trail must say so rather than drop it. So a row is skipped only
85
+ * when the stored row with its id holds the same facts (`SQL_AUDIT_UNLESS_STORED`); any other row
86
+ * under that id still raises the driver's `unique_violation`, exactly as before.
87
+ */
88
+ const SQL_AUDIT_UNLESS_STORED = `
89
+ where not exists (
90
+ select 1 from x_audit as a
91
+ where a.id = r.id
92
+ and (
93
+ a.at, a.action, a.mutator, a.surface, a.outcome, a.replayed, a.idempotency_key,
94
+ a.failure_code, a.actor_id, a.actor_kind, a.org_id, a.on_behalf_of_id, a.on_behalf_of_kind,
95
+ a.request_id, a.trace_id, a.locale, a.tz, a.build_id, a.role, a.input, a.primitive
96
+ ) is not distinct from (
97
+ r.at, r.action, r.mutator, r.surface, r.outcome, r.replayed, r.idempotency_key,
98
+ r.failure_code, r.actor_id, r.actor_kind, r.org_id, r.on_behalf_of_id, r.on_behalf_of_kind,
99
+ r.request_id, r.trace_id, r.locale, r.tz, r.build_id, r.role, r.input::jsonb, r.primitive
100
+ )
101
+ )`;
102
+
103
+ /**
104
+ * One record. `recorded_at` defaults to `now()` and is not a parameter: `at` is the caller's clock
82
105
  * (`ctx.now()`) and this is the database's, so the gap between them is the audit lag, and a
83
106
  * process whose clock has drifted is visible instead of invisible.
84
107
  */
@@ -87,11 +110,20 @@ insert into x_audit (
87
110
  id, at, action, mutator, surface, outcome, replayed, idempotency_key, failure_code,
88
111
  actor_id, actor_kind, org_id, on_behalf_of_id, on_behalf_of_kind,
89
112
  request_id, trace_id, locale, tz, build_id, role, input, primitive
90
- ) values (
91
- $1::uuid, $2::timestamptz, $3, $4, $5, $6, $7, $8, $9,
92
- $10, $11, $12, $13, $14,
93
- $15, $16, $17, $18, $19, $20, $21::jsonb, $22
94
113
  )
114
+ select
115
+ id, at, action, mutator, surface, outcome, replayed, idempotency_key, failure_code,
116
+ actor_id, actor_kind, org_id, on_behalf_of_id, on_behalf_of_kind,
117
+ request_id, trace_id, locale, tz, build_id, role, input, primitive
118
+ from (values (
119
+ $1::uuid, $2::timestamptz, $3::text, $4::boolean, $5::text, $6::text, $7::boolean, $8::text,
120
+ $9::text, $10::text, $11::text, $12::text, $13::text, $14::text,
121
+ $15::text, $16::text, $17::text, $18::text, $19::text, $20::text, $21::jsonb, $22::text
122
+ )) as r (
123
+ id, at, action, mutator, surface, outcome, replayed, idempotency_key, failure_code,
124
+ actor_id, actor_kind, org_id, on_behalf_of_id, on_behalf_of_kind,
125
+ request_id, trace_id, locale, tz, build_id, role, input, primitive
126
+ )${SQL_AUDIT_UNLESS_STORED}
95
127
  `;
96
128
 
97
129
  /**
@@ -117,7 +149,7 @@ from jsonb_to_recordset($1::jsonb) as r (
117
149
  actor_id text, actor_kind text, org_id text, on_behalf_of_id text, on_behalf_of_kind text,
118
150
  request_id text, trace_id text, locale text, tz text, build_id text, role text,
119
151
  input text, primitive text
120
- )
152
+ )${SQL_AUDIT_UNLESS_STORED}
121
153
  `;
122
154
 
123
155
  export interface PostgresAuditSinkOptions {
@@ -174,7 +206,16 @@ export function postgresAuditSink(
174
206
  const exec = grouped ? outsideTransactions(options.executor) : options.executor;
175
207
  const sink: PostgresAuditSink = {
176
208
  async write(record: AuditRecord): Promise<void> {
177
- await exec.query(SQL_AUDIT_INSERT, Object.values(rowOf(record)));
209
+ const row = Object.values(rowOf(record));
210
+ try {
211
+ await exec.query(SQL_AUDIT_INSERT, row);
212
+ } catch (error) {
213
+ // Group commit's single retry can meet its own batch still committing: its `not exists`
214
+ // ran first, it then waited on the key and drew 23505. Sent once more it sees the
215
+ // committed row and skips it if identical; a different row raises again, as it should.
216
+ if (acceptedIdOf(record) === undefined || !isUniqueViolation(error)) throw error;
217
+ await exec.query(SQL_AUDIT_INSERT, row);
218
+ }
178
219
  },
179
220
  async writeMany(records: readonly AuditRecord[]): Promise<void> {
180
221
  if (records.length === 0) return;
package/src/errors.ts CHANGED
@@ -81,7 +81,7 @@ export class ActionDeniedError extends UltimateError {
81
81
  super({
82
82
  code: refused.code,
83
83
  cause: `${refused.name} denied: ${refused.reason}`,
84
- fix: `x policy explain ${renderFixShellArg(refused.name, '<permission>')} --json # shows which clause decided and why`,
84
+ fix: `x policy explain ${renderFixShellArg(refused.name, '<permission>')} --input '<the request input as JSON>' --json # shows which clause decided and why; --input decides a predicate that reads the request`,
85
85
  callerFix: deniedCallerFix(),
86
86
  });
87
87
  this.denial = refused.denial;
@@ -5,8 +5,9 @@
5
5
  * handler starts — the policy, the input, the rate limit — is the ordinary problem response.
6
6
  */
7
7
 
8
+ import type { Ctx } from '@ultimat3/core';
8
9
  import { useContext, withChildContext } from '@ultimat3/core';
9
- import { toProblem } from '@ultimat3/http';
10
+ import { cappedWireDates, reportLateFault, toProblem } from '@ultimat3/http';
10
11
  import type { ChunkSink } from './action-stream';
11
12
 
12
13
  export const EVENT_STREAM = 'text/event-stream';
@@ -25,9 +26,20 @@ export function wantsEventStream(accept: string | null): boolean {
25
26
  const encoder = new TextEncoder();
26
27
  const STARTED: unique symbol = Symbol('started');
27
28
 
28
- /** One SSE frame. JSON never holds a raw newline, so `data:` is always one line. */
29
- export function sseFrame(event: 'chunk' | 'done' | 'error', data: unknown): Uint8Array {
30
- return encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data ?? null)}\n\n`);
29
+ /**
30
+ * One SSE frame. JSON never holds a raw newline, so `data:` is always one line. `dates` is the
31
+ * `x-ultimate-dates` value for THIS frame's data (core's `wire-dates.ts`, URI-encoded, so one line
32
+ * too): a field the SSE format tells every reader that does not know it to ignore, so a client from
33
+ * before it reads the frame it always read. Under the header's cap (`cappedWireDates`): a frame
34
+ * whose value is past it carries no `dates:` line, and its instants are read as ISO strings.
35
+ */
36
+ export function sseFrame(
37
+ event: 'chunk' | 'done' | 'error',
38
+ data: unknown,
39
+ dates?: string,
40
+ ): Uint8Array {
41
+ const named = dates === undefined ? '' : `dates: ${dates}\n`;
42
+ return encoder.encode(`event: ${event}\n${named}data: ${JSON.stringify(data ?? null)}\n\n`);
31
43
  }
32
44
 
33
45
  /** Runs the invocation with `sink` receiving its chunks; resolves the output. */
@@ -42,7 +54,9 @@ export async function streamAnswer(
42
54
  run: StreamRun,
43
55
  heartbeatMs: number = HEARTBEAT_MS,
44
56
  ): Promise<Response> {
45
- const requestId = useContext().requestId;
57
+ // Read here, in the request's frame: the settle below runs on a later turn.
58
+ const ctx = useContext();
59
+ const requestId = ctx.requestId;
46
60
  // The client leaving cancels the body; that aborts this signal, added to the request's own.
47
61
  const left = new AbortController();
48
62
  let out: ReadableStreamDefaultController<Uint8Array> | undefined;
@@ -57,9 +71,14 @@ export async function streamAnswer(
57
71
  const sink: ChunkSink = {
58
72
  owner,
59
73
  start: () => begin(),
60
- push: (chunk) => send(sseFrame('chunk', chunk)),
74
+ push: (chunk) => send(sseFrame('chunk', chunk, cappedWireDates(chunk, ctx))),
61
75
  };
62
- const settled = withChildContext({ signal: left.signal }, () => run(sink));
76
+ // The handler's own scope: its signal is the request's and `left`'s, composed.
77
+ let scope: Ctx = ctx;
78
+ const settled = withChildContext({ signal: left.signal }, () => {
79
+ scope = useContext();
80
+ return run(sink);
81
+ });
63
82
  // Settled without starting is a refusal — thrown here, before any byte — or a replayed answer,
64
83
  // which streams as a lone `done`.
65
84
  await Promise.race([started, settled]);
@@ -77,8 +96,15 @@ export async function streamAnswer(
77
96
  }
78
97
  };
79
98
  settled.then(
80
- (output) => finish(sseFrame('done', output)),
81
- (error: unknown) => finish(sseFrame('error', toProblem(error, { requestId }))),
99
+ (output) => finish(sseFrame('done', output, cappedWireDates(output, ctx))),
100
+ (error: unknown) => {
101
+ // A fault after the first byte never reaches the pipeline's `error-map` stage — the 200
102
+ // has gone — so the request's late-fault report records it (the monitor, the app's
103
+ // `onError`, the log line, once). It tells the reader cancelling, or the caller hanging
104
+ // up, from a failure by `scope`'s signal, and records nothing for those.
105
+ reportLateFault(error, scope);
106
+ finish(sseFrame('error', toProblem(error, { requestId })));
107
+ },
82
108
  );
83
109
  },
84
110
  cancel() {
package/src/http.ts CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  writeDigest,
23
23
  } from '@ultimat3/core';
24
24
  import type { Route, RouteMeta, UltimateRequest } from '@ultimat3/http';
25
- import { jsonResponse, publishRateLimit, redirect, takeRedirect } from '@ultimat3/http';
25
+ import { publishRateLimit, redirect, takeRedirect } from '@ultimat3/http';
26
26
  import { admitsAnonymous, policyCapability, policyPermissions } from '@ultimat3/policy';
27
27
  import type { ActionRateLimit, AnyAction } from './action';
28
28
  import { withChunkSink } from './action-stream';
@@ -43,7 +43,7 @@ import {
43
43
  import { answerNatively, isNativeFormPost } from './native-answer';
44
44
  import { withDeclaredErrors } from './openapi-errors';
45
45
  import { assertActionRateLimit, fixedRateLimit } from './rate-limit-gate';
46
- import { carriesRecords, recordResponse } from './record-wire';
46
+ import { carriesRecords, plainResponse, recordResponse } from './record-wire';
47
47
  import { assertReplayPrincipal, REPLAY_REFUSAL } from './replay-scope';
48
48
 
49
49
  /** The digest a request's idempotency key names its write by; none for a missing or blank one. */
@@ -174,7 +174,7 @@ function projectRoute(
174
174
  ? redirect(to.location, to.status)
175
175
  : enveloped
176
176
  ? recordResponse(target.output, result)
177
- : jsonResponse(result);
177
+ : plainResponse(result);
178
178
  if (key !== null) response.headers.set(REPLAYED_HEADER, replayed ? '1' : '0');
179
179
  return response;
180
180
  };
@@ -13,7 +13,7 @@ import type {
13
13
  IdempotencyStore,
14
14
  } from './idempotency';
15
15
  import { requestDeadlineMs } from './request-deadline';
16
- import { liveTransaction } from './tx-scope';
16
+ import { settleScope } from './tx-scope';
17
17
 
18
18
  /**
19
19
  * How long a key is remembered. A day is the window every payment API this shape exists to serve
@@ -118,7 +118,7 @@ export class MemoryIdempotencyStore implements IdempotencyStore {
118
118
  createdAt: nowMs,
119
119
  };
120
120
  this.#records.set(key, record);
121
- this.#flights.set(record, { bound: liveTransaction() !== undefined, settling: false });
121
+ this.#flights.set(record, { bound: settleScope() !== undefined, settling: false });
122
122
  this.#maintain(nowMs);
123
123
  return Promise.resolve({ record, created: true });
124
124
  }
@@ -158,15 +158,15 @@ export class MemoryIdempotencyStore implements IdempotencyStore {
158
158
  value,
159
159
  ...(redacted ? { redacted: true } : {}),
160
160
  });
161
- const tx = liveTransaction();
161
+ const tx = settleScope();
162
162
  if (tx === undefined) {
163
163
  if (existing !== undefined) this.#records.set(key, settled(existing));
164
164
  else fenced(key, reservationId, 'settle');
165
165
  return Promise.resolve();
166
166
  }
167
- // Inside a transaction the record is settled BY the commit, as the Postgres store's is: a
168
- // rollback leaves it in flight rather than replaying a success for rows nobody stored. And a
169
- // settle that lost its reservation is thrown, because nothing has committed yet and the throw
167
+ // Inside a transaction — SQL or memory — the record is settled BY the commit, as the Postgres
168
+ // store's is: a rollback leaves it in flight rather than replaying a success for rows nobody
169
+ // stored. And a settle that lost its reservation is thrown, because nothing has committed yet and the throw
170
170
  // is what rolls this attempt back beside the retry that replaced it.
171
171
  if (existing === undefined) {
172
172
  return Promise.reject(new IdempotencyReservationLostError(key));
package/src/invoke.ts CHANGED
@@ -50,7 +50,12 @@ import { idempotencyKeyFor } from './idempotency-key';
50
50
  import { drawMeter } from './meter-gate';
51
51
  import { guardAction, guardActionBeforeInput } from './policy-gate';
52
52
  import { spendActionLimit, withCallerAddress, withJobFrame } from './rate-limit-gate';
53
- import { parseActionInput, parsedOrNothing, validateOutput } from './validate';
53
+ import {
54
+ parseActionInput,
55
+ parsedOrNothing,
56
+ validateOutput,
57
+ validateReplayedOutput,
58
+ } from './validate';
54
59
 
55
60
  /**
56
61
  * Private on purpose. `@ultimat3/action` exports no way to read this back, which
@@ -403,8 +408,11 @@ async function perform(
403
408
  trace.replayed = outcome.replayed;
404
409
  // A replay is parsed like a first call. The memory store hands back the live value and the
405
410
  // postgres store `JSON.parse(JSON.stringify(v))` — a `Date` on the first call and a `string`
406
- // on every retry served from Postgres — so the output schema is the one answer to its shape.
407
- return outcome.replayed ? validateOutput(def.output, outcome.value, name) : outcome.value;
411
+ // on every retry served from Postgres — so the output schema is the one answer to its shape,
412
+ // and a stored `null` it refuses is the `undefined` JSON could not keep.
413
+ return outcome.replayed
414
+ ? validateReplayedOutput(def.output, outcome.value, name)
415
+ : outcome.value;
408
416
  } finally {
409
417
  // Only for a handler that actually started, and only through the gate. A replay ran no handler
410
418
  // and changed nothing the first call had not already busted — re-busting per retry re-purges
@@ -1,12 +1,12 @@
1
1
  /**
2
- * The record envelope, on the action's HTTP projection only. Derived from the output schema — an
3
- * action whose output references an entity row answers `{ data, records }` under
4
- * `x-ultimate-records: 1`; every other action's body is byte-identical to what it always was.
2
+ * The action's 200 on the HTTP projection. Derived from the output schema — an action whose output
3
+ * references an entity row answers `{ data, records }` under `x-ultimate-records: 1`; every other
4
+ * action's body is byte-identical to what it always was. Either names its instants by path.
5
5
  */
6
6
 
7
- import { encodeRecordEnvelope, RECORDS_HEADER } from '@ultimat3/core';
7
+ import { DATES_HEADER, encodeRecordEnvelope, RECORDS_HEADER } from '@ultimat3/core';
8
8
  import { hasEntityRows, rowsOf } from '@ultimat3/entity';
9
- import { jsonResponse } from '@ultimat3/http';
9
+ import { cappedWireDates, jsonResponse } from '@ultimat3/http';
10
10
  import type { StandardSchemaV1 } from '@ultimat3/schema';
11
11
 
12
12
  /** The header value that says "this body is an envelope". Presence alone is not enough. */
@@ -24,9 +24,29 @@ export function carriesRecords(output: StandardSchemaV1): boolean {
24
24
  return hasEntityRows(output);
25
25
  }
26
26
 
27
- /** The 200 for an action that carries records: the envelope, and the header that names it. */
27
+ /**
28
+ * The output's instants — `@ultimat3/core`'s `wire-dates.ts`, the rule `@ultimat3/query`'s
29
+ * `record-answer.ts` follows — so the typed client hands back the `Date` the output type promises.
30
+ * A header, never the body: an old client reads the ISO string it always read. Capped
31
+ * (`cappedWireDates`, 4 KB): an output needing one path per instant past that sends NO header —
32
+ * a proxy refuses a response whose headers outgrow its buffer — and is logged once per action.
33
+ */
34
+ function datesOf(result: unknown): { readonly headers: Record<string, string> } {
35
+ const dates = cappedWireDates(result);
36
+ return { headers: dates === undefined ? {} : { [DATES_HEADER]: dates } };
37
+ }
38
+
39
+ /** The 200 for an action that carries no records: the output itself. */
40
+ export function plainResponse(result: unknown): Response {
41
+ return jsonResponse(result, datesOf(result));
42
+ }
43
+
44
+ /**
45
+ * The 200 for an action that carries records: the envelope, and the header that names it. The
46
+ * paths are the DATA's, as on a read: the client revives the envelope's `data`, never `records`.
47
+ */
28
48
  export function recordResponse(output: StandardSchemaV1, result: unknown): Response {
29
- const response = jsonResponse(encodeRecordEnvelope(result, rowsOf(output, result)));
30
- response.headers.set(RECORDS_HEADER, ENVELOPED);
31
- return response;
49
+ return jsonResponse(encodeRecordEnvelope(result, rowsOf(output, result)), {
50
+ headers: { [RECORDS_HEADER]: ENVELOPED, ...datesOf(result).headers },
51
+ });
32
52
  }
package/src/tx-scope.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The open database transaction, as this package needs it — **the only** file here that imports
3
3
  * `@ultimat3/db` (`tx-scope.test.ts`): when a write is durable, whether a transaction is OPEN and on
4
- * which client, a scope whose writes are never kept, and an executor that never joins one.
4
+ * which client, a scope whose writes are never kept, an executor that never joins one, and the
5
+ * one SQLSTATE an insert outside a transaction asks about.
5
6
  */
6
7
 
7
8
  // Type-only: `idempotency-postgres.ts` imports this module, and a runtime edge would be a cycle.
@@ -13,9 +14,12 @@ import {
13
14
  dbClientInstalled,
14
15
  liveTxConnection,
15
16
  outsideTransaction,
17
+ SQLSTATE,
18
+ sqlState,
16
19
  withTransaction,
17
20
  } from '@ultimat3/db';
18
21
  import { memoryJournal, memoryTransactor } from '@ultimat3/entity';
22
+ import { memoryTxOpen } from '@ultimat3/entity/internal/memory-tx';
19
23
 
20
24
  /** The mark a keyed run puts on the open root: its COMMIT carries the settle, abort or no abort. */
21
25
  export const carrySettleOnCommit = (): void => completeTransaction();
@@ -29,6 +33,10 @@ export const outsideTransactions = (executor: PgExecutor): PgExecutor => ({
29
33
  query: (text, values) => outsideTransaction(() => executor.query(text, values)),
30
34
  });
31
35
 
36
+ /** Whether `error` is Postgres' `unique_violation`, read through db's one SQLSTATE reader. */
37
+ export const isUniqueViolation = (error: unknown): boolean =>
38
+ sqlState(error) === SQLSTATE.uniqueViolation;
39
+
32
40
  /** The half of a transaction a deferred effect needs. `@ultimat3/db`'s `DbTx` satisfies it. */
33
41
  export interface CommitScope {
34
42
  /** Fired once the ROOT transaction has committed; dropped on rollback or a lost COMMIT. */
@@ -82,6 +90,23 @@ export function liveTransaction(): LiveTransaction | undefined {
82
90
  };
83
91
  }
84
92
 
93
+ /** The half of an open transaction a settle bound to it needs: its commit and its rollback. */
94
+ export type SettleScope = Pick<LiveTransaction, 'onCommit' | 'onRollback'>;
95
+
96
+ /**
97
+ * The OPEN transaction a settle rides — the SQL one (`liveTransaction`), else the open MEMORY one,
98
+ * the answer `openCommitScope` gives the bust. `undefined` outside both and for an ended scope, so
99
+ * a settle the body forgot to await is its own unit of work on either store, never a dropped one.
100
+ */
101
+ export function settleScope(): SettleScope | undefined {
102
+ const sql = liveTransaction();
103
+ if (sql !== undefined) return sql;
104
+ const memory = memoryJournal();
105
+ const onCommit = memory?.onCommit?.bind(memory);
106
+ if (memory === undefined || onCommit === undefined || !memoryTxOpen(memory)) return undefined;
107
+ return { onCommit, onRollback: (undo) => memory.onRollback(undo) };
108
+ }
109
+
85
110
  /**
86
111
  * Thrown inside the scope only to end it, and caught right outside: the one way a `withTransaction`
87
112
  * body asks for ROLLBACK. Never an `UltimateError`, because nothing but `inRolledBackScope` ever
package/src/validate.ts CHANGED
@@ -65,3 +65,23 @@ export async function validateOutput<S extends StandardSchemaV1>(
65
65
  }
66
66
  return result.value;
67
67
  }
68
+
69
+ /**
70
+ * A REPLAYED answer's parse. JSON has no `undefined`, so a store that keeps the answer as JSON (the
71
+ * Postgres store) hands back `null` for a handler that returned nothing — and an output schema
72
+ * that accepted `undefined` refused its own replay. A stored `null` the schema refuses is read as
73
+ * the `undefined` it stood for, when the schema takes that; any other refusal is the first one.
74
+ */
75
+ export async function validateReplayedOutput<S extends StandardSchemaV1>(
76
+ schema: S,
77
+ stored: unknown,
78
+ actionName: string,
79
+ ): Promise<InferOutput<S>> {
80
+ const result = await validateAsync(schema, stored);
81
+ if (result.issues === undefined) return result.value;
82
+ if (stored === null) {
83
+ const absent = await validateAsync(schema, undefined);
84
+ if (absent.issues === undefined) return absent.value;
85
+ }
86
+ throw new OutputInvalidError(actionName, formatIssues(result.issues).join('; '));
87
+ }