@hotmeshio/hotmesh 0.26.0 → 0.26.2

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.26.0",
3
+ "version": "0.26.2",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WorkflowHandleService = void 0;
4
+ const utils_1 = require("../../modules/utils");
4
5
  const exporter_1 = require("./exporter");
5
6
  /**
6
7
  * Handle to a running or completed workflow execution. Returned by
@@ -253,8 +254,13 @@ class WorkflowHandleService {
253
254
  return complete(null, JSON.parse(state.metadata.err));
254
255
  }
255
256
  }
256
- //subscribe to 'done' topic
257
- this.hotMesh.sub(topic, async (_topic, state) => {
257
+ //subscribe to 'done' topic. Await the registration: the getStatus
258
+ //fallback below only covers completions that land BEFORE it reads.
259
+ //Unawaited, a job that completes after the status read but before
260
+ //the subscription goes active is seen by neither arm and result()
261
+ //never settles — hit reliably when a bulk resolve completes many
262
+ //workflows in the same instant.
263
+ await this.hotMesh.sub(topic, async (_topic, state) => {
258
264
  this.hotMesh.unsub(topic);
259
265
  if (state.data.done && !state.data?.$error) {
260
266
  await complete(state.data?.response);
@@ -267,10 +273,43 @@ class WorkflowHandleService {
267
273
  return await complete(null, error);
268
274
  }
269
275
  });
270
- //check state in case completed during wiring
271
- const status = await this.hotMesh.getStatus(this.workflowId);
272
- if (status <= 0) {
273
- await complete();
276
+ //check state in case completed during wiring. One read is not
277
+ //enough: the executed event commits before the status decrement,
278
+ //so a job caught mid-close shows status > 0 with its event already
279
+ //published — a subscriber wiring up in that window misses both
280
+ //arms. Escalating re-checks close the window (the status settles
281
+ //milliseconds after the publish), and the slow steady poll keeps
282
+ //result() live even if the notification itself is lost (NOTIFY
283
+ //carries no durability across connection drops).
284
+ const settleIfComplete = async () => {
285
+ if (isResolved)
286
+ return true;
287
+ const status = await this.hotMesh.getStatus(this.workflowId);
288
+ if (isResolved)
289
+ return true;
290
+ if (status <= 0) {
291
+ await complete();
292
+ this.hotMesh.unsub(topic);
293
+ return true;
294
+ }
295
+ return false;
296
+ };
297
+ if (!(await settleIfComplete())) {
298
+ void (async () => {
299
+ const RECHECK_DELAYS_MS = [250, 1000, 5000];
300
+ for (const delay of RECHECK_DELAYS_MS) {
301
+ await (0, utils_1.sleepFor)(delay);
302
+ if (await settleIfComplete())
303
+ return;
304
+ }
305
+ while (!isResolved) {
306
+ await (0, utils_1.sleepFor)(30000);
307
+ if (await settleIfComplete())
308
+ return;
309
+ }
310
+ })().catch(() => {
311
+ //the subscription remains the primary completion arm
312
+ });
274
313
  }
275
314
  });
276
315
  }
@@ -1,7 +1,7 @@
1
1
  import { HotMesh } from '../hotmesh';
2
2
  import { EventsConfig } from '../../types/system_events';
3
3
  import { Connection } from '../../types/durable';
4
- import { EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, StatsEscalationsParams, EscalationStats, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, EscalateToRoleParams, MigrateEscalationParams, ClaimManyParams, EscalateManyToRoleParams, UpdateManyPriorityParams, ResolveManyParams, PruneEscalationsParams, PruneEscalationsResult } from '../../types/hmsh_escalations';
4
+ import { EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, StatsEscalationsParams, EscalationStats, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, EscalateToRoleParams, MigrateEscalationParams, ClaimManyParams, EscalateManyToRoleParams, UpdateManyPriorityParams, ResolveManyParams, ResolveAllOrNoneParams, ResolveAllOrNoneResult, PruneEscalationsParams, PruneEscalationsResult } from '../../types/hmsh_escalations';
5
5
  export type GetHotMeshFn = (topic: string | null, namespace?: string) => Promise<HotMesh>;
6
6
  export interface EscalationClientConfig {
7
7
  /** Postgres connection options — used when creating a standalone EscalationClient. */
@@ -171,6 +171,12 @@ export declare class EscalationClientService {
171
171
  * making it `@>`-queryable alongside the creation metadata ("what was
172
172
  * intended"). This is distinct from `resolverPayload`, which is delivered to
173
173
  * the waiting workflow as `condition()`'s return value and is not GIN-indexed.
174
+ *
175
+ * Pass `params.assertClaim` to additionally require — inside the same guarded
176
+ * UPDATE — that no active claim lock stands against that assignee. Blocks
177
+ * with `claim-expired` (own claim window lapsed) or `claimed-by-other` (a
178
+ * live window held by someone else); unclaimed rows and durable
179
+ * pre-assignments (no window) resolve normally.
174
180
  */
175
181
  resolve(params: ResolveEscalationParams, namespace?: string): Promise<ResolveEscalationResult>;
176
182
  /**
@@ -226,6 +232,26 @@ export declare class EscalationClientService {
226
232
  * bulk resolution carries no wake and would strand the workflow.
227
233
  */
228
234
  resolveMany(params: ResolveManyParams): Promise<EscalationEntry[]>;
235
+ /**
236
+ * All-or-none bulk resolve with per-row payloads. Every item's escalation
237
+ * must be pending (and, when `assertAssignee` is set, currently assigned to
238
+ * that assignee) or NOTHING resolves — one atomic SQL statement locks the
239
+ * rows in deterministic order, applies each row's own `resolverPayload`,
240
+ * and commits each waiter's wake WITH its resolve (same durability contract
241
+ * as `resolve()`). Unlike `resolveMany()`, rows backing a live `condition()`
242
+ * waiter are first-class here: each receives its own payload as
243
+ * `condition()`'s return value.
244
+ *
245
+ * On `ok: false` no row was written and `failed` lists exactly the blocking
246
+ * rows with reasons (`not-found`, `already-resolved`, `already-cancelled`,
247
+ * `already-expired`, `assignee-mismatch`) — rows that were themselves
248
+ * resolvable stay pending and are not listed.
249
+ *
250
+ * Pass `params.metadata` to merge one shared outcome patch into every row's
251
+ * GIN-indexed `metadata` in the same statement. Ids must be unique; an empty
252
+ * `items` array returns `ok: true` with no entries.
253
+ */
254
+ resolveAllOrNone(params: ResolveAllOrNoneParams, namespace?: string): Promise<ResolveAllOrNoneResult>;
229
255
  /**
230
256
  * Returns dashboard-ready escalation counts. `period` controls the window
231
257
  * used for `created` and `resolved` counts (default `'24h'`). When `roles`
@@ -349,6 +349,12 @@ class EscalationClientService {
349
349
  * making it `@>`-queryable alongside the creation metadata ("what was
350
350
  * intended"). This is distinct from `resolverPayload`, which is delivered to
351
351
  * the waiting workflow as `condition()`'s return value and is not GIN-indexed.
352
+ *
353
+ * Pass `params.assertClaim` to additionally require — inside the same guarded
354
+ * UPDATE — that no active claim lock stands against that assignee. Blocks
355
+ * with `claim-expired` (own claim window lapsed) or `claimed-by-other` (a
356
+ * live window held by someone else); unclaimed rows and durable
357
+ * pre-assignments (no window) resolve normally.
352
358
  */
353
359
  async resolve(params, namespace) {
354
360
  const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
@@ -361,7 +367,7 @@ class EscalationClientService {
361
367
  if (preview?.signal_key) {
362
368
  wakeCommand = await this._buildWakeCommand(ns, preview.topic, preview.signal_key, params.resolverPayload ?? {});
363
369
  }
364
- const dbResult = await store.resolveEscalation({ id: params.id, resolverPayload: params.resolverPayload, metadata: params.metadata }, wakeCommand ?? undefined);
370
+ const dbResult = await store.resolveEscalation({ id: params.id, resolverPayload: params.resolverPayload, metadata: params.metadata, assertClaim: params.assertClaim }, wakeCommand ?? undefined);
365
371
  if (!dbResult.ok)
366
372
  return dbResult;
367
373
  if (dbResult.signalKey && !dbResult.wakeEnqueued) {
@@ -476,6 +482,74 @@ class EscalationClientService {
476
482
  this._emitMany('resolved', entries);
477
483
  return entries;
478
484
  }
485
+ /**
486
+ * All-or-none bulk resolve with per-row payloads. Every item's escalation
487
+ * must be pending (and, when `assertAssignee` is set, currently assigned to
488
+ * that assignee) or NOTHING resolves — one atomic SQL statement locks the
489
+ * rows in deterministic order, applies each row's own `resolverPayload`,
490
+ * and commits each waiter's wake WITH its resolve (same durability contract
491
+ * as `resolve()`). Unlike `resolveMany()`, rows backing a live `condition()`
492
+ * waiter are first-class here: each receives its own payload as
493
+ * `condition()`'s return value.
494
+ *
495
+ * On `ok: false` no row was written and `failed` lists exactly the blocking
496
+ * rows with reasons (`not-found`, `already-resolved`, `already-cancelled`,
497
+ * `already-expired`, `assignee-mismatch`) — rows that were themselves
498
+ * resolvable stay pending and are not listed.
499
+ *
500
+ * Pass `params.metadata` to merge one shared outcome patch into every row's
501
+ * GIN-indexed `metadata` in the same statement. Ids must be unique; an empty
502
+ * `items` array returns `ok: true` with no entries.
503
+ */
504
+ async resolveAllOrNone(params, namespace) {
505
+ const ns = (params.namespace ?? namespace) ?? factory_1.APP_ID;
506
+ const items = params.items ?? [];
507
+ if (!items.length)
508
+ return { ok: true, entries: [] };
509
+ const ids = items.map((i) => i.id);
510
+ if (new Set(ids).size !== ids.length) {
511
+ throw new Error('resolveAllOrNone: duplicate escalation ids in items');
512
+ }
513
+ const hm = await this._engine(null, ns);
514
+ const store = hm.engine.store;
515
+ //pre-build each waiter's wake so it commits INSIDE the resolve
516
+ //statement; signal routing (signal_key, topic) is immutable after
517
+ //creation, so the preview rows are authoritative for wake targeting
518
+ const payloadById = new Map(items.map((i) => [i.id, i.resolverPayload ?? {}]));
519
+ const previews = await store.listEscalations({
520
+ ids,
521
+ namespace: params.namespace,
522
+ });
523
+ const wakeCommands = [];
524
+ for (const row of previews) {
525
+ if (!row.signal_key)
526
+ continue;
527
+ const cmd = await this._buildWakeCommand(ns, row.topic, row.signal_key, payloadById.get(row.id) ?? {});
528
+ if (cmd)
529
+ wakeCommands.push(cmd);
530
+ }
531
+ const dbResult = await store.resolveAllOrNoneEscalations({
532
+ items,
533
+ namespace: params.namespace,
534
+ metadata: params.metadata,
535
+ assertAssignee: params.assertAssignee,
536
+ }, wakeCommands);
537
+ if (!dbResult.ok)
538
+ return { ok: false, failed: dbResult.failed };
539
+ //rows whose wake was not part of the commit (no hook rule deployed, or
540
+ //signal routing enriched after the preview) — deliver post-commit
541
+ const enqueuedKeys = new Set(wakeCommands.map((w) => w.forSignalKey));
542
+ for (const entry of dbResult.entries) {
543
+ if (entry.signal_key && !enqueuedKeys.has(entry.signal_key)) {
544
+ await this._deliverEscalationSignal(ns, entry.topic, {
545
+ id: entry.signal_key,
546
+ data: payloadById.get(entry.id) ?? {},
547
+ });
548
+ }
549
+ }
550
+ this._emitMany('resolved', dbResult.entries);
551
+ return { ok: true, entries: dbResult.entries };
552
+ }
479
553
  // ─── Aggregates ─────────────────────────────────────────────────────────────
480
554
  /**
481
555
  * Returns dashboard-ready escalation counts. `period` controls the window
@@ -328,6 +328,28 @@ declare class PostgresStoreService extends StoreService<ProviderClient, Provider
328
328
  escalateManyEscalationsToRole(params: import('../../../../types/hmsh_escalations').EscalateManyToRoleParams): Promise<number>;
329
329
  updateManyEscalationsPriority(params: import('../../../../types/hmsh_escalations').UpdateManyPriorityParams): Promise<number>;
330
330
  resolveManyEscalations(params: import('../../../../types/hmsh_escalations').ResolveManyParams): Promise<import('../../../../types/hmsh_escalations').EscalationEntry[]>;
331
+ /**
332
+ * All-or-none bulk resolve with per-row payloads. One SQL statement:
333
+ * the FOR UPDATE lock (ordered by id — deterministic acquisition, no
334
+ * deadlock between overlapping batches), the count-gated UPDATE, and
335
+ * the per-row wake INSERTs are one atomic unit. When ANY row is
336
+ * missing, non-pending, or fails the assignee assertion, the gate
337
+ * count mismatches, the UPDATE matches zero rows, no wake is written,
338
+ * and the statement degrades to a pure read — the returned snapshot
339
+ * names each blocking row and why. Same durability contract as
340
+ * `resolveEscalation`: each wake commits WITH its row's resolve.
341
+ */
342
+ resolveAllOrNoneEscalations(params: import('../../../../types/hmsh_escalations').ResolveAllOrNoneParams, wakeCommands?: import('../../../../types/hmsh_escalations').EscalationWakeCommand[]): Promise<{
343
+ ok: true;
344
+ entries: import('../../../../types/hmsh_escalations').EscalationEntry[];
345
+ wakeCount: number;
346
+ } | {
347
+ ok: false;
348
+ failed: Array<{
349
+ id: string;
350
+ reason: import('../../../../types/hmsh_escalations').ResolveAllOrNoneBlockReason;
351
+ }>;
352
+ }>;
331
353
  escalationStats(params?: import('../../../../types/hmsh_escalations').StatsEscalationsParams): Promise<import('../../../../types/hmsh_escalations').EscalationStats>;
332
354
  listDistinctEscalationTypes(namespace?: string): Promise<string[]>;
333
355
  releaseExpiredEscalations(_namespace?: string): Promise<number>;
@@ -1889,7 +1889,7 @@ class PostgresStoreService extends __1.StoreService {
1889
1889
  };
1890
1890
  }
1891
1891
  async resolveEscalation(params, wakeCommand) {
1892
- const { id, namespace, resolverPayload, metadata } = params;
1892
+ const { id, namespace, resolverPayload, metadata, assertClaim } = params;
1893
1893
  const payloadJson = resolverPayload ? JSON.stringify(resolverPayload) : null;
1894
1894
  const metaJson = metadata ? JSON.stringify(metadata) : null;
1895
1895
  //single statement: FOR UPDATE lock, TOCTOU-guarded UPDATE, and the
@@ -1901,10 +1901,20 @@ class PostgresStoreService extends __1.StoreService {
1901
1901
  const sqlParams = namespace
1902
1902
  ? [id, payloadJson, metaJson, namespace]
1903
1903
  : [id, payloadJson, metaJson];
1904
+ //claim assertion rides the same guarded UPDATE: when $claimIdx is NULL
1905
+ //the predicate collapses to TRUE (today's semantics). A claim is a work
1906
+ //LOCK that exists only while a TTL window (assigned_until) is active —
1907
+ //blocked states are exactly: a live window held by a different assignee,
1908
+ //and the asserting assignee's own lapsed window (stale work). Unclaimed
1909
+ //rows, durable pre-assignments (assigned_to with no window), and rows
1910
+ //whose window lapsed under a different assignee all resolve normally.
1911
+ sqlParams.push(assertClaim ?? null);
1912
+ const claimIdx = sqlParams.length;
1904
1913
  const { wakeCTE, wakeCount } = this.composeEscalationWakeCTE(wakeCommand, sqlParams, 'resolved');
1905
1914
  const result = await this.pgClient.query(`
1906
1915
  WITH target AS MATERIALIZED (
1907
- SELECT id, signal_key, topic, status FROM public.hmsh_escalations
1916
+ SELECT id, signal_key, topic, status, assigned_to, assigned_until
1917
+ FROM public.hmsh_escalations
1908
1918
  WHERE id = $1 ${namespace ? 'AND namespace = $4' : ''}
1909
1919
  LIMIT 1 FOR UPDATE
1910
1920
  ),
@@ -1917,9 +1927,14 @@ class PostgresStoreService extends __1.StoreService {
1917
1927
  updated_at = NOW()
1918
1928
  FROM target
1919
1929
  WHERE e.id = target.id AND target.status = 'pending'
1930
+ AND ($${claimIdx}::text IS NULL
1931
+ OR target.assigned_to IS NULL
1932
+ OR target.assigned_until IS NULL
1933
+ OR (target.assigned_to = $${claimIdx}::text AND target.assigned_until > NOW())
1934
+ OR (target.assigned_to <> $${claimIdx}::text AND target.assigned_until <= NOW()))
1920
1935
  RETURNING e.*
1921
1936
  )${wakeCTE}
1922
- SELECT t.id, t.status AS prior_status, t.signal_key, t.topic,
1937
+ SELECT t.id, t.status AS prior_status, t.signal_key, t.topic, t.assigned_to,
1923
1938
  CASE
1924
1939
  WHEN r.id IS NOT NULL THEN 'resolved'
1925
1940
  WHEN t.id IS NULL THEN 'not-found'
@@ -1943,6 +1958,15 @@ class PostgresStoreService extends __1.StoreService {
1943
1958
  // resolution landed.
1944
1959
  return { ok: false, reason: 'already-expired' };
1945
1960
  }
1961
+ if (row.prior_status === 'pending') {
1962
+ // Still pending, yet blocked — only the claim assertion can do that.
1963
+ // Same-assignee means their claim lapsed; anything else means the
1964
+ // row is (or was last) held by a different principal.
1965
+ return {
1966
+ ok: false,
1967
+ reason: row.assigned_to === assertClaim ? 'claim-expired' : 'claimed-by-other',
1968
+ };
1969
+ }
1946
1970
  return { ok: false, reason: 'already-resolved' };
1947
1971
  }
1948
1972
  return {
@@ -2222,6 +2246,117 @@ class PostgresStoreService extends __1.StoreService {
2222
2246
  RETURNING *`, namespace ? [payloadJson, ids, metaJson, namespace] : [payloadJson, ids, metaJson]);
2223
2247
  return result.rows;
2224
2248
  }
2249
+ /**
2250
+ * All-or-none bulk resolve with per-row payloads. One SQL statement:
2251
+ * the FOR UPDATE lock (ordered by id — deterministic acquisition, no
2252
+ * deadlock between overlapping batches), the count-gated UPDATE, and
2253
+ * the per-row wake INSERTs are one atomic unit. When ANY row is
2254
+ * missing, non-pending, or fails the assignee assertion, the gate
2255
+ * count mismatches, the UPDATE matches zero rows, no wake is written,
2256
+ * and the statement degrades to a pure read — the returned snapshot
2257
+ * names each blocking row and why. Same durability contract as
2258
+ * `resolveEscalation`: each wake commits WITH its row's resolve.
2259
+ */
2260
+ async resolveAllOrNoneEscalations(params, wakeCommands) {
2261
+ const { items, namespace, metadata, assertAssignee } = params;
2262
+ if (!items?.length)
2263
+ return { ok: true, entries: [], wakeCount: 0 };
2264
+ const ids = items.map((i) => i.id);
2265
+ if (new Set(ids).size !== ids.length) {
2266
+ throw new Error('resolveAllOrNoneEscalations: duplicate escalation ids in items');
2267
+ }
2268
+ const payloads = items.map((i) => i.resolverPayload ? JSON.stringify(i.resolverPayload) : null);
2269
+ const metaJson = metadata ? JSON.stringify(metadata) : null;
2270
+ const sqlParams = [ids, payloads, metaJson, assertAssignee ?? null];
2271
+ let nsClause = '';
2272
+ if (namespace) {
2273
+ sqlParams.push(namespace);
2274
+ nsClause = `AND e.namespace = $${sqlParams.length}`;
2275
+ }
2276
+ //per-row wakes: one engine_streams INSERT per resolved row whose
2277
+ //signal_key matches its pre-built command; zero rows when the gate fails
2278
+ let wakeCTE = '';
2279
+ let wakeCount = '0::int AS wake_count';
2280
+ if (wakeCommands?.length) {
2281
+ const schemaName = this.kvsql().safeName(this.appId);
2282
+ const base = sqlParams.length;
2283
+ sqlParams.push(this.appId, wakeCommands.map((w) => w.forSignalKey), wakeCommands.map((w) => w.message));
2284
+ wakeCTE = `,
2285
+ wake AS (
2286
+ INSERT INTO ${schemaName}.engine_streams (stream_name, message, priority)
2287
+ SELECT $${base + 1}, w.message, 5
2288
+ FROM unnest($${base + 2}::text[], $${base + 3}::text[]) AS w(signal_key, message)
2289
+ JOIN resolved r ON r.signal_key = w.signal_key
2290
+ RETURNING id
2291
+ )`;
2292
+ wakeCount = '(SELECT COUNT(*) FROM wake)::int AS wake_count';
2293
+ }
2294
+ const result = await this.pgClient.query(`
2295
+ WITH input AS MATERIALIZED (
2296
+ SELECT * FROM unnest($1::uuid[], $2::text[]) AS t(id, payload_text)
2297
+ ),
2298
+ target AS MATERIALIZED (
2299
+ SELECT e.id, e.signal_key, e.topic, e.status, e.assigned_to
2300
+ FROM public.hmsh_escalations e
2301
+ WHERE e.id = ANY($1::uuid[]) ${nsClause}
2302
+ ORDER BY e.id
2303
+ FOR UPDATE
2304
+ ),
2305
+ eligible AS (
2306
+ SELECT t.id FROM target t
2307
+ WHERE t.status = 'pending'
2308
+ AND ($4::text IS NULL OR t.assigned_to = $4::text)
2309
+ ),
2310
+ resolved AS (
2311
+ UPDATE public.hmsh_escalations e
2312
+ SET status = 'resolved', resolved_at = NOW(),
2313
+ resolver_payload = i.payload_text::jsonb,
2314
+ metadata = CASE WHEN $3::jsonb IS NOT NULL
2315
+ THEN COALESCE(e.metadata, '{}'::jsonb) || $3::jsonb
2316
+ ELSE e.metadata END,
2317
+ updated_at = NOW()
2318
+ FROM input i
2319
+ WHERE e.id = i.id
2320
+ AND e.status = 'pending'
2321
+ AND (SELECT COUNT(*) FROM eligible) = (SELECT COUNT(*) FROM input)
2322
+ RETURNING e.*
2323
+ )${wakeCTE}
2324
+ SELECT
2325
+ i.id AS input_id,
2326
+ t.status AS prior_status,
2327
+ CASE
2328
+ WHEN r.id IS NOT NULL THEN 'resolved'
2329
+ WHEN t.id IS NULL THEN 'not-found'
2330
+ WHEN t.status = 'cancelled' THEN 'already-cancelled'
2331
+ WHEN t.status = 'expired' THEN 'already-expired'
2332
+ WHEN t.status <> 'pending' THEN 'already-resolved'
2333
+ WHEN $4::text IS NOT NULL AND t.assigned_to IS DISTINCT FROM $4::text THEN 'assignee-mismatch'
2334
+ ELSE 'blocked-by-batch'
2335
+ END AS outcome,
2336
+ row_to_json(r.*) AS entry_json,
2337
+ ${wakeCount}
2338
+ FROM input i
2339
+ LEFT JOIN target t ON t.id = i.id
2340
+ LEFT JOIN resolved r ON r.id = i.id
2341
+ ORDER BY i.id
2342
+ `, sqlParams);
2343
+ const rows = result.rows;
2344
+ if (rows.length && rows.every((r) => r.outcome === 'resolved')) {
2345
+ return {
2346
+ ok: true,
2347
+ entries: rows.map((r) => r.entry_json),
2348
+ wakeCount: rows[0].wake_count,
2349
+ };
2350
+ }
2351
+ return {
2352
+ ok: false,
2353
+ //'blocked-by-batch' rows were themselves resolvable — only the true
2354
+ //blockers are reported; the caller re-gangs around exactly these
2355
+ failed: rows
2356
+ .filter((r) => r.outcome !== 'resolved' && r.outcome !== 'blocked-by-batch')
2357
+ .map((r) => ({ id: r.input_id, reason: r.outcome })),
2358
+ };
2359
+ }
2225
2360
  async escalationStats(params = {}) {
2226
2361
  const { namespace, roles, period = '24h' } = params;
2227
2362
  if (roles !== undefined && roles.length === 0) {
@@ -103,7 +103,7 @@ export type ResolveEscalationResult = {
103
103
  entry: EscalationEntry;
104
104
  } | {
105
105
  ok: false;
106
- reason: 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired';
106
+ reason: 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired' | 'claim-expired' | 'claimed-by-other';
107
107
  };
108
108
  /**
109
109
  * A pre-built wake message, committed INSIDE the resolve/cancel transaction
@@ -307,6 +307,18 @@ export interface ResolveEscalationParams {
307
307
  * `condition()`'s return value and is not GIN-indexed.
308
308
  */
309
309
  metadata?: Record<string, unknown>;
310
+ /**
311
+ * When provided, the resolve additionally asserts — inside the same guarded
312
+ * UPDATE — that no claim LOCK stands against this assignee. A claim is a
313
+ * lock only while its TTL window (`assigned_until`) is active; the assert
314
+ * blocks exactly two states: a live window held by a different assignee
315
+ * (`claimed-by-other`), and this assignee's own lapsed window
316
+ * (`claim-expired` — stale work; re-claim to resolve). Unclaimed rows,
317
+ * durable pre-assignments (`assigned_to` with no window), and rows whose
318
+ * window lapsed under a different assignee resolve normally. Closes the
319
+ * claim-race window for interactive claim-then-resolve flows.
320
+ */
321
+ assertClaim?: string;
310
322
  }
311
323
  export interface ResolveByMetadataParams {
312
324
  key: string;
@@ -352,6 +364,47 @@ export interface ResolveManyParams {
352
364
  */
353
365
  metadata?: Record<string, unknown>;
354
366
  }
367
+ /** One member of a `resolveAllOrNone()` batch — its own `resolverPayload` is
368
+ * stored as that row's `resolver_payload` and delivered to that row's waiting
369
+ * workflow as `condition()`'s return value. */
370
+ export interface ResolveAllOrNoneItem {
371
+ id: string;
372
+ resolverPayload?: Record<string, unknown>;
373
+ }
374
+ export interface ResolveAllOrNoneParams {
375
+ /** The batch. Ids must be unique; each item carries its own payload. */
376
+ items: ResolveAllOrNoneItem[];
377
+ namespace?: string;
378
+ /**
379
+ * Shared outcome patch merged (not replaced) into EVERY row's GIN-indexed
380
+ * `metadata` in the single atomic statement. See {@link ResolveEscalationParams.metadata}.
381
+ */
382
+ metadata?: Record<string, unknown>;
383
+ /**
384
+ * When provided, every row must currently be assigned to this assignee
385
+ * (`assigned_to` equality, asserted inside the same statement). Closes the
386
+ * claim-race window for claim-then-resolve flows: a row re-claimed by another
387
+ * principal between the caller's claim and this resolve blocks the batch.
388
+ */
389
+ assertAssignee?: string;
390
+ }
391
+ /** Why a specific row blocked a `resolveAllOrNone()` batch. */
392
+ export type ResolveAllOrNoneBlockReason = 'not-found' | 'already-resolved' | 'already-cancelled' | 'already-expired' | 'assignee-mismatch';
393
+ /**
394
+ * Result of `resolveAllOrNone()`. On `ok: false` NOTHING was written; `failed`
395
+ * lists only the rows that blocked the batch (rows that were themselves
396
+ * resolvable are not listed — they remain pending, untouched).
397
+ */
398
+ export type ResolveAllOrNoneResult = {
399
+ ok: true;
400
+ entries: EscalationEntry[];
401
+ } | {
402
+ ok: false;
403
+ failed: Array<{
404
+ id: string;
405
+ reason: ResolveAllOrNoneBlockReason;
406
+ }>;
407
+ };
355
408
  /**
356
409
  * Full-fidelity migration params. Extends `CreateEscalationParams` with:
357
410
  * - `id` (required) — preserves the original UUID; no auto-generation
@@ -25,5 +25,5 @@ export { ReclaimedMessageType, RetryPolicy, RouterConfig, StreamCode, StreamConf
25
25
  export { context, Context, Counter, Meter, metrics, propagation, SpanContext, Span, SpanStatus, SpanStatusCode, SpanKind, trace, Tracer, ValueType, } from './telemetry';
26
26
  export { WorkListTaskType } from './task';
27
27
  export { TransitionMatch, TransitionRule, Transitions } from './transition';
28
- export { ConditionQueueConfig, EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, EscalateToRoleParams, MigrateEscalationParams, } from './hmsh_escalations';
28
+ export { ConditionQueueConfig, EscalationEntry, ClaimEscalationResult, ClaimByMetadataResult, ReleaseEscalationResult, ResolveEscalationResult, CancelEscalationResult, ListEscalationsParams, CreateEscalationParams, UpdateEscalationParams, AppendMilestonesParams, ClaimEscalationParams, ClaimByMetadataParams, ReleaseEscalationParams, ResolveEscalationParams, ResolveByMetadataParams, ResolveAllOrNoneItem, ResolveAllOrNoneParams, ResolveAllOrNoneBlockReason, ResolveAllOrNoneResult, EscalateToRoleParams, MigrateEscalationParams, } from './hmsh_escalations';
29
29
  export { EscalationVerb, EngineVerb, WorkerVerb, SystemEvent, EventsConfig } from './system_events';
@@ -143,8 +143,8 @@ export interface SystemEvent {
143
143
  span_id?: string;
144
144
  /**
145
145
  * Full committed row for escalation events; lifecycle metadata for
146
- * engine/worker events. Long-tail and hike-mono each cherry-pick fields
147
- * for their own event shape.
146
+ * engine/worker events. Each dependent cherry-picks fields for its
147
+ * own event shape.
148
148
  */
149
149
  data: Record<string, unknown>;
150
150
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hotmeshio/hotmesh",
3
- "version": "0.26.0",
3
+ "version": "0.26.2",
4
4
  "description": "Durable Workflow",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
package/OPTIMIZATIONS.md DELETED
@@ -1,128 +0,0 @@
1
- # HotMesh needs — from long-tail
2
-
3
- A needs document from the long-tail project: the usage patterns we run at
4
- production scale and the engine support that would let us run them well. Each item
5
- states what we do, the concrete access pattern, and the engine capability or
6
- guarantee we need. Ordered by leverage.
7
-
8
- Context: long-tail is a durable HITL escalation platform on Postgres. Escalations
9
- live in `public.hmsh_escalations` (engine-created); we layer a `public.lt_escalations`
10
- view and a few app-owned indexes on top. Our dominant runtime shape is
11
- **single-role** work-queue traffic — claim / available / count / settle scoped to
12
- one `role` — plus a per-role escalation form the resolve UI renders.
13
-
14
- ---
15
-
16
- ## 1. Safe retention for terminal escalation rows
17
-
18
- **Usage.** An escalation is written once, resolved once, then read for audit. The
19
- pending working set stays small — a role-leading pending partial index keeps
20
- single-role claim/available queries `O(pending)` regardless of table size:
21
-
22
- ```sql
23
- WHERE role = $1 AND status = 'pending'
24
- AND (assigned_to IS NULL OR assigned_until <= NOW())
25
- AND metadata @> $facets
26
- ORDER BY priority ASC, created_at ASC
27
- FOR UPDATE SKIP LOCKED
28
- ```
29
-
30
- The terminal set (resolved / expired / cancelled) grows for the life of the
31
- deployment — the source of long-run table bloat, autovacuum load, and index growth.
32
-
33
- **Need.** A safe, engine-blessed way to age out terminal rows. Tell us what state
34
- the engine still reads once an escalation is terminal (replay, completion, audit),
35
- so we know what is inert, then one of:
36
- - a supported retention/archive call the engine owns; or
37
- - a documented contract that a row is safe to delete once its status is terminal
38
- and older than a horizon; or
39
- - time sub-partitioning of the terminal set the engine can `DETACH`/`DROP`.
40
-
41
- `hmsh_escalations` stays a single physical table keyed by `id`/`signal_key` for
42
- the engine's lookups; retention touches only rows the engine confirms are inert. We
43
- can supply the horizon and exact DDL.
44
-
45
- ---
46
-
47
- ## 2. Stable ownership of app-added indexes on `hmsh_escalations`
48
-
49
- **Usage.** We add indexes to the engine table via advisory-locked
50
- `CREATE INDEX CONCURRENTLY IF NOT EXISTS`:
51
- - a role-leading pending index `(role, priority, created_at) WHERE status='pending'`
52
- for the claim/available order;
53
- - a **pending-scoped GIN** on `metadata` (`jsonb_path_ops`) `WHERE status='pending'`
54
- — keeps the GIN sized to the working set and cuts write amplification on the
55
- high-churn insert→resolve path;
56
- - covering partial indexes for resolved-row reads.
57
-
58
- **Need.** A stable contract that app-added indexes on `hmsh_escalations` survive
59
- engine migrations — the engine keeps the table in place across upgrades — or a
60
- documented post-migration hook we can register to re-ensure them. Shipping these
61
- index shapes in the engine itself also works; the requirement is that they persist.
62
-
63
- ---
64
-
65
- ## 3. Atomic metadata write in the `condition()` Leg1 checkpoint
66
-
67
- **Usage.** A workflow surfaces a HITL wait with `condition(signalId, config)`. We
68
- pass the target `role`, claim/routing facets, and `metadata.schema_version` (the
69
- form version the resolve UI renders) in `config.metadata`. Claim/resolve-by-metadata
70
- and the dashboard read those facets via GIN `@>`; the resolve UI reads
71
- `schema_version` to render the exact form.
72
-
73
- **Need.** Guarantee — as a documented public contract — that `config.metadata` is
74
- written into the escalation row **atomically in the same Leg1 checkpoint** that
75
- creates the row (one commit, crash-safe). This is the foundation our JIT-versioned
76
- form pinning and metadata-driven routing stand on.
77
-
78
- ---
79
-
80
- ## 4. Honored long-activity timeout + reclaim safety
81
-
82
- **Usage.** We run a batch pattern: a single proxyActivity loops internally for
83
- ~60s (poll → reconcile → act), returning one durable checkpoint per call instead of
84
- one per step, so replay stays compact.
85
-
86
- **Need.** A documented guarantee that:
87
- - `proxyActivities({ startToCloseTimeout })` is honored for long (30–120s) activities;
88
- - the stream reclaim window (`HMSH_XCLAIM_DELAY_MS`) holds an in-flight activity for
89
- the duration of its `startToCloseTimeout`, so a long activity is not reclaimed and
90
- re-dispatched (duplicate execution) before it completes. Deriving the reclaim
91
- window from `startToCloseTimeout` automatically makes a 60s+ activity safe by
92
- default.
93
-
94
- ---
95
-
96
- ## 5. Documented concurrent-condition bound for harvest fan-out
97
-
98
- **Usage.** A market-maker workflow opens N `condition()` waits and harvests them
99
- with `Promise.all`, chunked to stay within the safe concurrent-condition bound (a
100
- fast signaler can arrive before a later condition registers).
101
-
102
- **Need.** Publish the safe concurrent-condition bound as a stable number with the
103
- recommended chunking pattern, so we size harvest fan-out to spec rather than
104
- empirically — and raise it where the engine can.
105
-
106
- ---
107
-
108
- ## 6. Signal buffering + startChild leader-keeps-seat as public contract
109
-
110
- **Usage.** Two behaviors our crash-safe patterns build on:
111
- - a signal delivered to a workflow **not yet parked** on that signalId is buffered
112
- and delivered on the next `condition()` await;
113
- - `startChild` with a **duplicate workflowId** lets the sitting execution keep its
114
- seat (leader-keeps-seat), enabling self-continuing link chains (`x-l1`, `x-l2`, …)
115
- as an alternative to `continueAsNew`.
116
-
117
- **Need.** Elevate both to documented, stable public guarantees (including the signal
118
- buffering TTL), versioned as contract.
119
-
120
- ---
121
-
122
- ### How we consume these
123
-
124
- Items 1–2 are the scale needs — retention for terminal rows, and durable app-owned
125
- indexes that keep the hot path `O(pending)`. Item 3 is the atomicity guarantee our
126
- versioned forms and metadata routing depend on. Items 4–6 are behaviors we already
127
- build on and want made explicit. We can provide `EXPLAIN` plans, row-count/latency
128
- profiles, and the exact DDL for any of these on request.
package/RELEASE-0.26.0.md DELETED
@@ -1,111 +0,0 @@
1
- # HotMesh v0.26.0 — for the long-tail project
2
-
3
- This release answers the needs document. Items 1–5 and the signal-buffering
4
- half of item 6 ship as published contracts with proving tests; the startChild
5
- contract (item 6b) is scheduled for its own follow-up release. Numbering below
6
- matches your document.
7
-
8
- ## 1. Retention for terminal escalation rows — new API
9
-
10
- Terminal rows (`resolved`, `cancelled`, `expired`) are inert: every engine
11
- state transition guards on `status = 'pending'`, and the engine reads terminal
12
- rows only through `list()` / `get()` / `stats()`. Age them out with the new
13
- engine-owned call:
14
-
15
- ```typescript
16
- let deleted: number;
17
- do {
18
- ({ deleted } = await client.escalations.prune({ olderThan: '90 days' }));
19
- } while (deleted > 0);
20
- ```
21
-
22
- - `olderThan` is a Postgres interval; rows qualify when
23
- `updated_at < NOW() - olderThan`.
24
- - `statuses` narrows which terminal states are pruned (defaults to all three);
25
- `namespace` scopes to one app; `limit` bounds rows per call (default 10,000,
26
- cap 100,000) so vacuum pressure stays flat.
27
- - Each call is one atomic statement — candidate selection
28
- (`FOR UPDATE SKIP LOCKED`) and the DELETE commit together, so concurrent
29
- pruners cooperate and live waiters, claims, and signal delivery proceed
30
- untouched. The proving test backdates a parked waiter 120 days, prunes, and
31
- resolves it to completion.
32
- - If you run retention with your own tooling instead, the documented
33
- safe-to-delete predicate is exactly the one `prune()` uses:
34
- `status IN ('resolved','cancelled','expired') AND updated_at` older than
35
- your horizon.
36
- - Choose a horizon at least as long as your reporting window: `stats()`
37
- created/resolved counts and `get()` by id reflect the rows retained.
38
-
39
- ## 2. App-added indexes survive engine migrations — published contract
40
-
41
- Engine migrations on `public.hmsh_escalations` are strictly additive
42
- (`CREATE TABLE / INDEX IF NOT EXISTS`, `ADD COLUMN IF NOT EXISTS`, advisory-
43
- locked), and the table persists in place across upgrades. The engine manages
44
- only indexes with the `idx_hmsh_esc_*` prefix; indexes under any other name
45
- are yours and persist. Your advisory-locked
46
- `CREATE INDEX CONCURRENTLY IF NOT EXISTS` pattern is the recommended one.
47
-
48
- Two notes on your shapes: the engine's `idx_hmsh_esc_available`
49
- (`(namespace, app_id, role, priority ASC, created_at ASC) WHERE
50
- status = 'pending'`) already serves the single-role claim/available order at
51
- `O(pending)`. Your pending-scoped GIN stays app-owned: the engine keeps its
52
- full-table GIN because resolver-merged metadata (v0.24.0) is read on resolved
53
- rows.
54
-
55
- ## 3. Atomic metadata in the Leg1 checkpoint — published contract
56
-
57
- Every field of the `condition()` config — `metadata` facets included — is one
58
- INSERT committed inside the Leg1 checkpoint transaction: one commit,
59
- crash-safe. From the row's first visible moment it carries its complete
60
- routing context and metadata, so claim-by-metadata routing and
61
- `schema_version`-pinned forms can trust every row they read. The proving test
62
- tight-polls from workflow start and asserts the first sighting is complete.
63
-
64
- ## 4. Long activities execute exactly once — published contract
65
-
66
- - `startToCloseTimeout` is honored for long activities (deadline enforcement
67
- is covered by positive and negative tests).
68
- - While an activity runs, the consumer heartbeats its stream reservation at
69
- half the base window, so the message stays leased for the full run —
70
- your 60s batch loop (poll → reconcile → act, one checkpoint per call) is a
71
- supported shape at default settings, for any duration. Redelivery happens
72
- when a consumer crashes and stops heartbeating, and the collation ledger
73
- settles a redelivered message as a duplicate before the activity function
74
- re-executes.
75
- - The proving test runs a 45s activity against a 30s reservation window with
76
- a second worker actively polling the same queue: exactly one execution.
77
- - Deployment note: standard Postgres connections have this lease extension.
78
- A `securedWorker` connection (SECURITY DEFINER stored-proc mode) enforces
79
- the adaptive reservation window instead — 30s base, scaling to 30 minutes
80
- under load — so size activities to that window in secured mode.
81
-
82
- ## 5. Concurrent-condition bound — the published number is a TTL
83
-
84
- Fan-out is sized by time, and by count it scales freely. A signal that races
85
- ahead of its `condition()` registration is buffered as a pending signal and
86
- delivered — crash-safe, in a single transaction — when the wait registers.
87
- The buffer holds a signal for **10 minutes** by default; pass `expire` to
88
- `signal()` (e.g. `'1h'`, `'30d'`) when signaling early on purpose.
89
-
90
- Chunk your harvest so every condition in a chunk registers within the TTL of
91
- its fastest signaler. The proving test opens 25 waits in one `Promise.all`
92
- and fires all 25 signals before any wait has registered: every signal is
93
- delivered to its own wait, in order.
94
-
95
- ## 6. Contracts
96
-
97
- - **Signal buffering** is now a documented public guarantee (item 5 above,
98
- TTL included).
99
- - **startChild leader-keeps-seat**: the sitting execution keeps its seat
100
- today, and fire-and-forget `startChild` link chains (`x-l1`, `x-l2`, …)
101
- work on that behavior. The *awaited* duplicate path (`executeChild` on an
102
- id that already exists) gets defined semantics — a typed result rather
103
- than an open wait — in a dedicated follow-up release; until then, treat
104
- awaited duplicates as unspecified and build chains on the fire-and-forget
105
- form.
106
-
107
- ## Upgrading
108
-
109
- `npm install @hotmeshio/hotmesh@0.26.0`. Migrations are additive and run
110
- automatically under the existing advisory lock; your indexes and views
111
- persist. Full durable suite: 433 tests green.