@uru-intelligence/app 2.2.1 → 2.2.5

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/README.md CHANGED
@@ -53,7 +53,8 @@ const page = await uru.datasets.queryRows('sales', {
53
53
  sort: [{ field: 'closed_at', direction: 'desc' }],
54
54
  });
55
55
 
56
- // Actions: run a declared capability and decode its result, or throw.
56
+ // Actions: run a declared capability, wait until it ends, and decode its
57
+ // result, or throw.
57
58
  const summary = await uru.actions.run('summarize', { region: 'emea' }, {
58
59
  decodeResult: value => {
59
60
  if (typeof value !== 'string') {
@@ -82,7 +83,10 @@ Use `createUruBackgroundJobCoordinator` when a caller must recover after a
82
83
  lost start response or a process restart. It uses the existing `job`,
83
84
  `jobStatus`, and `cancelJob` operations. It does not own job state.
84
85
 
85
- The caller supplies a durable store scoped to the deployment and viewer. Its
86
+ The caller supplies a durable store scoped to the Gem and the viewer, not to one
87
+ deployment: a job started before a new release of the Gem stays in the store,
88
+ and the next release observes, waits on, cancels and resumes it. Each record
89
+ keeps the deployment that saved it, for your own audit. Its
86
90
  `create` operation must insert only when the key is absent. Its three update
87
91
  operations must be atomic and must preserve the saved request. The helper saves
88
92
  the idempotency key, input, timeout, and absolute deadline before it starts a
@@ -119,13 +123,21 @@ if (started.response.pending) {
119
123
  showResult(outcome.status.result);
120
124
  }
121
125
  }
126
+
127
+ // Every lifecycle method accepts the same local AbortSignal and callbacks.
128
+ const requestSignal = new AbortController().signal;
129
+ const callOptions = { signal: requestSignal };
130
+ await jobs.observe(request.idempotencyKey, callOptions);
131
+ await jobs.wait(request.idempotencyKey, callOptions);
132
+ await jobs.cancel(request.idempotencyKey, callOptions);
133
+ await jobs.resume(request.idempotencyKey, callOptions);
122
134
  ```
123
135
 
124
136
  After a lost start response, call `resume` with the same key. The helper sends
125
137
  the saved input, key, and timeout again. The server uses that key to return the
126
138
  same accepted work. It does not create a new logical request. While the caller's
127
- store keeps the saved row, the helper refuses changed input, timeout, deployment,
128
- or deadline for that key. The deadline is local. The helper does not send it to
139
+ store keeps the saved row, the helper refuses changed input, timeout, or
140
+ deadline for that key. The deadline is local. The helper does not send it to
129
141
  the server. If the caller deletes the row, the helper cannot enforce the saved
130
142
  request identity or deadline.
131
143
 
@@ -136,6 +148,234 @@ the returned status until it is terminal. Status and result access still follow
136
148
  the server's current job-status contract. This helper cannot recover a result
137
149
  that the server no longer exposes.
138
150
 
151
+ ## Customer job patterns
152
+
153
+ The examples below use the coordinator above and small Gem-owned handlers. Each
154
+ caller supplies a durable store. It saves one request before dispatch. After a
155
+ restart, resume with the same key. Keep the original input and deadline.
156
+
157
+ The package includes all four examples under
158
+ `@uru-intelligence/app/examples/customer-workflows/*`. These are runnable
159
+ JavaScript modules with TypeScript declarations. They do not require this
160
+ repository.
161
+
162
+ ### Scheduled collector
163
+
164
+ Declare a program job with a schedule in `uru.json`. The schedule owns recurring
165
+ starts. A manual catch-up request can use the coordinator too. Give that request
166
+ a saved id and one fixed deadline:
167
+
168
+ ```json
169
+ {
170
+ "capabilities": {
171
+ "jobs": {
172
+ "collect_orders": {
173
+ "handler": { "module": "src/jobs.ts", "export": "collectOrders" },
174
+ "input": { "sourceId": "orders" },
175
+ "schedule": { "cron": "0 * * * *", "timeZone": "America/Chicago" }
176
+ }
177
+ }
178
+ }
179
+ }
180
+ ```
181
+
182
+ ```ts
183
+ const key = `collector:${sourceId}:${requestId}`;
184
+ const request = {
185
+ capabilityName: "collect_orders",
186
+ idempotencyKey: key,
187
+ input: { sourceId },
188
+ deadlineAt,
189
+ timeoutMs: 25_000,
190
+ };
191
+ const started = await jobs.start(request);
192
+ // After a restart, use jobs.resume(key). Do not make a new key.
193
+ ```
194
+
195
+ The installed collector keeps provider order ids in customer fields. Each new
196
+ order uses a null row id, so Uru creates its UUID. Before the first run, create
197
+ one `collector_state` row with `{ sourceId: "orders", nextCursor: null }`.
198
+ The handler queries that row and uses its Uru UUID for each cursor update. It
199
+ never uses `sourceId` as a Dataset row id.
200
+
201
+ This example reads an append-only source. Each source order id must occur once.
202
+ A source that sends later order changes needs a durable map from each source id
203
+ to its Uru row UUID.
204
+
205
+ ```ts
206
+ import { collectScheduledOrders } from
207
+ "@uru-intelligence/app/examples/customer-workflows/scheduled-collector";
208
+
209
+ export const collectOrders = (input, checkpoint, signal) =>
210
+ collectScheduledOrders(uru, input, checkpoint, signal, readOrdersPage);
211
+ ```
212
+
213
+ Declare and grant the `collector_state` and `collected_orders` Datasets before
214
+ the Build. Create exactly one state row for each source before its schedule can
215
+ run. `readOrdersPage` is Gem code for an approved read connection. Keep provider
216
+ cursors private. Uru owns recurrence and run status. The private Dataset cursor
217
+ carries collection position across runs, so no second local scheduler is needed.
218
+
219
+ Store the input cursor, an explicit sequence, and the cumulative page count in
220
+ each page step result. Checkpoint the same sequence and count after the step.
221
+ The checkpoint is stored as JSON data, where object key order is not a page
222
+ order. On recovery, sort validated steps by their sequence. Use the newest
223
+ step's cumulative count, even when the separate cursor checkpoint was lost.
224
+ Reject a saved step gap. The first saved step must be page 1.
225
+
226
+ ### Review-only draft
227
+
228
+ Create a draft output and stop at review. This path writes no external service.
229
+ Give each draft a stable id:
230
+
231
+ ```ts
232
+ const key = `review-draft:${draftId}`;
233
+ const started = await jobs.start({
234
+ capabilityName: "save_review_draft",
235
+ idempotencyKey: key,
236
+ input: { draftId, markdown },
237
+ deadlineAt,
238
+ timeoutMs: 25_000,
239
+ });
240
+ // In the program job, save the output inside a named step.
241
+ const output = await uru.jobs.step("save review draft", async step => {
242
+ if (signal.aborted) return { kind: "canceled" };
243
+ const created = await uru.files.createOutput({
244
+ name: `${draftId}.md`,
245
+ contentType: "text/markdown",
246
+ content: new TextEncoder().encode(markdown),
247
+ idempotencyKey: step.idempotencyKey,
248
+ signal,
249
+ });
250
+ return { kind: "review_required", outputId: created.outputId };
251
+ });
252
+ if (output.kind === "review_required") {
253
+ await uru.jobs.checkpoint({
254
+ draftId,
255
+ phase: output.kind,
256
+ outputId: output.outputId,
257
+ });
258
+ }
259
+ return output;
260
+ ```
261
+
262
+ Keep `draftId` fixed while recovering the same draft. The named step keeps its
263
+ write key across attempts of the same job run, so a lost response does not
264
+ create a second file. A person must review the output before a separate
265
+ capability can send or publish it.
266
+
267
+ ### File processor
268
+
269
+ Pass a Uru file id, not a URL or file bytes from the browser. `files.read`
270
+ checks access. Save processed bytes with a key tied to the file and processor
271
+ version:
272
+
273
+ ```ts
274
+ const key = `file:${fileId}:processor:${processorVersion}`;
275
+ const started = await jobs.start({
276
+ capabilityName: "process_file",
277
+ idempotencyKey: key,
278
+ input: { fileId, processorVersion },
279
+ deadlineAt,
280
+ timeoutMs: 25_000,
281
+ });
282
+ // In the program job, put the output write in a named step.
283
+ const file = await uru.files.read(fileId, { signal });
284
+ const processed = await transformFile(file, signal);
285
+ const output = await uru.jobs.step("write processed file", async step => {
286
+ if (signal.aborted) return { kind: "canceled" };
287
+ const created = await uru.files.createOutput({
288
+ name: processed.name,
289
+ contentType: processed.contentType,
290
+ content: processed.content,
291
+ idempotencyKey: step.idempotencyKey,
292
+ signal,
293
+ });
294
+ return { kind: "complete", outputId: created.outputId };
295
+ });
296
+ if (output.kind === "complete") {
297
+ await uru.jobs.checkpoint({
298
+ fileId,
299
+ processorVersion,
300
+ phase: output.kind,
301
+ outputId: output.outputId,
302
+ });
303
+ }
304
+ ```
305
+
306
+ If the output response is lost, rerun with the same file id, processor version,
307
+ and job key. Do not use a new key to repeat the same processing request.
308
+
309
+ ### Approved external write
310
+
311
+ Load the approved intent from a trusted server after a person confirms the
312
+ exact target and payload. The server loader must verify the authenticated actor
313
+ and every approved field. Do not use a browser value or a writable Dataset row
314
+ as proof of approval. The job must name the exact bound tool role and operation.
315
+ Uru checks current connection access and Tool Approval when it runs that action.
316
+
317
+ The app package job runtime does not expose a verified actor ID to Gem code.
318
+ Your app must inject a trusted loader that can verify the actor and current
319
+ approval. If it cannot, the loader must return no intent and the write must
320
+ stop. This package example does not provide approval storage.
321
+
322
+ ```ts
323
+ const intent = await loadApprovedIntentForAuthenticatedActor(approvalId);
324
+ if (!intent) throw new Error("No approved intent");
325
+ const key = `external-write:${intent.approvalId}`;
326
+ const started = await jobs.start({
327
+ capabilityName: "send_approved_update",
328
+ idempotencyKey: key,
329
+ input: {
330
+ approvalId: intent.approvalId,
331
+ approvedByActorId: intent.approvedByActorId,
332
+ targetId: intent.targetId,
333
+ payload: intent.payload,
334
+ },
335
+ deadlineAt: intent.deadlineAt,
336
+ timeoutMs: 25_000,
337
+ });
338
+ // If the reply is lost, call jobs.resume(key). Do not start a new request.
339
+ ```
340
+
341
+ Bind the same trusted server check to the published job handler. The handler
342
+ reads the saved step before it checks renewed approval. A saved result survives
343
+ revocation. A new or incomplete step must pass the server check before it calls
344
+ the provider.
345
+
346
+ ```ts
347
+ import { createUruServerContext } from "@uru-intelligence/app";
348
+ import { createSendApprovedUpdateHandler } from "./approved-external-write.js";
349
+ import { loadApprovedIntentForJobActor } from "./trusted-approval-server.js";
350
+
351
+ export const sendApprovedUpdate = createSendApprovedUpdateHandler(
352
+ createUruServerContext,
353
+ (env) => (approvalId, signal) =>
354
+ loadApprovedIntentForJobActor(env, approvalId, signal),
355
+ );
356
+ ```
357
+
358
+ `loadApprovedIntentForJobActor` is app-owned code. It must read a server-owned
359
+ approval record, resolve the actor from the trusted job run, and verify that
360
+ actor may use the approval. The returned target and payload must match the
361
+ approved record. The runtime environment has the job run id, but it has no
362
+ verified actor id. Do not treat an actor id in job input as proof. Do not grant
363
+ Gem code write access to the approval record. A loader without trusted actor
364
+ data must return no intent. The loader must accept the job's abort signal and
365
+ stop its request when the job is canceled. Check the signal again after the
366
+ lookup. A cancellation before the provider call is canceled, not an unknown
367
+ provider result. Use the action start event to find this boundary. After that
368
+ event, keep an uncertain provider result open.
369
+
370
+ If the provider result is unknown, keep that result open. Check the same Uru
371
+ run and provider before a person approves another request. Never use a new key
372
+ to force an uncertain write to complete.
373
+
374
+ The executable source examples test these patterns against this repository's
375
+ package source. This does not prove an installed npm version. After the
376
+ protected npm release, install the exact published version in a clean Gem and
377
+ repeat the checks before claiming installed-package support.
378
+
139
379
  ## Program job handlers
140
380
 
141
381
  A Gem can declare a job that runs code from its published source:
@@ -191,6 +431,25 @@ Uru runs a lost job attempt again from its start, under the same job run, with
191
431
  the last checkpoint. Put the job's writes in `jobs.step` so that the next
192
432
  attempt can run safely.
193
433
 
434
+ Uru also runs the job again when the handler throws a temporary answer from
435
+ Uru after the SDK's own resends ran out: a 408, 429 or 503 that does not say
436
+ `retryable: false`, a 502 or 504 that no server answered, Cloudflare's own 520
437
+ to 527 or 530, or a 500 with no Uru error code, which a proxy in front of Uru
438
+ gave. This needs a job that is still retryable (see below), an attempt left
439
+ (three in all), and no cancel. Any other answer ends the job: a 500 with Uru's
440
+ error code, a 403, 404, 409 or 422, or an error from your own code.
441
+
442
+ On the next attempt:
443
+
444
+ - Steps that finished return their saved results and do not run again.
445
+ - The step that was cut short runs again from its start. Its actions, job
446
+ starts and Dataset row writes send the same keys, and so does a file output
447
+ that passes `step.idempotencyKey`, so Uru answers each one from its first
448
+ run and nothing is written twice.
449
+ - Everything else runs again: reads, code outside a step, and every HTTP
450
+ request your code sends to another service. Give such a request
451
+ `step.idempotencyKey` when the service accepts one.
452
+
194
453
  A step runs once per job run: its result is saved in the checkpoint, and the
195
454
  next attempt returns the saved result without running the step. Inside a step,
196
455
  each action, job start and Dataset row write gets a default key that the job
@@ -209,7 +468,7 @@ const ids = await uru.jobs.step('load', async () => {
209
468
  });
210
469
  for (const id of ids) {
211
470
  await uru.jobs.step(`send ${id}`, async step => {
212
- await uru.actions.run('send_invoice', { id });
471
+ await uru.actions.run('send_invoice', { id }, { signal });
213
472
  await uru.files.createOutput({
214
473
  name: `${id}.txt`,
215
474
  contentType: 'text/plain',
@@ -220,6 +479,12 @@ for (const id of ids) {
220
479
  }
221
480
  ```
222
481
 
482
+ - `actions.run` returns when the action has ended. An action that takes
483
+ longer than the server's short wait answers pending; `actions.run` then
484
+ reads its status until it ends, and returns its result or throws its
485
+ failure. Pass the handler's `signal`, so a canceled job stops waiting. Do
486
+ not give a write a short `timeoutMs`: it bounds the whole wait, and when it
487
+ ends the call throws while the action goes on.
223
488
  - Give each step its own name, and run steps one at a time. While a step runs,
224
489
  make only that step's calls.
225
490
  - A step must make the same calls in the same order each time it runs. Save
@@ -281,8 +546,8 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
281
546
  A custom retry wait can accept the optional `AbortSignal` to stop its own
282
547
  work. The SDK still bounds the call when that wait ignores the signal.
283
548
  - **Calls ride out a restarting server.** When Uru gives no answer (a failed
284
- or reset connection, a reply cut off after its headers, HTTP 502 or 504, or
285
- a 503 without an Uru error code),
549
+ or reset connection, a reply cut off after its headers, HTTP 502 or 504, a
550
+ 503 without an Uru error code, or Cloudflare's own 520 to 527 or 530),
286
551
  the client sends the call again after about 0.5, 1, 2, 4, 8, 8 and 8
287
552
  seconds, each stretched by up to twice for jitter: about a minute in all.
288
553
  Each wait reports a `reconnecting` status event. An action or a job start
@@ -290,13 +555,46 @@ const response = await app.query('summary', {}, { onStatus: event => render(even
290
555
  instead of running it twice. A query sends a new key each time. Job status
291
556
  reads, job cancels, `jobs.progress` and `jobs.checkpoint` are always sent
292
557
  again. A Dataset row write is sent again with its key (each call gets one
293
- when you give none). An endpoint, a server function and `sqlWrite` are never
294
- sent again, because they have no stored result to replay. `sqlWrite` still
295
- sends a key: if your code sends the same statement again with the same
296
- `idempotencyKey`, each row change it planned is replayed when the plan is
297
- unchanged and refused when it changed, so the statement never writes twice. The caller's
558
+ when you give none). An endpoint and a server function are never sent
559
+ again, because they have no stored result to replay. `sqlWrite` is not sent
560
+ again either. It still sends a key: if your code sends the same statement
561
+ again with the same `idempotencyKey`, Uru returns the first result with
562
+ `replayed: true` and does not run the statement again, so the statement
563
+ never writes twice. The same key with another statement fails, and a
564
+ refusal stays saved under the key, so give a new attempt a new key. A
565
+ statement over 2 or more Datasets that fails with `partial_write` saved
566
+ some Datasets and not others: do not send it again with a new key, which
567
+ writes the saved Datasets again. The caller's
298
568
  `signal` and `timeoutMs` end the waits. Set `dampers.maxTransportRetries` to
299
- `0` to turn resends off.
569
+ `0` to turn resends off. The SDK then does not tell the Uru gateway of a
570
+ hosted job that it resends, so the gateway may still send a call that is safe
571
+ to repeat again after a lost answer, a temporary answer or a 500 with no Uru
572
+ error code.
573
+ - **Job writes ride out a short database stall.** A Dataset row write with a
574
+ key, `jobs.progress` and `jobs.checkpoint` are also sent again when Uru
575
+ answers that it cannot serve the call now: HTTP 408, 429 or 503. They use
576
+ the same waits, or the answer's `Retry-After` when that is longer. When the
577
+ `Retry-After` is longer than the wait time that is left, the call throws
578
+ that answer at once and never sends before the server allows. A row
579
+ write sends the same key each time, so the server joins the first command
580
+ and never writes twice. They are also sent again, at most twice, after a
581
+ 500 with no Uru error code: Uru answers its own 500 with an error code, so
582
+ a 500 without one came from a proxy in front of Uru. Every other answer is
583
+ final and is never sent again: a 500 with Uru's error code, a 403, 404,
584
+ 409, 422 or any other status, an error body with `retryable: false`, or a
585
+ setup failure that a resend cannot fix. When the resends run out, the call
586
+ throws `UruAppRuntimeError` with the last status and the answer's parsed
587
+ body. A file call and an upload that are not accepted keep that body too.
588
+ - **A query rides out a short stall too.** A query only reads, so it is also
589
+ sent again, with a new key, after HTTP 408 or a 503 that is not final, such
590
+ as Uru's 503 when its database pool is full for a moment. It uses the
591
+ lost-answer waits above. A 429 keeps its rate-limit waits, and an action or
592
+ a job start keeps a temporary answer as its result.
593
+ - **How long a call can take.** All the waits of one call add up to at most
594
+ 63 seconds. A send that gets no answer counts as lost after 30 seconds, so
595
+ in the worst case (8 sends that each run 30 seconds) a Dataset row write,
596
+ `jobs.progress` or `jobs.checkpoint` returns or throws after about 5
597
+ minutes. A fast temporary answer ends it after about a minute.
300
598
 
301
599
  ## Transport values
302
600
 
@@ -369,8 +667,8 @@ Use `datasetRowForMutation(row)` with `upsertRowViews` to keep row identity
369
667
  separate from customer data. This saves a customer field named `id` without
370
668
  changing the native row id. It also sends `rowVersion` as the row precondition.
371
669
  Pass the page's `revision` as `expectedDatasetRevision` when it must match the
372
- read. Use flat `upsertRows` calls for new or partial rows that do not need to
373
- carry a customer field named `id`. A customer field named `fields` is read or
670
+ read. Use flat `upsertRows` calls only when the customer schema has no field
671
+ named `id`. A customer field named `fields` is read or
374
672
  edited as `row.fields.fields`, because `row.fields` is the customer-field map.
375
673
 
376
674
  Capability and job-status envelopes can omit `result` or return `null` while
@@ -473,7 +771,12 @@ an `idempotencyKey` to reject changes made since that read:
473
771
  ```ts
474
772
  const page = await uru.datasets.queryRows('contacts', { limit: 1 });
475
773
  if (page.revision === undefined) throw new Error('Native revision required');
476
- await uru.datasets.upsertRows('contacts', [{ id: rowId, name: 'Updated' }],
774
+ const saved = page.rows[0];
775
+ if (!saved) throw new Error('Contact row required');
776
+ await uru.datasets.upsertRowViews('contacts', [
777
+ { rowId: saved.id, expectedRowVersion: saved.rowVersion ?? null,
778
+ fields: { ...saved.fields, name: 'Updated' } },
779
+ ],
477
780
  undefined, { expectedDatasetRevision: page.revision, idempotencyKey: saveId });
478
781
  ```
479
782
 
@@ -3,5 +3,9 @@ import type { CreateUruBackgroundJobCoordinatorOptions, UruBackgroundJobCoordina
3
3
  * Coordinate the released `job`, `jobStatus`, and `cancelJob` operations.
4
4
  * The store saves request identity and control intent only; the server remains
5
5
  * authoritative for execution state and results.
6
+ *
7
+ * A record keeps the deployment that saved it, for the caller's audit only.
8
+ * The coordinator of a later release of the same Gem observes, waits on,
9
+ * cancels and resumes it through its own client.
6
10
  */
7
11
  export declare const createUruBackgroundJobCoordinator: (options: CreateUruBackgroundJobCoordinatorOptions) => UruBackgroundJobCoordinator;
@@ -1,8 +1,8 @@
1
1
  import { UruAppRuntimeError } from "./errors.js";
2
+ import { isFinalExecutionStatus } from "./runtime.js";
2
3
  import { awaitWithAbort, abortReason } from "./transport-deadline.js";
3
4
  import { isRuntimeJsonObject } from "./transport-json.js";
4
5
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
5
- const TERMINAL_STATES = new Set(["succeeded", "failed", "canceled", "cancelled"]);
6
6
  class JobDeadlineExceeded extends Error {
7
7
  constructor() {
8
8
  super("The background job deadline expired.");
@@ -129,20 +129,18 @@ const recordForStore = (record) => ({
129
129
  cancelRequested: record.cancelRequested,
130
130
  cancelAcknowledged: record.cancelAcknowledged,
131
131
  });
132
+ /**
133
+ * Whether two records hold the same logical request. The deployment that saved
134
+ * a record is not part of it: every release of the same Gem resumes the
135
+ * request, and the server answers its key and its execution across releases.
136
+ */
132
137
  const sameRequest = (left, right) => left.idempotencyKey === right.idempotencyKey &&
133
- left.deploymentId === right.deploymentId &&
134
138
  left.capabilityName === right.capabilityName &&
135
139
  left.deadlineAt === right.deadlineAt &&
136
140
  left.timeoutMs === right.timeoutMs &&
137
141
  canonicalInput(left.input) === canonicalInput(right.input);
138
- const terminalStatus = (status) => {
139
- if (status.pending === true)
140
- return false;
141
- return (status.pending === false ||
142
- status.success === true ||
143
- TERMINAL_STATES.has(status.state ?? "") ||
144
- TERMINAL_STATES.has(status.status ?? ""));
145
- };
142
+ /** Whether the store kept every saved field of a record it wrote. */
143
+ const sameSavedRecord = (actual, expected) => sameRequest(actual, expected) && actual.deploymentId === expected.deploymentId;
146
144
  const defaultSleep = async (milliseconds, signal) => {
147
145
  let remaining = Math.max(0, milliseconds);
148
146
  await new Promise((resolve, reject) => {
@@ -245,6 +243,10 @@ const retryDelay = (status, pollIntervalMs) => {
245
243
  * Coordinate the released `job`, `jobStatus`, and `cancelJob` operations.
246
244
  * The store saves request identity and control intent only; the server remains
247
245
  * authoritative for execution state and results.
246
+ *
247
+ * A record keeps the deployment that saved it, for the caller's audit only.
248
+ * The coordinator of a later release of the same Gem observes, waits on,
249
+ * cancels and resumes it through its own client.
248
250
  */
249
251
  export const createUruBackgroundJobCoordinator = (options) => {
250
252
  const deploymentId = options.deploymentId.trim();
@@ -279,9 +281,7 @@ export const createUruBackgroundJobCoordinator = (options) => {
279
281
  if (value === null)
280
282
  return null;
281
283
  const record = recordFromUnknown(value);
282
- if (record === null ||
283
- record.idempotencyKey !== key ||
284
- record.deploymentId !== deploymentId) {
284
+ if (record === null || record.idempotencyKey !== key) {
285
285
  throw invalidRecordError();
286
286
  }
287
287
  return record;
@@ -295,10 +295,7 @@ export const createUruBackgroundJobCoordinator = (options) => {
295
295
  };
296
296
  const validateUpdatedRecord = (expected, value) => {
297
297
  const actual = recordFromUnknown(value);
298
- if (actual === null ||
299
- actual.idempotencyKey !== expected.idempotencyKey ||
300
- actual.deploymentId !== deploymentId ||
301
- !sameRequest(actual, expected)) {
298
+ if (actual === null || !sameSavedRecord(actual, expected)) {
302
299
  throw invalidRecordError();
303
300
  }
304
301
  return actual;
@@ -331,7 +328,7 @@ export const createUruBackgroundJobCoordinator = (options) => {
331
328
  }
332
329
  const status = await options.app.jobStatus(record.executionId, copyCallOptions(callOptions));
333
330
  const common = { record, executionId: record.executionId, status };
334
- return terminalStatus(status)
331
+ return isFinalExecutionStatus(status)
335
332
  ? { kind: "complete", ...common }
336
333
  : { kind: "pending", ...common };
337
334
  };
@@ -445,9 +442,7 @@ export const createUruBackgroundJobCoordinator = (options) => {
445
442
  if (typeof created.created !== "boolean")
446
443
  throw invalidRecordError();
447
444
  const savedRecord = recordFromUnknown(created.record);
448
- if (savedRecord === null ||
449
- savedRecord.idempotencyKey !== key ||
450
- savedRecord.deploymentId !== deploymentId) {
445
+ if (savedRecord === null || savedRecord.idempotencyKey !== key) {
451
446
  throw invalidRecordError();
452
447
  }
453
448
  if (!created.created) {
@@ -456,7 +451,7 @@ export const createUruBackgroundJobCoordinator = (options) => {
456
451
  }
457
452
  throw runtimeError("This background job already exists. Use resume.");
458
453
  }
459
- if (!sameRequest(savedRecord, record))
454
+ if (!sameSavedRecord(savedRecord, record))
460
455
  throw invalidRecordError();
461
456
  const response = await withDeadline({
462
457
  deadlineAt: record.deadlineAt,
package/dist/dampers.d.ts CHANGED
@@ -23,10 +23,17 @@ export interface UruRunawayDamperOptions {
23
23
  maxRateLimitRetries?: number;
24
24
  /**
25
25
  * Max resends after a response the platform never gave: a failed or reset
26
- * connection, a reply cut off after its headers, a 502, a 504, or a 503
27
- * without a platform error code. The waits are about 0.5, 1, 2, 4, 8, 8 and
28
- * 8 seconds, each stretched by up to twice for jitter (default 7; `<= 0`
29
- * disables resends).
26
+ * connection, a send with no answer after 30 seconds, a reply cut off after
27
+ * its headers, a 502, a 504, or a 503 without a platform error code. A keyed
28
+ * Dataset row write, `jobs.progress` and `jobs.checkpoint` are also sent
29
+ * again after a temporary answer: a 408, a 429 or a 503 that does not say
30
+ * `retryable: false`. The waits are about 0.5, 1, 2, 4, 8, 8 and 8 seconds,
31
+ * each stretched by up to twice for jitter; a temporary answer's
32
+ * `Retry-After` can make a wait longer, and one longer than the wait time
33
+ * left ends the resends at once. All the waits of one call add up to
34
+ * at most 63 seconds. Each send can also run 30 seconds before it counts as
35
+ * lost, so in the worst case one call takes about 5 minutes: 8 sends of 30
36
+ * seconds and 63 seconds of waits (default 7; `<= 0` disables resends).
30
37
  */
31
38
  maxTransportRetries?: number;
32
39
  /** Jitter source in [0, 1); injectable for tests. Defaults to `Math.random`. */
package/dist/datasets.js CHANGED
@@ -32,7 +32,7 @@ const fetchDatasetWrite = async (options, subpath, body, send) => {
32
32
  body: serializedBody,
33
33
  config: send.config,
34
34
  headers,
35
- resendLost: send.resendLost,
35
+ repeatable: send.repeatable,
36
36
  runtimeFetch,
37
37
  sendTimeoutMs: 30_000,
38
38
  url,
@@ -50,8 +50,9 @@ const postProviderDatasetWrite = async (options, subpath, body, send) => decodeD
50
50
  const postProviderDatasetWriteDecoded = async (options, subpath, body, send, decodeResult) => decodeDatasetMutationResult(await fetchDatasetWrite(options, subpath, body, send), decodeResult);
51
51
  /**
52
52
  * One row write's body with its key. Each call gets its own key, and every
53
- * send of that call carries it, so a resend after a lost response is a replay
54
- * of the stored command rather than a second write.
53
+ * send of that call carries it, so a resend after a lost response or a
54
+ * temporary answer joins the stored command rather than making a second
55
+ * write.
55
56
  */
56
57
  const keyedMutationBody = (body, mutationOptions, config, keys, datasetRef) => {
57
58
  const callerKey = mutationOptions?.idempotencyKey;
@@ -66,7 +67,7 @@ const keyedMutationBody = (body, mutationOptions, config, keys, datasetRef) => {
66
67
  ...mutationOptions,
67
68
  ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
68
69
  },
69
- send: { config, resendLost: idempotencyKey !== undefined },
70
+ send: { config, repeatable: idempotencyKey !== undefined },
70
71
  };
71
72
  };
72
73
  const datasetMutationPath = (datasetRef) => {
@@ -169,10 +170,10 @@ const createIdMutationInvoker = (options, config, keys, operation) => {
169
170
  return mutate;
170
171
  };
171
172
  const createSqlWriteInvoker = (options, config, keys) => {
172
- // A SQL statement has no stored command to replay, so it is never sent
173
- // again here. Its key lets the server answer a caller's own second send of
174
- // the same call with the first result instead of running it twice.
175
- const send = { config, resendLost: false };
173
+ // A SQL statement is never sent again here. Its key lets the server answer
174
+ // a caller's own second send of the same statement with the first saved
175
+ // result instead of running it twice.
176
+ const send = { config, repeatable: false };
176
177
  async function write(sql, writeOptions, decodeResult) {
177
178
  const body = sqlBody(sql, writeOptions, config, keys);
178
179
  if (decodeResult === undefined) {
package/dist/errors.js CHANGED
@@ -13,15 +13,14 @@ const SAFE_RUNTIME_FAILURE_CODES = new Set([
13
13
  "policy_receipt_handoff_invalid",
14
14
  "mcp_proxy_not_configured",
15
15
  "missing_api_key",
16
- "dataset_frozen_gem_release_unverified",
17
- "dataset_frozen_gem_compatibility_disabled",
16
+ "row_conflict",
17
+ "dataset_conflict",
18
+ "idempotency_conflict",
18
19
  "timeout",
19
20
  "transport_error",
20
21
  "connection_unavailable",
21
22
  "artifact_tool_receipt_unavailable",
22
23
  "artifact_tool_attempt_unavailable",
23
- "tool_result_content_unavailable",
24
- "tool_parameters_content_unavailable",
25
24
  "artifact_tool_refresh_failed",
26
25
  "tool_admission_unavailable",
27
26
  "tool_gateway_denied",
@@ -72,6 +71,7 @@ const SAFE_RUNTIME_FAILURE_CODES = new Set([
72
71
  "job_cleanup_failed",
73
72
  "job_completion_not_accepted",
74
73
  "job_handler_failed",
74
+ "job_import_failed",
75
75
  "job_hard_deadline",
76
76
  "job_machine_start_failed",
77
77
  "job_machine_stopped",