@ultimat3/action 31.48.0 → 31.50.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 |
@@ -60,13 +60,13 @@ Owns the `action` + `mutator` primitives and five projections. Tier 3. The MCP t
60
60
  | `cache-gate.ts` | the post-COMMIT bust — **the only** file that calls `invalidateTags` |
61
61
  | `tx-scope.ts` | the open transaction — **the only** file that imports `@ultimat3/db` (`tx-scope.test.ts`): `openCommitScope` (the bust), `liveTransaction` (the settle), `completeTransaction`, and `inRolledBackScope`, the exercise's always-rolled-back scope and the memory transaction it opens always |
62
62
  | `rate-limit-gate.ts` | **the one place** a declared `rateLimit:` is spent (a `limit` resolved per call from `ctx`, through `toBucket`) |
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 |
63
+ | `meter*.ts`, `errors-meter.ts` | `meter:` (`meter.ts`), UTC window, store seam, memory, Postgres; `meter-gate.ts` draws a `meter:`, `meter-draw.ts` is `drawMeter` |
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 |
@@ -648,6 +661,15 @@ stored key says so (`day@UTC`). An idempotent replay draws nothing. `limit` may
648
661
  installed by the CLI boot (one row per counter, rolled over in place, no purge). Full table:
649
662
  [Actions → Usage meters](https://github.com/developerz-ai/ultimate/wiki/Actions#usage-meters-meter).
650
663
 
664
+ An amount measured after the work — tokens, bytes, rows — is `drawMeter(ctx, { meter, period,
665
+ amount, limit, key })`: added whole or not at all (`X_METER_EXCEEDED`), on the counter a `meter:`
666
+ of the same name and period uses. A `key` counts once while it is remembered: for the period it
667
+ counted in and the next, by one store — across replicas and restarts on the Postgres store the
668
+ boot installs; within one process on `memoryMeterStore()`, where either bound ends it early
669
+ (`maxDrawKeys`, or `maxKeys` evicting the counter with its keys). `limit` judges
670
+ new charges only: a remembered key replays even after its limit drops below its amount. Answers
671
+ `{ used, limit, replayed, resetsAt }`: [Actions → Programmatic draws](https://github.com/developerz-ai/ultimate/wiki/Actions#programmatic-draws-drawmeter).
672
+
651
673
  ## `idempotent:` — and where its records live
652
674
 
653
675
  `idempotent: true` + an `Idempotency-Key` header replays the first **outcome**
@@ -980,6 +1002,19 @@ joins the caller's open transaction, as it always has. A sink of your own with a
980
1002
  `writeMany(records)` gets the batching through `batchedAuditSink(sink, { maxRecords, maxDelayMs })`
981
1003
  from `@ultimat3/action/adapter` — and sends outside the ambient transaction itself.
982
1004
 
1005
+ **A batch whose reply is lost stores nothing twice.** A failed `writeMany` is retried one record at
1006
+ a time, and the batch may have committed before its reply was lost. Each accepted `write()` is one
1007
+ record object, the same one handed to `writeMany` and to its retry, carrying the row id minted when
1008
+ it was accepted. Both inserts skip a row whose id is already stored with the same facts. A
1009
+ DIFFERENT row under that id still raises the driver's `unique_violation`, so a collision is never
1010
+ silently dropped. A retry that meets its own batch still committing draws `unique_violation` once
1011
+ (it waited on the key); `postgresAuditSink` sends that record once more, and the second statement
1012
+ sees the committed row and skips it. `memoryAuditSink` keeps an accepted record once, too. Two attempts with identical
1013
+ facts are still two records: one object written twice is two acceptances. A sink of your own reads
1014
+ the same id with `acceptedIdOf(record)` from `@ultimat3/action/adapter` (a string for every record
1015
+ `batchedAuditSink` handed it, `undefined` for one written unbatched) and keys its idempotent insert
1016
+ on it.
1017
+
983
1018
  `x_audit` carries the framework's own facts as columns — the action, the surface, the outcome,
984
1019
  the actor, the correlation ids, the idempotency key — and the parsed `input` as `jsonb`, redacted
985
1020
  through **core's own** `isRedactedKey` table, the one `defineEnv({ secret: true })` extends. So a
@@ -1154,8 +1189,8 @@ around it; `undefined` restores the declared handler. `@ultimat3/testing`'s `stu
1154
1189
  | `X_ACTION_PATH_DUPLICATE` | two actions derive one HTTP path (`archiveOrder` / `archiveOrders`) | rename one export |
1155
1190
  | `X_ACTION_POLICY_MISSING` | registration without `policy:` | add `policy: can('…')` |
1156
1191
  | `X_RATE_LIMIT_INVALID` | `rateLimit:` with a non-positive or non-finite half — `windowMs: 0` refills infinitely. Owned by `@ultimat3/http`, which owns the conversion | make both positive, or delete the block |
1157
- | `X_METER_EXCEEDED` | a `meter:`'s allowance for the current UTC period is spent; `meta.resetsAt` and `Retry-After` say when it resets | wait, or raise what `meter.limit` resolves to for the tenant |
1158
- | `X_METER_INVALID` | a `meter:` with a bad name, period or `warnAt`, half a `warnAt`/`onWarn` pair, or a limit resolving to anything but a whole number ≥ 0 | fix the declaration the cause names |
1192
+ | `X_METER_EXCEEDED` | a `meter:`'s allowance for the current UTC period is spent, or a `drawMeter` amount would pass it; `meta.resetsAt` and `Retry-After` say when it resets | wait, or raise what `meter.limit` resolves to for the tenant. A `drawMeter` amount larger than the whole limit fits no period, carries no `Retry-After` and is `terminal` for a job: raise the limit, or, above 0, split the work into draws within it |
1193
+ | `X_METER_INVALID` | a `meter:` with a bad name, period or `warnAt`, half a `warnAt`/`onWarn` pair, or a limit resolving to anything but a whole number ≥ 0; a `drawMeter` with a bad amount (a positive safe integer) or key (1–255 chars, no NUL or lone surrogate), or an installed store that does not declare `keyedDraws: true` | fix the declaration the cause names |
1159
1194
  | `X_ACTION_DEPRECATION_INVALID` | `deprecated:` with a `since`/`sunset` that is not a date | use an ISO-8601 instant |
1160
1195
  | `X_INPUT_INVALID` | input failed the Standard Schema. Carries the rejections **twice**: the flattened line in `cause`, and the structured list in `meta.issues` — one value rendered two ways, `As of 2026-08-24` | `x actions show <name> --json` |
1161
1196
  | `X_IDEMPOTENCY_CONFLICT` | key reused with a new payload / still in flight | new key, or retry later |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/action",
3
- "version": "31.48.0",
3
+ "version": "31.50.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.48.0",
52
- "@ultimat3/core": "31.48.0",
53
- "@ultimat3/db": "31.48.0",
54
- "@ultimat3/entity": "31.48.0",
55
- "@ultimat3/http": "31.48.0",
56
- "@ultimat3/policy": "31.48.0",
57
- "@ultimat3/schema": "31.48.0",
58
- "@ultimat3/storage": "31.48.0"
51
+ "@ultimat3/cache": "31.50.0",
52
+ "@ultimat3/core": "31.50.0",
53
+ "@ultimat3/db": "31.50.0",
54
+ "@ultimat3/entity": "31.50.0",
55
+ "@ultimat3/http": "31.50.0",
56
+ "@ultimat3/policy": "31.50.0",
57
+ "@ultimat3/schema": "31.50.0",
58
+ "@ultimat3/storage": "31.50.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,
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import type { ActionPathStyle } from '@ultimat3/core';
12
- import type { BearerMountRateLimit, BearerResolver } from '@ultimat3/http';
12
+ import type { BearerMountRateLimit, BearerMountTenant, BearerResolver } from '@ultimat3/http';
13
13
  import { OpenApiConfigInvalidError } from './errors-http';
14
14
 
15
15
  /** A second door onto a cut of the API, authenticated by `Authorization: Bearer` alone. */
@@ -32,6 +32,12 @@ export interface ApiMount {
32
32
  * `x verify` refuses it stale, exactly as it does `openapi.json`.
33
33
  */
34
34
  readonly openapi?: string;
35
+ /**
36
+ * One token across tenants: the token resolves to a person, every call names its tenant as
37
+ * `?<arg>=<value>`, and `resolve`'s actor is the caller — the shape `defineAppMcp({ tenant })`
38
+ * takes, so one declaration serves both doors. Adds `GET <prefix>/tenants`.
39
+ */
40
+ readonly tenant?: BearerMountTenant;
35
41
  }
36
42
 
37
43
  export interface ApiHttp {
@@ -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;
@@ -50,8 +50,8 @@ export const ACTION_ERROR_TITLES: Readonly<Record<string, string>> = {
50
50
  X_CONTRACT_EXERCISE_UNREACHED: 'no generated run reached the handler',
51
51
  X_CONTRACT_EXERCISE_UNDECLARED: '.contract() on a non-public action names no exercise',
52
52
  X_ACTION_STREAM_INVALID: 'a streaming action broke its stream contract',
53
- X_METER_EXCEEDED: "an action's usage meter is spent for this period",
54
- X_METER_INVALID: "an action's meter cannot be counted against",
53
+ X_METER_EXCEEDED: 'a usage meter is spent for this period',
54
+ X_METER_INVALID: 'a usage meter cannot be counted against',
55
55
  X_REPLAY_PRINCIPAL_MISMATCH:
56
56
  'a queued offline write was replayed under a session that did not queue it',
57
57
  };
@@ -15,33 +15,89 @@ export interface MeterExceededInput {
15
15
  readonly nowMs: number;
16
16
  }
17
17
 
18
+ /**
19
+ * A `drawMeter` call's refusal: no action to name, the call site is the fix. `amount` is set only
20
+ * when the draw alone is larger than the whole limit, which no reset makes room for.
21
+ */
22
+ export type MeterDrawRefusal = Omit<MeterExceededInput, 'action'> & { readonly amount?: number };
23
+
18
24
  /**
19
25
  * `meta.retryAfterSeconds` is the framework's one spelling of a stated delay: `@ultimat3/http`
20
- * renders it onto `Retry-After`, and a job's retry waits the same number.
26
+ * renders it onto `Retry-After`, and a job's retry waits the same number. A draw larger than the
27
+ * whole limit states none and is `terminal`: no reset admits it, so a job dead-letters it at once
28
+ * instead of waiting out a period to be refused again.
21
29
  */
22
30
  export class MeterExceededError extends UltimateError {
23
- constructor(input: MeterExceededInput) {
31
+ constructor(input: MeterExceededInput | MeterDrawRefusal) {
24
32
  const resetsAt = new Date(input.resetsAtMs).toISOString();
25
33
  const retryAfterSeconds = Math.max(1, Math.ceil((input.resetsAtMs - input.nowMs) / 1000));
34
+ const meterArg = renderFixShellArg(input.meter, '<meter>');
35
+ const oversizedBy = 'action' in input ? undefined : input.amount;
36
+ const oversized = oversizedBy !== undefined;
37
+ // At a limit of 0 no draw is small enough: splitting is advice only above it.
38
+ const split = input.limit > 0 ? `, or split the work into draws of at most ${input.limit}` : '';
26
39
  super({
27
40
  code: 'X_METER_EXCEEDED',
28
- cause: `the "${input.meter}" meter on action "${input.action}" allows ${input.limit} calls per ${input.period} (UTC), and this caller's allowance for the period is spent; it resets at ${resetsAt}`,
29
- fix: `x actions show ${renderFixShellArg(input.action, '<action>')} --json # names the meter and its period; raise what meter.limit resolves to for this tenant in the action file, or retry after meta.resetsAt`,
41
+ ...(oversized
42
+ ? {
43
+ cause: `the "${input.meter}" meter allows ${input.limit} units per ${input.period} (UTC), and this draw of ${oversizedBy} is larger than the whole allowance: nothing was counted, and no reset makes room for it`,
44
+ fix: `grep -rn "drawMeter(" apps/ # the call drawing "${meterArg}": raise what its limit resolves to for this tenant${split}`,
45
+ }
46
+ : !('action' in input)
47
+ ? {
48
+ cause: `the "${input.meter}" meter allows ${input.limit} units per ${input.period} (UTC), and this draw would pass this caller's allowance for the period; nothing was counted, and it resets at ${resetsAt}`,
49
+ fix: `grep -rn "drawMeter(" apps/ # the call drawing "${meterArg}": raise what its limit resolves to for this tenant, or retry after meta.resetsAt`,
50
+ }
51
+ : {
52
+ cause: `the "${input.meter}" meter on action "${input.action}" allows ${input.limit} calls per ${input.period} (UTC), and this caller's allowance for the period is spent; it resets at ${resetsAt}`,
53
+ fix: `x actions show ${renderFixShellArg(input.action, '<action>')} --json # names the meter and its period; raise what meter.limit resolves to for this tenant in the action file, or retry after meta.resetsAt`,
54
+ }),
30
55
  callerFix: `retry after ${resetsAt} (the Retry-After header): the "${input.meter}" allowance resets then, and a larger one is the application's to grant`,
31
- meta: { meter: input.meter, limit: input.limit, resetsAt, retryAfterSeconds },
56
+ ...(oversized
57
+ ? {
58
+ callerFix: `this request needs more of "${input.meter}" than one ${input.period} allows; the application has to grant a larger allowance`,
59
+ retry: 'terminal' as const,
60
+ }
61
+ : {}),
62
+ meta: {
63
+ meter: input.meter,
64
+ limit: input.limit,
65
+ resetsAt,
66
+ ...(oversized ? {} : { retryAfterSeconds }),
67
+ },
32
68
  });
33
69
  }
34
70
  }
35
71
 
36
- export type MeterField = 'name' | 'period' | 'limit' | 'warnAt';
72
+ export type MeterField = 'name' | 'period' | 'limit' | 'warnAt' | 'amount' | 'key' | 'store';
73
+
74
+ /** Where the meter was written: an action's `meter:` block, or a `drawMeter` call. */
75
+ export type MeterSite = 'action' | 'draw';
37
76
 
38
77
  /** A meter declared — or a limit resolved — that no counter could enforce. */
39
78
  export class MeterInvalidError extends UltimateError {
40
- constructor(meter: string, field: MeterField, expected: string, value?: unknown) {
79
+ constructor(
80
+ meter: string,
81
+ field: MeterField,
82
+ expected: string,
83
+ value?: unknown,
84
+ site: MeterSite = 'action',
85
+ ) {
86
+ const meterArg = renderFixShellArg(meter, '<meter>');
41
87
  super({
42
88
  code: 'X_METER_INVALID',
43
- cause: `meter "${meter}" declares ${field}${value === undefined ? '' : ` = ${renderCauseValue(value)}`}, which is not ${expected}`,
44
- fix: `meter: { name: 'calls', period: 'day', limit: ({ ctx }) => 500, warnAt: 0.8, onWarn: quotaWarning } # edit the action declaring "${renderFixShellArg(meter, '<meter>')}" — ${field} must be ${expected}`,
89
+ ...(field === 'store'
90
+ ? {
91
+ cause: `meter "${meter}" is drawn on an installed meter store that is not ${expected}: a store written before keyed draws counts one call per draw and never replays, so nothing was counted`,
92
+ fix: `meterStore: { ...store, keyedDraws: true }, // apps/<app>/runtime.ts: keep the store's own scope, add amount and drawKey to its draw(), and pass meterStoreConformance from @ultimat3/testing`,
93
+ }
94
+ : {
95
+ cause: `meter "${meter}" declares ${field}${value === undefined ? '' : ` = ${renderCauseValue(value)}`}, which is not ${expected}`,
96
+ fix:
97
+ site === 'draw'
98
+ ? `drawMeter(ctx, { meter: 'tokens', period: 'day', amount: 1200, limit: ({ ctx }) => 100_000, key: run.id }); // edit the drawMeter call drawing "${meterArg}": ${field} must be ${expected}`
99
+ : `meter: { name: 'calls', period: 'day', limit: ({ ctx }) => 500, warnAt: 0.8, onWarn: quotaWarning }, // edit the action declaring "${meterArg}": ${field} must be ${expected}`,
100
+ }),
45
101
  meta: { meter, field },
46
102
  });
47
103
  }
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() {