From 29c0fa0d0897fc7ec6b290b1cb25b56d22ddaa1c Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Fri, 6 Nov 2026 21:48:17 -0300 Subject: [PATCH 001/100] Isolate time-travel ancestor traversal and reset by job Constrain the initial ancestor lookup, recursive hops, and ancestor reset to the requested job while retaining accepted foreign-parent inputs. Cover direct and recursive foreign links on both SQL engines, including a parallel-root discriminator that fails with reset-only isolation. Preserve archived invalid-target restoration. Correct the nested-parallel fixture to establish completed siblings before testing retention; the previous failure setup could fail those siblings before time travel. --- packages/duron/src/adapters/postgres/base.ts | 7 +- packages/duron/test/time-travel.test.ts | 163 ++++++++++++++++++- 2 files changed, 165 insertions(+), 5 deletions(-) diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 00ecfde..711e530 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -647,16 +647,18 @@ export abstract class PostgresBaseAdapter< AND s.job_id = ${jobId} AND EXISTS (SELECT 1 FROM locked_job) ), - -- Find all ancestor steps recursively (from target up to root) + -- Find ancestors within this job only; stop at any foreign parent ancestors AS ( SELECT s.id, s.parent_step_id, 0 AS depth FROM ${this.tables.jobStepsActiveTable} s WHERE s.id = (SELECT parent_step_id FROM target_step) + AND s.job_id = ${jobId} AND EXISTS (SELECT 1 FROM target_step) UNION ALL SELECT s.id, s.parent_step_id, a.depth + 1 FROM ${this.tables.jobStepsActiveTable} s INNER JOIN ancestors a ON s.id = a.parent_step_id + WHERE s.job_id = ${jobId} ), -- Steps to keep: completed steps created before target + completed parallel siblings of target and ancestors + their descendants parallel_siblings AS ( @@ -741,7 +743,7 @@ export abstract class PostgresBaseAdapter< AND id != (SELECT id FROM target_step) RETURNING id ), - -- Reset ancestor steps to active + -- Reset ancestor steps to active, confined to the requested job reset_ancestors AS ( UPDATE ${this.tables.jobStepsActiveTable} SET @@ -756,6 +758,7 @@ export abstract class PostgresBaseAdapter< history_failed_attempts = '{}'::jsonb, updated_at = now() WHERE id IN (SELECT id FROM ancestors) + AND job_id = ${jobId} RETURNING id ), -- Reset target step to active diff --git a/packages/duron/test/time-travel.test.ts b/packages/duron/test/time-travel.test.ts index bd66094..462fb97 100644 --- a/packages/duron/test/time-travel.test.ts +++ b/packages/duron/test/time-travel.test.ts @@ -1,11 +1,13 @@ import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { type SQL, sql } from 'drizzle-orm' import { z } from 'zod/mini' import { defineAction } from '../src/action.js' import { Client } from '../src/client.js' import { JOB_STATUS_ACTIVE, + JOB_STATUS_CANCELLED, JOB_STATUS_COMPLETED, JOB_STATUS_CREATED, JOB_STATUS_FAILED, @@ -14,6 +16,7 @@ import { } from '../src/constants.js' import { + type Adapter, type AdapterFactory, type AdapterInstance, pgliteFactory, @@ -530,16 +533,18 @@ function runTests(name: string, factory: AdapterFactory) { it('should preserve sibling parallel steps AND their children when time traveling to nested step in a parallel step', async () => { // This tests the edge case from processOrder: time traveling to a step inside // a parallel step should preserve sibling parallel steps AND all their nested children - const jobId = await client.runAction('nestedBranchAction', { failAtStep: 'child-b-2' }) + // Complete the graph first: an early parallel failure can fail unfinished + // siblings, which are not covered by the completed-sibling retention rule. + const jobId = await client.runAction('nestedBranchAction', {}) await client.fetch({ batchSize: 1 }) const job = await client.waitForJob(jobId, { timeout: 10000 }) expectToBeDefined(job) - expect(job?.status).toBe(JOB_STATUS_FAILED) + expect(job?.status).toBe(JOB_STATUS_COMPLETED) // Get steps before time travel const { steps } = await client.getJobSteps({ jobId }) - // Verify initial state: parallel step a and c completed with children, parallel step b failed + // Verify initial state: parallel siblings and their children are completed const branchA = steps.find((s) => s.name === 'branch-a') const childA1 = steps.find((s) => s.name === 'child-a-1') const childA2 = steps.find((s) => s.name === 'child-a-2') @@ -555,6 +560,10 @@ function runTests(name: string, factory: AdapterFactory) { expectToBeDefined(childC1) expectToBeDefined(childB1) expectToBeDefined(childB2) + // Preservation requires completed siblings, not merely existing steps. + for (const step of [branchA, childA1, childA2, branchC, childC1]) { + expect(step.status).toBe(STEP_STATUS_COMPLETED) + } // Time travel to child-b-2 (nested inside parallel step b) const success = await client.timeTravelJob(jobId, childB2!.id) @@ -641,12 +650,160 @@ function runTests(name: string, factory: AdapterFactory) { }) } +// Public Adapter fixtures: foreign parent IDs are accepted inputs, not StepManager graphs. +async function createActiveJob(adapter: Adapter, groupKey: string) { + const jobId = await adapter.createJob({ + queue: 'time-travel-isolation', + groupKey, + input: {}, + timeoutMs: 60000, + checksum: 'isolation', + concurrencyLimit: 10, + concurrencyStepLimit: 10, + }) + expectToBeDefined(jobId) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + return jobId +} + +async function createCompletedStep( + adapter: Adapter, + jobId: string, + name: string, + parentStepId: string | null = null, + parallel = false, +) { + const step = await adapter.createOrRecoverJobStep({ + jobId, + name, + parentStepId, + parallel, + timeoutMs: 60000, + retriesLimit: 3, + }) + expectToBeDefined(step) + expect(await adapter.completeJobStep({ stepId: step.id, output: { saved: name } })).toBe(true) + return step.id +} + +// Agreed native observation seam: public detail lookup intentionally hides storage +// membership. Read only the default test schema; all fixture mutations remain public. +async function getJobStorage(adapter: Adapter, jobId: string) { + type Membership = { active: boolean; archived: boolean } + const { db } = adapter as unknown as { + db: { execute: (query: SQL) => Promise } + } + const result = await db.execute(sql` + SELECT + EXISTS(SELECT 1 FROM duron.jobs_active WHERE id = ${jobId}) AS active, + EXISTS(SELECT 1 FROM duron.jobs_archive WHERE id = ${jobId}) AS archived + `) + return ('rows' in result ? result.rows : result)[0] +} + +function runIsolationTests(factory: AdapterFactory) { + describe(`Time Travel Job Isolation (${factory.name})`, () => { + it.each(['direct parent', 'ancestor after a same-job hop'])( + 'stops at a foreign %s without changing its job or step', + async (relationship) => { + const { adapter, deleteDb } = await factory.create({ logger: 'silent' }) + try { + adapter.setId(crypto.randomUUID()) + const foreignJobId = await createActiveJob(adapter, 'foreign') + const foreignStepId = await createCompletedStep(adapter, foreignJobId, 'foreign-root') + const foreignJobBefore = await adapter.getJobById(foreignJobId) + const foreignStepBefore = await adapter.getJobStepById(foreignStepId) + expect(foreignJobBefore?.status).toBe(JOB_STATUS_ACTIVE) + expect(foreignStepBefore?.output).toEqual({ saved: 'foreign-root' }) + expect(foreignStepBefore?.finishedAt).toBeInstanceOf(Date) + + const jobId = await createActiveJob(adapter, 'requested') + const parentId = + relationship === 'direct parent' + ? foreignStepId + : await createCompletedStep(adapter, jobId, 'same-job-parent', foreignStepId) + const targetId = await createCompletedStep(adapter, jobId, 'target', parentId) + // This later root is NOT a sibling of target. Traversing the foreign root + // would incorrectly preserve it as that ancestor's parallel sibling, + // even if the ancestor UPDATE alone were guarded by job_id. + const laterRootId = await createCompletedStep(adapter, jobId, 'later-root', null, true) + expect(await adapter.completeJob({ jobId, output: { saved: 'requested-job' } })).toBe( + true, + ) + + expect(await adapter.timeTravelJob({ jobId, stepId: targetId })).toBe(true) + expect(await adapter.getJobById(foreignJobId)).toEqual(foreignJobBefore) + expect(await adapter.getJobStepById(foreignStepId)).toEqual(foreignStepBefore) + expect(await adapter.getJobStepById(laterRootId)).toBeNull() + expect(await adapter.getJobStepById(targetId)).toMatchObject({ + status: STEP_STATUS_ACTIVE, + output: null, + finishedAt: null, + parentStepId: parentId, + }) + if (relationship !== 'direct parent') { + expect(await adapter.getJobStepById(parentId)).toMatchObject({ + status: STEP_STATUS_ACTIVE, + output: null, + finishedAt: null, + parentStepId: foreignStepId, + }) + } + expect(await adapter.getJobById(jobId)).toMatchObject({ + status: JOB_STATUS_CREATED, + output: null, + finishedAt: null, + }) + } finally { + await adapter.stop() + await deleteDb() + } + }, + ) + + it.each([JOB_STATUS_COMPLETED, JOB_STATUS_FAILED, JOB_STATUS_CANCELLED])( + 'restores an archived %s job before returning false for a missing target', + async (status) => { + const { adapter, deleteDb } = await factory.create({ logger: 'silent' }) + try { + adapter.setId(crypto.randomUUID()) + const jobId = await createActiveJob(adapter, 'invalid-target') + const stepId = await createCompletedStep(adapter, jobId, 'saved-step') + if (status === JOB_STATUS_COMPLETED) { + expect(await adapter.completeJob({ jobId, output: { saved: 'job-output' } })).toBe(true) + } else if (status === JOB_STATUS_FAILED) { + expect(await adapter.failJob({ jobId, error: { message: 'saved-error' } })).toBe(true) + } else { + expect(await adapter.cancelJob({ jobId })).toBe(true) + } + const jobBefore = await adapter.getJobById(jobId) + const stepBefore = await adapter.getJobStepById(stepId) + expect(jobBefore?.status).toBe(status) + expect(await getJobStorage(adapter, jobId)).toEqual({ active: false, archived: true }) + const missingStepId = crypto.randomUUID() + expect(await adapter.getJobStepById(missingStepId)).toBeNull() + + expect(await adapter.timeTravelJob({ jobId, stepId: missingStepId })).toBe(false) + expect(await adapter.getJobById(jobId)).toEqual(jobBefore) + expect(await adapter.getJobStepById(stepId)).toEqual(stepBefore) + expect(await getJobStorage(adapter, jobId)).toEqual({ active: true, archived: false }) + } finally { + await adapter.stop() + await deleteDb() + } + }, + ) + }) +} + // ============================================================================= // Run Tests for Each Adapter // ============================================================================= runTests('pglite', pgliteFactory) +runIsolationTests(pgliteFactory) // oxlint-disable-next-line useLiteralKeys if (process.env['POSTGRES_TEST'] === 'true') { runTests('postgres', postgresFactory) + runIsolationTests(postgresFactory) } From e267efc6e40b8f9a6ead37b17f0662101ecf5295 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 7 Nov 2026 09:06:56 -0300 Subject: [PATCH 002/100] Apply step updatedAfter to both search branches Group the existing name and English output search predicates before the strict millisecond boundary. Preserve parameterization, storage union, ordering and output omission. Add both-engine boundary, precision and search-preservation regressions plus Client/REST contract coverage. Correct step-list documentation to the existing nonpaginated response. --- packages/docs/content/docs/client-api.mdx | 17 +- packages/docs/content/docs/server-api.mdx | 32 ++-- packages/duron/src/adapters/adapter.ts | 20 +-- packages/duron/src/adapters/postgres/base.ts | 4 +- packages/duron/src/client.ts | 10 +- packages/duron/test/adapter.test.ts | 161 ++++++++++++++++++- packages/duron/test/server.test.ts | 40 +++++ 7 files changed, 245 insertions(+), 39 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index e2c3c7d..ca9ef0e 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -473,27 +473,28 @@ const result = await client.getJobs({ ### `getJobSteps(options)` -Get steps for a job with pagination and fuzzy search. +Get all matching steps for a job from active and archive storage, ordered by `createdAt` ascending. +There are no `page` or `pageSize` options. ```ts const result = await client.getJobSteps({ jobId, - page: 1, - pageSize: 20, search: 'fetch', updatedAfter: new Date('2024-01-01'), }) +// result: { steps, total } ``` **Parameters:** - `options.jobId` - The ID of the job -- `options.page` - Page number (default: 1) -- `options.pageSize` - Number of items per page (default: 20) -- `options.search` - Fuzzy search in step names (optional) -- `options.updatedAfter` - Steps updated after this date (optional) +- `options.search` - Optional search in step names or output. SQL adapters use case-insensitive + name matching (including SQL `%` and `_` wildcards) or English full-text output search. +- `options.updatedAfter` - Optional strict boundary: only steps whose `updatedAt`, truncated to + milliseconds, is greater than this date. Applies to both name and output matches. -**Returns:** Promise resolving to steps result with pagination info +**Returns:** Promise resolving to `{ steps, total }`, where `total` equals `steps.length` after filtering. +Step output is searchable but omitted from list results. Use `getJobStepById` to retrieve output. ### `getJobStepById(stepId)` diff --git a/packages/docs/content/docs/server-api.mdx b/packages/docs/content/docs/server-api.mdx index a3e8760..0ebfd10 100644 --- a/packages/docs/content/docs/server-api.mdx +++ b/packages/docs/content/docs/server-api.mdx @@ -349,37 +349,43 @@ Delete multiple jobs using the same query parameters as `GET /jobs`. Active jobs #### `GET /jobs/:id/steps` -Get steps for a job with pagination and search. +Get all matching steps from active and archive storage, ordered by `createdAt` ascending. +This endpoint has no pagination. **Query Parameters:** -- `page` - Page number (default: 1) -- `pageSize` - Items per page (default: 20, max: 1000) -- `search` - Fuzzy search in step names -- `fUpdatedAfter` - Steps updated after this date (ISO string) +- `search` - Optional search in step names or output. SQL adapters use case-insensitive + name matching (including SQL `%` and `_` wildcards) or English full-text output search. +- `fUpdatedAfter` - Optional ISO date string. Only steps whose `updatedAt`, truncated to + milliseconds, is strictly greater than this date are returned, for either search branch. -**Response:** +**Response:** `{ steps, total }`, where `total` equals the number of returned steps after filtering. +Output is searchable but omitted from this response; use `GET /steps/:id` to retrieve it. ```json { - "data": [ + "steps": [ { "id": "uuid", "jobId": "job-uuid", + "parentStepId": null, + "parallel": false, "name": "fetchUser", "status": "completed", + "error": null, + "timeoutMs": 30000, + "expiresAt": "2024-01-01T00:00:31Z", + "retriesLimit": 3, + "retriesCount": 0, + "delayedMs": null, + "historyFailedAttempts": {}, "createdAt": "2024-01-01T00:00:00Z", "startedAt": "2024-01-01T00:00:01Z", "finishedAt": "2024-01-01T00:00:02Z", "updatedAt": "2024-01-01T00:00:02Z" } ], - "pagination": { - "page": 1, - "pageSize": 20, - "total": 5, - "totalPages": 1 - } + "total": 1 } ``` diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index bfdc817..be38fd3 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -751,12 +751,12 @@ export abstract class Adapter extends EventEmitter { } /** - * Get steps for a job with pagination and fuzzy search. - * Steps are always ordered by created_at ASC. - * Steps do not include output data. + * Get all matching steps for a job, ordered by created_at ASC, without pagination. + * Search matches step names or output; results omit output. + * updatedAfter applies a strict millisecond boundary to every match. * - * @param options - Query options including jobId, pagination, and search - * @returns Promise resolving to steps result with pagination info + * @param options - Query options including jobId, search, and updatedAfter + * @returns Promise resolving to { steps, total }, where total is the number of matching steps */ async getJobSteps(options: GetJobStepsOptions): Promise { try { @@ -875,12 +875,12 @@ export abstract class Adapter extends EventEmitter { protected abstract _getJobById(jobId: string): Promise /** - * Internal method to get steps for a job with pagination and fuzzy search. - * Steps are always ordered by created_at ASC. - * Steps do not include output data. + * Internal method to get all matching steps, ordered by created_at ASC, without pagination. + * Search matches step names or output; results omit output. + * updatedAfter applies a strict millisecond boundary to every match. * - * @param options - Validated query options including jobId, pagination, and search - * @returns Promise resolving to steps result with pagination info + * @param options - Validated query options including jobId, search, and updatedAfter + * @returns Promise resolving to { steps, total }, where total is the number of matching steps */ protected abstract _getJobSteps(options: GetJobStepsOptions): Promise diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 711e530..5cd4f63 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1470,8 +1470,8 @@ export abstract class PostgresBaseAdapter< ) s ${ fuzzySearch && fuzzySearch.length > 0 - ? sql`WHERE s.name ILIKE ${`%${fuzzySearch}%`} - OR to_tsvector('english', s.output::text) @@ plainto_tsquery('english', ${fuzzySearch})` + ? sql`WHERE (s.name ILIKE ${`%${fuzzySearch}%`} + OR to_tsvector('english', s.output::text) @@ plainto_tsquery('english', ${fuzzySearch}))` : sql`` } ${ diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 9202bd0..32e684c 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -818,12 +818,12 @@ export class Client< } /** - * Get steps for a job with pagination and fuzzy search. - * Steps are always ordered by created_at ASC. - * Steps do not include output data. + * Get all matching steps for a job, ordered by created_at ASC, without pagination. + * Search matches step names or output; results omit output. + * updatedAfter applies a strict millisecond boundary to every match. * - * @param options - Query options including jobId, pagination, and search - * @returns Promise resolving to steps result with pagination info + * @param options - Query options including jobId, search, and updatedAfter + * @returns Promise resolving to { steps, total }, where total is the number of matching steps */ async getJobSteps(options: GetJobStepsOptions): Promise { await this.start() diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index 2b9d028..e6a319d 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -1,5 +1,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { type SQL, sql } from 'drizzle-orm' + import { JOB_STATUS_ACTIVE, JOB_STATUS_CANCELLED, @@ -728,7 +730,164 @@ function runAdapterTests(adapterFactory: AdapterFactory) { expect(result.jobs[0]?.actionName).toBe('action-1') }) - it('should get job steps with pagination', async () => { + for (const storage of ['active', 'archive'] as const) { + it(`should apply the strict millisecond step-search boundary in ${storage} storage (seeded timestamps)`, async () => { + const jobId = await adapter.createJob({ + queue: 'step-search-boundary', + groupKey: 'test-group', + input: {}, + timeoutMs: 60_000, + checksum: 'abc123', + concurrencyLimit: 1, + concurrencyStepLimit: 10, + }) + expectToBeDefined(jobId) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId!]) + + const fixtures = [ + { name: 'needle-old', output: null, updated: '2026-01-01T00:00:00.122999Z' }, + { name: 'old-output', output: 'needle', updated: '2026-01-01T00:00:00.122999Z' }, + { name: 'needle-equal', output: null, updated: '2026-01-01T00:00:00.123000Z' }, + { name: 'equal-output', output: 'needle', updated: '2026-01-01T00:00:00.123000Z' }, + { name: 'needle-submillisecond', output: null, updated: '2026-01-01T00:00:00.123999Z' }, + { + name: 'submillisecond-output', + output: 'needle', + updated: '2026-01-01T00:00:00.123999Z', + }, + { name: 'needle-new', output: null, updated: '2026-01-01T00:00:00.124000Z' }, + { name: 'new-output', output: 'needle', updated: '2026-01-01T00:00:00.124000Z' }, + { name: 'unrelated-new', output: 'haystack', updated: '2026-01-01T00:00:00.124000Z' }, + ] + const ids: string[] = [] + for (const fixture of fixtures) { + const step = await adapter.createOrRecoverJobStep({ + jobId: jobId!, + parentStepId: null, + name: fixture.name, + timeoutMs: 60_000, + retriesLimit: 0, + }) + expectToBeDefined(step) + ids.push(step!.id) + expect( + await adapter.completeJobStep({ stepId: step!.id, output: fixture.output }), + ).toBe(true) + } + if (storage === 'archive') { + expect(await adapter.completeJob({ jobId: jobId!, output: null })).toBe(true) + } + + // Native SQL fixture seam: public writers cannot supply microsecond timestamps. + // Seed after public archival so Date conversion cannot hide the precision case. + const { db } = adapter as unknown as { + db: { + execute: ( + query: SQL, + ) => Promise<{ timestamp: string }[] | { rows: { timestamp: string }[] }> + } + } + const table = sql.identifier(`job_steps_${storage}`) + for (const [index, fixture] of fixtures.entries()) { + const seeded = await db.execute(sql` + UPDATE duron.${table} + SET updated_at = ${fixture.updated}::timestamptz, + created_at = '2026-01-01T00:00:00Z'::timestamptz + ${index} * interval '1 second' + WHERE id = ${ids[index]} + RETURNING to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS timestamp + `) + // Verify native microseconds and actual storage membership, not a JS Date round trip. + expect(Array.isArray(seeded) ? seeded : seeded.rows).toEqual([ + { timestamp: fixture.updated }, + ]) + } + + const withoutBoundary = await adapter.getJobSteps({ jobId: jobId!, search: 'needle' }) + expect(withoutBoundary.steps.map((step) => step.id)).toEqual(ids.slice(0, 8)) + expect(withoutBoundary.total).toBe(8) + + const updatedAfter = new Date('2026-01-01T00:00:00.123Z') + const result = await adapter.getJobSteps({ + jobId: jobId!, + search: 'needle', + updatedAfter, + }) + expect(result.steps.map((step) => step.id)).toEqual([ids[6]!, ids[7]!]) + expect(result.total).toBe(2) + for (const step of result.steps) { + expect(step).not.toHaveProperty('output') + expect(step.updatedAt).toEqual(new Date('2026-01-01T00:00:00.124Z')) + } + + for (const search of [undefined, ' ']) { + const unsearched = await adapter.getJobSteps({ jobId: jobId!, search, updatedAfter }) + expect(unsearched.steps.map((step) => step.id)).toEqual([ids[6]!, ids[7]!, ids[8]!]) + expect(unsearched.total).toBe(3) + } + }) + + it(`should preserve wildcard names and plain English output search in ${storage} storage`, async () => { + const jobId = await adapter.createJob({ + queue: 'step-search-semantics', + groupKey: 'test-group', + input: {}, + timeoutMs: 60_000, + checksum: 'abc123', + concurrencyLimit: 1, + concurrencyStepLimit: 10, + }) + expectToBeDefined(jobId) + await adapter.fetch({ batch: 1 }) + const nameMatch = await adapter.createOrRecoverJobStep({ + jobId: jobId!, + parentStepId: null, + name: 'MiXeD-alphaZtail', + timeoutMs: 60_000, + retriesLimit: 0, + }) + const outputMatch = await adapter.createOrRecoverJobStep({ + jobId: jobId!, + parentStepId: null, + name: 'payload', + timeoutMs: 60_000, + retriesLimit: 0, + }) + expectToBeDefined(nameMatch) + expectToBeDefined(outputMatch) + expect(await adapter.completeJobStep({ stepId: nameMatch!.id, output: null })).toBe(true) + expect( + await adapter.completeJobStep({ + stepId: outputMatch!.id, + output: { text: 'running foxes' }, + }), + ).toBe(true) + if (storage === 'archive') { + expect(await adapter.completeJob({ jobId: jobId!, output: null })).toBe(true) + } + + // Public-only fixture: SQL wildcards/casing and English stemming remain native. + for (const [search, expectedIds] of [ + [' MIXED%tail ', [nameMatch!.id]], + ['alpha_tail', [nameMatch!.id]], + ['runs fox', [outputMatch!.id]], + ['fox | absent', []], // Plain text, not a raw tsquery OR operator. + ["' OR 1=1 --", []], + ] as const) { + const result = await adapter.getJobSteps({ + jobId: jobId!, + search, + updatedAfter: new Date(0), + }) + expect(result.steps.map((step) => step.id)).toEqual([...expectedIds]) + expect(result.total).toBe(expectedIds.length) + for (const step of result.steps) { + expect(step).not.toHaveProperty('output') + } + } + }) + } + + it('should get all job steps without pagination', async () => { const jobId = await adapter.createJob({ queue: 'test-action', groupKey: 'test-group', diff --git a/packages/duron/test/server.test.ts b/packages/duron/test/server.test.ts index 42004b9..24bc680 100644 --- a/packages/duron/test/server.test.ts +++ b/packages/duron/test/server.test.ts @@ -206,6 +206,46 @@ function runServerTests(adapterFactory: AdapterFactory) { expect(result.steps.length).toBe(result.total) }) + it('should expose the same nonpaginated filtered step contract through Client and REST', async () => { + const jobId = await client.runAction('testAction', { message: 'Step list contract' }) + await client.fetch({ batchSize: 1 }) + expect((await client.waitForJob(jobId, { timeout: 5000 }))?.status).toBe( + JOB_STATUS_COMPLETED, + ) + + const outputMatches = await client.getJobSteps({ jobId, search: 'processed' }) + expect(outputMatches.steps.map((step) => step.name)).toEqual(['step-1']) + expect(outputMatches.total).toBe(1) + expect(outputMatches.steps[0]).not.toHaveProperty('output') + const boundary = outputMatches.steps[0]!.updatedAt + + for (const search of ['processed', 'step-1']) { + for (const updatedAfter of [new Date(0), boundary]) { + const expectedTotal = updatedAfter === boundary ? 0 : 1 + const direct = await client.getJobSteps({ jobId, search, updatedAfter }) + expect(Object.keys(direct).toSorted()).toEqual(['steps', 'total']) + expect(direct.total).toBe(expectedTotal) + expect(direct.steps.map((step) => step.name)).toEqual(expectedTotal ? ['step-1'] : []) + + const query = new URLSearchParams({ search, fUpdatedAfter: updatedAfter.toISOString() }) + const response = await server.handle( + new Request(`http://localhost/api/jobs/${jobId}/steps?${query}`), + ) + expect(response.status).toBe(200) + // Check the raw response: schema parsing could hide extra pagination/output fields. + const body = (await response.json()) as { + steps: Record[] + total: number + } + expect(body).toEqual(JSON.parse(JSON.stringify(direct))) + expect(Object.keys(body).toSorted()).toEqual(['steps', 'total']) + for (const step of body.steps) { + expect(step).not.toHaveProperty('output') + } + } + } + }) + it('should filter steps by search query', async () => { const jobId = await client.runAction('testAction', { message: 'Search steps', From 39028eb9ad86f16c2122ff48104f3b3607cf7822 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 7 Nov 2026 10:07:27 -0300 Subject: [PATCH 003/100] Fix global job listing order and pagination Filter active/archive populations before a single global SQL page and obtain an independent exact count. Preserve ORM decoding, output, UTF-16 text order, public Date precision, Number duration ties, and final UUID ascending order. Add both-engine listing, restoration, Client/REST, filter/error, and real-driver payload-bound regressions. Correct listing documentation and the explicitly approved status-filter fixture assumption. Root typecheck/lint/test/format and core build pass. Listing-scoped both-engine verification passes; the unrelated preexisting PGLite recovery fixture failure from the broader run remains documented in the local implementation ticket. --- packages/docs/content/docs/client-api.mdx | 23 +- packages/docs/content/docs/server-api.mdx | 46 +- packages/duron/src/adapters/adapter.ts | 8 +- packages/duron/src/adapters/postgres/base.ts | 246 ++++---- packages/duron/src/client.ts | 2 +- packages/duron/test/adapter.test.ts | 597 ++++++++++++++++++- packages/duron/test/client.test.ts | 38 ++ packages/duron/test/server.test.ts | 44 +- 8 files changed, 840 insertions(+), 164 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index ca9ef0e..27315fb 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -415,7 +415,21 @@ const job = await client.getJobById(jobId) ### `getJobs(options?)` -Get jobs with pagination, filtering, and sorting. +Get matching jobs from active and archive storage with global sorting and pagination. +Job records include input, output, and error, but not steps. A terminal job restored to +active storage remains visible under its status filter. + +SQL adapters apply every requested sort key in order, then use job ID ascending to +break ties. An empty sort array uses only ID ascending. The default is `startedAt` +descending. Nulls sort last ascending and first descending; text uses JavaScript +UTF-16 lexical order, dates use public millisecond precision, and `duration` sorts +numeric `durationMs` (including fractional or negative values). + +`total` counts all matching jobs even for an empty or out-of-range page. Count and +page queries do not share a method-wide snapshot, and separate page requests do +not promise a stable snapshot during concurrent changes. At most `pageSize` job +payloads return from the database; this does not bound payload size, database +filtering/sorting work, or latency. ```ts const result = await client.getJobs({ @@ -445,7 +459,7 @@ const result = await client.getJobs({ **Parameters:** - `options.page` - Page number (default: 1) -- `options.pageSize` - Number of items per page (default: 20) +- `options.pageSize` - Number of items per page (default: 10) - `options.filters` - Filter options (see below) - `options.sort` - Sort options (see below) @@ -466,10 +480,11 @@ const result = await client.getJobs({ **Sort Options:** -- `field` - Field to sort by: `'createdAt'`, `'startedAt'`, `'finishedAt'`, `'updatedAt'`, `'status'`, `'actionName'`, `'description'` +- `field` - Field to sort by: `'createdAt'`, `'startedAt'`, `'finishedAt'`, `'status'`, `'actionName'`, `'expiresAt'`, `'duration'`, `'description'` - `order` - Sort order: `'asc'` or `'desc'` -**Returns:** Promise resolving to jobs result with pagination info +**Returns:** Promise resolving to `{ jobs, total, page, pageSize }`. Job timestamps are +`Date` values; `durationMs` is a number or `null`. ### `getJobSteps(options)` diff --git a/packages/docs/content/docs/server-api.mdx b/packages/docs/content/docs/server-api.mdx index 0ebfd10..b7876c2 100644 --- a/packages/docs/content/docs/server-api.mdx +++ b/packages/docs/content/docs/server-api.mdx @@ -176,12 +176,24 @@ Authenticate and receive JWT tokens. #### `GET /jobs` -Get jobs with pagination, filtering, and sorting. +Get matching jobs from active and archive storage with global sorting and pagination. +Job records include input, output, and error, but not steps. Restored terminal jobs +remain visible under their status filters. + +SQL adapters apply sort keys in the supplied order, followed by job ID ascending for +ties. The default sort is `startedAt:desc`. Nulls sort last ascending and first +descending; text follows JavaScript UTF-16 lexical order, dates use public millisecond +precision, and `duration` sorts numeric `durationMs`. + +`total` includes all matching jobs even when the page is empty. Count and page are +separate queries, not a method-wide or cross-request snapshot. At most `pageSize` +job payloads return from the database; payload size, database work, and latency are +not bounded by this limit. **Query Parameters:** - `page` - Page number (default: 1) -- `pageSize` - Items per page (default: 20, max: 1000) +- `pageSize` - Items per page (default: 10, max: 1000) - `fStatus` - Filter by status (comma-separated or multiple params) - `fActionName` - Filter by action name (comma-separated or multiple params) - `fGroupKey` - Filter by group key (comma-separated or multiple params) @@ -202,30 +214,36 @@ Get jobs with pagination, filtering, and sorting. GET /api/jobs?page=1&pageSize=20&fStatus=active,completed&sort=createdAt:desc ``` -**Response:** +**Response:** `{ jobs, total, page, pageSize }`. Timestamps are serialized as ISO +strings (or `null` for nullable timestamps); `durationMs` is a number or `null`. ```json { - "data": [ + "jobs": [ { "id": "uuid", "actionName": "sendEmail", + "groupKey": "user-123", "description": "Send email to user@example.com", "status": "completed", "input": { "to": "user@example.com" }, "output": { "success": true }, - "createdAt": "2024-01-01T00:00:00Z", - "startedAt": "2024-01-01T00:00:01Z", - "finishedAt": "2024-01-01T00:00:05Z", - "updatedAt": "2024-01-01T00:00:05Z" + "error": null, + "timeoutMs": 60000, + "expiresAt": "2024-01-01T00:01:01.000Z", + "createdAt": "2024-01-01T00:00:00.000Z", + "startedAt": "2024-01-01T00:00:01.000Z", + "finishedAt": "2024-01-01T00:00:05.000Z", + "updatedAt": "2024-01-01T00:00:05.000Z", + "concurrencyLimit": 1, + "concurrencyStepLimit": 1, + "clientId": "worker-1", + "durationMs": 4000 } ], - "pagination": { - "page": 1, - "pageSize": 20, - "total": 100, - "totalPages": 5 - } + "page": 1, + "pageSize": 20, + "total": 100 } ``` diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index be38fd3..b869f55 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -770,8 +770,8 @@ export abstract class Adapter extends EventEmitter { } /** - * Get jobs with pagination, filtering, and sorting. - * Does not include step information or job output. + * Get jobs with global pagination, filtering, and sorting across active and archive storage. + * Includes job output, but not step information. * * @param options - Query options including pagination, filters, and sort * @returns Promise resolving to jobs result with pagination info @@ -885,8 +885,8 @@ export abstract class Adapter extends EventEmitter { protected abstract _getJobSteps(options: GetJobStepsOptions): Promise /** - * Internal method to get jobs with pagination, filtering, and sorting. - * Does not include step information or job output. + * Internal method to get jobs with global pagination, filtering, and sorting. + * Includes job output, but not step information. * * @param options - Validated query options including pagination, filters, and sort * @returns Promise resolving to jobs result with pagination info diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 5cd4f63..a626fd0 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1,4 +1,17 @@ -import { and, between, desc, eq, gt, gte, ilike, inArray, isNull, ne, or, sql } from 'drizzle-orm' +import { + type SQL, + and, + between, + eq, + gt, + gte, + ilike, + inArray, + isNull, + ne, + or, + sql, +} from 'drizzle-orm' import type { PgAsyncDatabase, PgColumn } from 'drizzle-orm/pg-core' import type { AnyRelations } from 'drizzle-orm/relations' @@ -1678,152 +1691,125 @@ export abstract class PostgresBaseAdapter< } /** - * Internal method to get jobs with pagination, filtering, and sorting. - * Does not include step information or job output. + * Get globally ordered matching jobs, including output but not steps. + * Only the requested page payload and a separate count return from the database; + * this does not bound database filtering/sorting work or provide a shared snapshot. */ protected async _getJobs(options?: GetJobsOptions): Promise { const page = options?.page ?? 1 const pageSize = options?.pageSize ?? 10 const filters = options?.filters ?? {} - // Determine which table(s) to query based on status filter - const activeStatuses = [JOB_STATUS_CREATED, JOB_STATUS_ACTIVE] const archiveStatuses = [JOB_STATUS_COMPLETED, JOB_STATUS_FAILED, JOB_STATUS_CANCELLED] const statusFilter = filters.status const statuses = Array.isArray(statusFilter) ? statusFilter : statusFilter ? [statusFilter] : [] - - const queryActive = - statuses.length === 0 || statuses.some((s) => (activeStatuses as string[]).includes(s)) const queryArchive = statuses.length === 0 || statuses.some((s) => (archiveStatuses as string[]).includes(s)) - // Query active table - let activeJobs: any[] = [] - let activeTotal = 0 - if (queryActive) { - const jobsTable = this.tables.jobsActiveTable - const where = this._buildJobsWhereClause(filters) - activeTotal = await this.db.$count(jobsTable, where) - - if (activeTotal > 0) { - const durationMs = sql` - CASE - WHEN ${jobsTable.started_at} IS NOT NULL AND ${jobsTable.finished_at} IS NOT NULL - THEN EXTRACT(EPOCH FROM (${jobsTable.finished_at} - ${jobsTable.started_at})) * 1000 - ELSE NULL - END - `.as('duration_ms') - - activeJobs = await this.db - .select({ - id: jobsTable.id, - actionName: jobsTable.action_name, - groupKey: jobsTable.group_key, - description: jobsTable.description, - input: jobsTable.input, - output: jobsTable.output, - error: jobsTable.error, - status: jobsTable.status, - timeoutMs: jobsTable.timeout_ms, - expiresAt: jobsTable.expires_at, - startedAt: jobsTable.started_at, - finishedAt: jobsTable.finished_at, - createdAt: jobsTable.created_at, - updatedAt: jobsTable.updated_at, - concurrencyLimit: jobsTable.concurrency_limit, - concurrencyStepLimit: jobsTable.concurrency_step_limit, - clientId: jobsTable.client_id, - durationMs, - }) - .from(jobsTable) - .where(where) - .orderBy(desc(jobsTable.created_at)) - .limit(pageSize) - .offset((page - 1) * pageSize) - } - } - - // Query archive table - let archiveJobs: any[] = [] - let archiveTotal = 0 - if (queryArchive) { - const archiveTable = this.tables.jobsArchiveTable - // Build where clause for archive (similar to active but using archive table) - const archiveWhere = this._buildArchiveJobsWhereClause(filters) - archiveTotal = await this.db.$count(archiveTable, archiveWhere) - - if (archiveTotal > 0) { - const durationMs = sql` - CASE - WHEN ${archiveTable.started_at} IS NOT NULL AND ${archiveTable.finished_at} IS NOT NULL - THEN EXTRACT(EPOCH FROM (${archiveTable.finished_at} - ${archiveTable.started_at})) * 1000 - ELSE NULL - END - `.as('duration_ms') - - archiveJobs = await this.db - .select({ - id: archiveTable.id, - actionName: archiveTable.action_name, - groupKey: archiveTable.group_key, - description: archiveTable.description, - input: archiveTable.input, - output: archiveTable.output, - error: archiveTable.error, - status: archiveTable.status, - timeoutMs: archiveTable.timeout_ms, - expiresAt: archiveTable.expires_at, - startedAt: archiveTable.started_at, - finishedAt: archiveTable.finished_at, - createdAt: archiveTable.created_at, - updatedAt: archiveTable.updated_at, - concurrencyLimit: archiveTable.concurrency_limit, - concurrencyStepLimit: archiveTable.concurrency_step_limit, - clientId: archiveTable.client_id, - durationMs, - }) - .from(archiveTable) - .where(archiveWhere) - .orderBy(desc(archiveTable.created_at)) - .limit(pageSize) - .offset((page - 1) * pageSize) - } - } - - // Combine results - const allJobs = [...activeJobs, ...archiveJobs] - const total = activeTotal + archiveTotal + // Active storage can contain every status after a false time-travel restoration. + const activeTable = this.tables.jobsActiveTable + const archiveTable = this.tables.jobsArchiveTable + const activeWhere = this._buildJobsWhereClause(filters) + const archiveWhere = this._buildArchiveJobsWhereClause(filters) + const selectJobs = ( + table: Schema['jobsActiveTable'] | Schema['jobsArchiveTable'], + where: SQL | undefined, + ) => + this.db + .select({ + id: table.id, + actionName: table.action_name, + groupKey: table.group_key, + description: table.description, + input: table.input, + output: table.output, + error: table.error, + status: table.status, + timeoutMs: table.timeout_ms, + expiresAt: table.expires_at, + startedAt: table.started_at, + finishedAt: table.finished_at, + createdAt: table.created_at, + updatedAt: table.updated_at, + concurrencyLimit: table.concurrency_limit, + concurrencyStepLimit: table.concurrency_step_limit, + clientId: table.client_id, + durationMs: sql` + CASE WHEN ${table.started_at} IS NOT NULL AND ${table.finished_at} IS NOT NULL + THEN EXTRACT(EPOCH FROM (${table.finished_at} - ${table.started_at})) * 1000 + ELSE NULL END + `.as('duration_ms'), + }) + .from(table) + .where(where) + + const active = selectJobs(activeTable, activeWhere) + const matching = ( + queryArchive ? active.unionAll(selectJobs(archiveTable, archiveWhere)) : active + ).as('matching_jobs') + const activeIds = this.db.select({ id: activeTable.id }).from(activeTable).where(activeWhere) + const matchingIds = ( + queryArchive + ? activeIds.unionAll( + this.db.select({ id: archiveTable.id }).from(archiveTable).where(archiveWhere), + ) + : activeIds + ).as('matching_job_ids') - // Sort combined results + // A separate scalar count survives empty pages. This does not add a shared snapshot. + const [count] = await this.db + .select({ total: sql`count(*)`.mapWith(Number) }) + .from(matchingIds) const sortInput = options?.sort ?? { field: 'startedAt', order: 'desc' } const sorts = Array.isArray(sortInput) ? sortInput : [sortInput] - - allJobs.sort((a, b) => { - for (const sort of sorts) { - const field = sort.field - const order = sort.order.toUpperCase() === 'ASC' ? 1 : -1 - const aVal = a[field] - const bVal = b[field] - - if (aVal === null && bVal === null) continue - if (aVal === null) return order - if (bVal === null) return -order - - if (aVal < bVal) return -order - if (aVal > bVal) return order + const order = sorts.map((sort) => { + const column = matching[sort.field === 'duration' ? 'durationMs' : sort.field] + let key = sql`${column}` + if (sort.field === 'description' || sort.field === 'actionName' || sort.field === 'status') { + // SQL locale/code-point order differs from JS UTF-16 lexical order. Decode explicitly + // converted UTF8 bytes, then emit BMP units or surrogate pairs without installing a function. + key = sql`CASE WHEN ${column} IS NULL THEN NULL ELSE ARRAY( + SELECT unit FROM generate_series(1, char_length(${column})) AS positions(pos) + CROSS JOIN LATERAL ( + SELECT convert_to(substr(${column}, positions.pos, 1), 'UTF8') AS bytes + ) AS encoded + CROSS JOIN LATERAL (SELECT CASE octet_length(bytes) + WHEN 1 THEN get_byte(bytes, 0) + WHEN 2 THEN (get_byte(bytes, 0) - 192) * 64 + get_byte(bytes, 1) - 128 + WHEN 3 THEN (get_byte(bytes, 0) - 224) * 4096 + + (get_byte(bytes, 1) - 128) * 64 + get_byte(bytes, 2) - 128 + WHEN 4 THEN (get_byte(bytes, 0) - 240) * 262144 + + (get_byte(bytes, 1) - 128) * 4096 + + (get_byte(bytes, 2) - 128) * 64 + get_byte(bytes, 3) - 128 + END AS codepoint) AS decoded + CROSS JOIN LATERAL unnest(CASE WHEN codepoint < 65536 THEN ARRAY[codepoint] + ELSE ARRAY[55296 + ((codepoint - 65536) / 1024), + 56320 + ((codepoint - 65536) % 1024)] END) + WITH ORDINALITY AS units(unit, ordinal) + ORDER BY positions.pos, units.ordinal + ) END` + } else if ( + sort.field === 'createdAt' || + sort.field === 'startedAt' || + sort.field === 'finishedAt' || + sort.field === 'expiresAt' + ) { + // Match the selected timestamp's ORM Date precision, including before the epoch. + key = sql`date_trunc('milliseconds', ${column})` + } else if (sort.field === 'duration') { + // The public duration is a Number, so SQL-only extra precision must not break its ties. + key = sql`${column}::double precision` } - return 0 + return sql`${key} ${sql.raw(sort.order === 'asc' ? 'ASC NULLS LAST' : 'DESC NULLS FIRST')}` }) - - // Apply pagination - const paginatedJobs = allJobs.slice(0, pageSize) - - return { - jobs: paginatedJobs, - total, - page, - pageSize, - } + const jobs = await this.db + .select() + .from(matching) + .orderBy(...order, sql`${matching.id} ASC`) + .offset((page - 1) * pageSize) + .limit(pageSize) + + return { jobs, total: count!.total, page, pageSize } } /** diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 32e684c..7398554 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -832,7 +832,7 @@ export class Client< /** * Get jobs with pagination, filtering, and sorting. - * Does not include step information or job output. + * Includes job output, but not step information. * * @param options - Query options including pagination, filters, and sort * @returns Promise resolving to jobs result with pagination info diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index e6a319d..46a4261 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'bun:test' import { type SQL, sql } from 'drizzle-orm' +import type { GetJobsOptions } from '../src/adapters/schemas.js' import { JOB_STATUS_ACTIVE, JOB_STATUS_CANCELLED, @@ -624,6 +625,574 @@ function runAdapterTests(adapterFactory: AdapterFactory) { await adapter.start() }) + // Native fixture seam for listing precision/order cases. All IDs come from public creation; + // archives use public cancellation. SQL seeds are labeled at each test, never public-only. + async function createListingJobs(count: number) { + const ids: string[] = [] + for (let index = 0; index < count; index++) { + const id = await adapter.createJob({ + queue: 'listing-order', + groupKey: 'test-group', + input: { marker: 'input', payload: 'i'.repeat(16_384) }, + timeoutMs: 60_000, + checksum: 'abc123', + concurrencyLimit: 10, + concurrencyStepLimit: 1, + }) + expectToBeDefined(id) + ids.push(id) + } + // Rank fixture IDs, never sort the returned listing before asserting it. + return ids.toSorted() + } + + async function seedListingJob(id: string, storage: 'active' | 'archive', fields: SQL) { + const { db } = adapter as unknown as { + db: { execute: (query: SQL) => Promise } + } + await db.execute(sql`UPDATE duron.${sql.identifier(`jobs_${storage}`)} + SET ${fields} WHERE id = ${id}`) + } + + it('should paginate the globally interleaved population (seeded creation times)', async () => { + const ids = await createListingJobs(6) + for (const [rank, id] of ids.entries()) { + const storage = rank % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + await seedListingJob( + id, + storage, + sql`created_at = ${`2026-01-0${6 - rank}T00:00:00Z`}::timestamptz`, + ) + } + for (const [page, ranks] of [[0, 1], [2, 3], [4, 5], [], []].entries()) { + const result = await adapter.getJobs({ + page: page + 1, + pageSize: 2, + sort: { field: 'createdAt', order: 'desc' }, + }) + expect(result.jobs.map((job) => job.id)).toEqual(ranks.map((rank) => ids[rank]!)) + expect(result.total).toBe(6) + expect(result.page).toBe(page + 1) + expect(result.pageSize).toBe(2) + for (const job of result.jobs) { + expect(job.input).toEqual({ marker: 'input', payload: 'i'.repeat(16_384) }) + expect(job.createdAt).toBeInstanceOf(Date) + } + } + }) + + it('should preserve secondary keys and final ID ties, including empty sorts (seeded keys)', async () => { + const ids = await createListingJobs(4) + for (const [rank, id] of ids.entries()) { + const storage = rank % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + await seedListingJob( + id, + storage, + sql` + description = 'equal', + created_at = ${`2026-01-0${[1, 3, 2, 2][rank]}T00:00:00Z`}::timestamptz`, + ) + } + const secondary = await adapter.getJobs({ + sort: [ + { field: 'description', order: 'asc' }, + { field: 'createdAt', order: 'desc' }, + ], + }) + expect(secondary.jobs.map((job) => job.id)).toEqual([ids[1]!, ids[2]!, ids[3]!, ids[0]!]) + expect(secondary.total).toBe(4) + for (const sort of [ + [], + [{ field: 'description', order: 'desc' }], + [ + { field: 'description', order: 'asc' }, + { field: 'description', order: 'desc' }, + ], + ] as const) { + for (const page of [1, 2, 2, 3]) { + const result = await adapter.getJobs({ page, pageSize: 2, sort: [...sort] }) + expect(result.jobs.map((job) => job.id)).toEqual(ids.slice((page - 1) * 2, page * 2)) + expect(result.total).toBe(4) + } + } + }) + + for (const field of ['description', 'actionName'] as const) { + it(`should order ${field} by UTF-16 units with prefixes and nulls (seeded text)`, async () => { + const values = [ + '\uE000', + '\u{10000}', + 'a\uE000', + 'a\u{10000}', + '', + 'a', + null, + '\uFFFF', + '\uD7FF', + '\u{10FFFF}', + 'é', + 'e\u0301', + 'A', + ] + const ids = await createListingJobs(values.length) + for (const [rank, id] of ids.entries()) { + const storage = rank % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + const value = field === 'actionName' && values[rank] === null ? 'z' : values[rank] + await seedListingJob( + id, + storage, + sql`${sql.identifier(field === 'actionName' ? 'action_name' : field)} = ${value}`, + ) + } + const ascending = + field === 'description' + ? [4, 12, 5, 3, 2, 11, 10, 8, 1, 9, 0, 7, 6] + : [4, 12, 5, 3, 2, 11, 6, 10, 8, 1, 9, 0, 7] + for (const order of ['asc', 'desc'] as const) { + const expected = order === 'asc' ? ascending : ascending.toReversed() + for (let page = 1; page <= 6; page++) { + const result = await adapter.getJobs({ page, pageSize: 3, sort: { field, order } }) + expect(result.jobs.map((job) => job.id)).toEqual( + expected.slice((page - 1) * 3, page * 3).map((rank) => ids[rank]!), + ) + expect(result.total).toBe(values.length) + for (const job of result.jobs) { + const value = values[ids.indexOf(job.id)] ?? null + expect(job[field]).toBe(field === 'actionName' && value === null ? 'z' : value) + } + } + } + }) + } + + for (const [field, column] of [ + ['createdAt', 'created_at'], + ['startedAt', 'started_at'], + ['finishedAt', 'finished_at'], + ['expiresAt', 'expires_at'], + ] as const) { + it(`should order ${field} by public Date milliseconds (seeded native precision)`, async () => { + const timestamps = [ + '1970-01-01T00:00:00.000900Z', + '1970-01-01T00:00:00.000100Z', + '1970-01-01T00:00:00.001000Z', + '1969-12-31T23:59:59.999900Z', + '1969-12-31T23:59:59.999100Z', + '1970-01-01T00:00:00.000000Z', + '1969-12-31T23:59:59.998900Z', + ...(field === 'createdAt' ? [] : [null, null]), + ] + const milliseconds = [0, 0, 1, -1, -1, 0, -2, null, null] + const ids = await createListingJobs(timestamps.length) + for (const [rank, id] of ids.entries()) { + const storage = rank % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + await seedListingJob( + id, + storage, + sql`${sql.identifier(column)} = ${timestamps[rank]}::timestamptz`, + ) + } + for (const order of ['asc', 'desc'] as const) { + const nulls = field === 'createdAt' ? [] : [7, 8] + const expected = + order === 'asc' ? [6, 3, 4, 0, 1, 5, 2, ...nulls] : [...nulls, 2, 0, 1, 5, 3, 4, 6] + for (let page = 1; page <= 4; page++) { + const result = await adapter.getJobs({ page, pageSize: 3, sort: { field, order } }) + expect(result.jobs.map((job) => job.id)).toEqual( + expected.slice((page - 1) * 3, page * 3).map((rank) => ids[rank]!), + ) + expect(result.total).toBe(timestamps.length) + for (const job of result.jobs) { + const expectedMs = milliseconds[ids.indexOf(job.id)] ?? null + expect(job[field]?.getTime() ?? null).toBe(expectedMs) + } + } + } + }) + } + + it('should order numeric duration and Number-rounded ties (seeded native durations)', async () => { + const durations = [100, 10, 2, 2.5, null, -1.25, 94670899200000, 94670899200000] + const ids = await createListingJobs(durations.length) + for (const [rank, id] of ids.entries()) { + const storage = rank % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + const finish = + rank < 6 + ? sql`'2000-01-01T00:00:00Z'::timestamptz + ${durations[rank]} * interval '1 millisecond'` + : sql`${rank === 6 ? '5000-01-01T00:00:00.000001Z' : '5000-01-01T00:00:00.000000Z'}::timestamptz` + await seedListingJob( + id, + storage, + sql` + description = 'same', started_at = '2000-01-01T00:00:00Z'::timestamptz, + finished_at = ${finish}`, + ) + } + for (const order of ['asc', 'desc'] as const) { + const expected = order === 'asc' ? [5, 2, 3, 1, 0, 6, 7, 4] : [4, 6, 7, 0, 1, 3, 2, 5] + for (const sort of [ + [{ field: 'duration', order }], + [ + { field: 'description', order: 'asc' }, + { field: 'duration', order }, + ], + ] as const) { + const result = await adapter.getJobs({ sort: [...sort] }) + expect(result.jobs.map((job) => job.id)).toEqual(expected.map((rank) => ids[rank]!)) + expect(result.total).toBe(durations.length) + expect(result.jobs.map((job) => job.durationMs)).toEqual( + expected.map((rank) => durations[rank] ?? null), + ) + for (const job of result.jobs) { + if (job.durationMs !== null) expect(typeof job.durationMs).toBe('number') + } + } + } + }) + + it('should sort contrary to creation order in each population (seeded keys)', async () => { + const ids = await createListingJobs(6) + for (const [rank, id] of ids.entries()) { + const storage = rank % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + await seedListingJob( + id, + storage, + sql` + created_at = ${`2026-01-0${6 - rank}T00:00:00Z`}::timestamptz, + description = ${String(6 - rank)}`, + ) + } + for (const [status, expected] of [ + [undefined, [5, 4, 3, 2, 1, 0]], + [JOB_STATUS_CREATED, [4, 2, 0]], + [JOB_STATUS_CANCELLED, [5, 3, 1]], + ] as const) { + for (let page = 1; page <= 4; page++) { + const result = await adapter.getJobs({ + filters: { status }, + page, + pageSize: 2, + sort: { field: 'description', order: 'asc' }, + }) + expect(result.jobs.map((job) => job.id)).toEqual( + expected.slice((page - 1) * 2, page * 2).map((rank) => ids[rank]!), + ) + expect(result.total).toBe(expected.length) + } + } + const defaults = await adapter.getJobs() + expect(defaults.jobs.map((job) => job.id)).toEqual(ids) + expect(defaults).toMatchObject({ total: 6, page: 1, pageSize: 10 }) + const statuses = await adapter.getJobs({ sort: { field: 'status', order: 'asc' } }) + expect(statuses.jobs.map((job) => job.id)).toEqual([ + ids[1]!, + ids[3]!, + ids[5]!, + ids[0]!, + ids[2]!, + ids[4]!, + ]) + }) + + it('should return only the global page payload from the real driver (observed driver boundary)', async () => { + const ids = await createListingJobs(6) + for (const [rank, id] of ids.entries()) { + const storage = rank % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + await seedListingJob( + id, + storage, + sql`output = ${JSON.stringify({ payload: 'o'.repeat(16_384) })}::jsonb`, + ) + } + const payloadBatches: number[] = [] + const scalarBatches: number[] = [] + function observe(fields: { name: string }[], rows: unknown[]) { + if (fields.some((field) => field.name === 'input')) { + expect(fields.some((field) => field.name === 'output')).toBe(true) + payloadBatches.push(rows.length) + } else { + scalarBatches.push(rows.length) + } + } + // Observe actual driver results before ORM mapping. Never fabricate, truncate or sort them. + const { + db: { $client: driver }, + } = adapter as unknown as { + db: { $client: Record } + } + const method = adapterFactory.name === 'postgres' ? 'unsafe' : 'query' + const descriptor = Object.getOwnPropertyDescriptor(driver, method) + if (adapterFactory.name === 'postgres') { + type Rows = unknown[] & { columns: { name: string }[] } + type Pending = Promise & { values(): Pending } + const unsafe = driver[method] as (...args: unknown[]) => Pending + driver[method] = (...args: unknown[]) => { + const pending = unsafe.apply(driver, args) + const then = pending.then.bind(pending) + let observed = false + // Keep the actual lazy Query (including .values()); delegate to its original then. + // oxlint-disable-next-line unicorn/no-thenable -- Observe an existing driver Promise, not a new thenable. + pending.then = (fulfilled, rejected) => + then((rows) => { + if (!observed) { + observe(rows.columns, rows) + observed = true + } + return rows + }).then(fulfilled, rejected) + return pending + } + } else { + const query = driver[method] as (...args: unknown[]) => Promise<{ + fields: { name: string }[] + rows: unknown[] + }> + driver[method] = async (...args: unknown[]) => { + const result = await query.apply(driver, args) + observe(result.fields, result.rows) + return result + } + } + try { + for (const [page, expected] of [ + [1, [ids[0]!, ids[1]!]], + [2, [ids[2]!, ids[3]!]], + [9, []], + ] as const) { + payloadBatches.length = 0 + scalarBatches.length = 0 + const result = await adapter.getJobs({ page, pageSize: 2, sort: [] }) + expect(payloadBatches.length).toBeGreaterThan(0) + expect(payloadBatches.reduce((sum, rows) => sum + rows, 0)).toBe(expected.length) + expect(scalarBatches).toEqual([1]) + expect(result.jobs.map((job) => job.id)).toEqual([...expected]) + expect(result.total).toBe(6) + for (const job of result.jobs) { + expect(job.input).toEqual({ marker: 'input', payload: 'i'.repeat(16_384) }) + expect(job.output).toEqual({ payload: 'o'.repeat(16_384) }) + expect(job.createdAt).toBeInstanceOf(Date) + expect(Object.keys(job).toSorted()).toEqual( + [ + 'id', + 'actionName', + 'groupKey', + 'description', + 'input', + 'output', + 'error', + 'status', + 'timeoutMs', + 'expiresAt', + 'startedAt', + 'finishedAt', + 'createdAt', + 'updatedAt', + 'concurrencyLimit', + 'concurrencyStepLimit', + 'clientId', + 'durationMs', + ].toSorted(), + ) + } + } + } finally { + if (descriptor) Object.defineProperty(driver, method, descriptor) + else delete driver[method] + } + }) + + for (const storage of ['active', 'archive'] as const) { + it(`should preserve listing filters and errors in ${storage} storage (seeded payloads and dates)`, async () => { + const ids = await createListingJobs(3) + const inputs = [ + { + nested: { value: 'MiXeD_needle' }, + object: { 0: 'object-zero' }, + array: ['array-zero'], + optional: null, + number: 2, + tags: ['red', 2, null, { x: 1 }], + undefinedText: 'undefined', + nanText: 'NaN', + }, + { + nested: { value: 'haystack' }, + object: { 0: 'alternate' }, + array: ['array-zero'], + number: 10, + tags: ['green'], + }, + { + nested: { value: 'MiXeDXneedle' }, + object: { 0: 'object-zero' }, + array: ['array-zero'], + optional: 'null', + number: '2', + tags: ['blue'], + }, + ] + for (const [rank, id] of ids.entries()) { + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + await seedListingJob( + id, + storage, + sql` + input = ${JSON.stringify(inputs[rank])}::jsonb, + output = ${JSON.stringify({ text: rank === 1 ? 'running foxes' : 'unrelated' })}::jsonb, + group_key = ${rank === 1 ? 'elsewhere' : 'MiXeD-group'}, + description = ${rank === 1 ? 'haystack' : 'MiXeD-needle'}, + client_id = ${rank === 1 ? 'client-b' : 'client-a'}, + created_at = ${`2026-01-01T00:00:0${rank}.999999Z`}::timestamptz, + started_at = ${`2026-01-01T00:00:0${rank}.999999Z`}::timestamptz, + finished_at = ${`2026-01-01T00:00:0${rank}.999999Z`}::timestamptz, + updated_at = ${`2026-01-01T00:00:00.12${rank + 3}999Z`}::timestamptz`, + ) + } + const cases: [NonNullable, number[]][] = [ + [{ groupKey: 'mixed%' }, [0, 2]], + [{ groupKey: ['mixed-group'] }, []], + [{ groupKey: ['MiXeD-group'] }, [0, 2]], + [{ actionName: 'listing-order' }, [0, 1, 2]], + [{ actionName: 'listing%' }, []], + [{ actionName: [] }, []], + [{ clientId: ['client-a'] }, [0, 2]], + [{ description: 'mixed_ne%' }, [0, 2]], + [{ search: 'run fox' }, [1]], + [{ search: 'needle' }, [0, 2]], + [{ search: ' ' }, [0, 1, 2]], + [{ search: "' OR true --" }, []], + [{ inputFilter: { 'nested.value': 'mixed_needle' } }, [0, 2]], + [{ inputFilter: { 'object.0': 'object-zero' } }, [0, 2]], + [{ inputFilter: { 'array.0': 'array-zero' } }, []], + [{ inputFilter: { optional: null } }, [2]], + [{ inputFilter: { optional: '' } }, [0, 1, 2]], + [{ inputFilter: { number: 2 } }, [0, 2]], + [{ inputFilter: { undefinedText: undefined } }, [0]], + [{ inputFilter: { nanText: NaN } }, [0]], + [{ inputFilter: { tags: ['RED', 'green'] } }, [0, 1]], + [{ inputFilter: { tags: [2, null, { x: 1 }] } }, [0]], + [{ inputFilter: { tags: [] } }, [0, 1, 2]], + [{ inputFilter: { 'object.0': 'object-zero', tags: ['blue'] } }, [2]], + [{ outputFilter: { text: 'running' } }, [1]], + [{ updatedAfter: new Date('2026-01-01T00:00:00.124Z') }, [2]], + [{ status: [] }, []], + ] + for (const field of ['createdAt', 'startedAt', 'finishedAt'] as const) { + cases.push([ + { [field]: [new Date('2026-01-01T00:00:00Z'), new Date('2026-01-01T00:00:01Z')] }, + [0, 1], + ]) + cases.push([{ [field]: new Date('2026-01-01T00:00:01Z') }, [1, 2]]) + } + for (const [filters, expected] of cases) { + const result = await adapter.getJobs({ filters, sort: [], pageSize: 2 }) + expect(result.jobs.map((job) => job.id)).toEqual( + expected.slice(0, 2).map((rank) => ids[rank]!), + ) + expect(result.total).toBe(expected.length) + const empty = await adapter.getJobs({ filters, sort: [], page: 9, pageSize: 2 }) + expect(empty.jobs).toEqual([]) + expect(empty.total).toBe(expected.length) + } + // Wrong-shaped JSON string-array expansion is an error, not a no-match result. + await expect( + adapter.getJobs({ filters: { inputFilter: { number: ['2'] } } }), + ).rejects.toThrow() + await expect(adapter.getJobs({ page: 0 })).rejects.toThrow() + await expect( + adapter.getJobs({ sort: { field: 'id' as 'createdAt', order: 'asc' } }), + ).rejects.toThrow() + }) + } + + it('should retain ORM Date validation before public listing validation (seeded exceptional timestamps)', async () => { + const [id] = await createListingJobs(1) + expectToBeDefined(id) + await seedListingJob( + id, + 'active', + sql`created_at = '5000-01-01T00:00:00+05:45'::timestamptz`, + ) + const valid = await adapter.getJobs({ sort: { field: 'createdAt', order: 'asc' } }) + expect(valid.jobs[0]?.createdAt).toEqual(new Date('5000-01-01T00:00:00+05:45')) + for (const timestamp of ['infinity', '-infinity', '294000-01-01T00:00:00Z']) { + await seedListingJob(id, 'active', sql`created_at = ${timestamp}::timestamptz`) + // The existing detail path also decodes before parsing. No string transform may + // accidentally admit Invalid Date in the new union projection. + await expect(adapter.getJobById(id)).rejects.toThrow() + await expect( + adapter.getJobs({ sort: { field: 'createdAt', order: 'asc' } }), + ).rejects.toThrow() + } + }) + + for (const status of [JOB_STATUS_COMPLETED, JOB_STATUS_FAILED, JOB_STATUS_CANCELLED]) { + it(`should list ${status} jobs after false restoration (public operations)`, async () => { + const jobId = await adapter.createJob({ + queue: 'listing-restoration', + groupKey: 'test-group', + input: { retained: 'input' }, + timeoutMs: 60_000, + checksum: 'abc123', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expectToBeDefined(jobId) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + if (status === JOB_STATUS_COMPLETED) { + expect(await adapter.completeJob({ jobId, output: { retained: 'output' } })).toBe(true) + } else if (status === JOB_STATUS_FAILED) { + expect( + await adapter.failJob({ + jobId, + error: serializeError(new Error('retained failure')), + }), + ).toBe(true) + } else { + expect(await adapter.cancelJob({ jobId })).toBe(true) + } + const before = await adapter.getJobs({ filters: { status } }) + expect(before.total).toBe(1) + expect(before.jobs.map((job) => job.id)).toEqual([jobId]) + const missingStepId = crypto.randomUUID() + expect(await adapter.getJobStepById(missingStepId)).toBeNull() + expect(await adapter.timeTravelJob({ jobId, stepId: missingStepId })).toBe(false) + + const restored = await adapter.getJobs({ filters: { status } }) + expect(restored).toEqual(before) + expect(restored.jobs[0]).toMatchObject({ status, input: { retained: 'input' } }) + if (status === JOB_STATUS_COMPLETED) { + expect(restored.jobs[0]?.output).toEqual({ retained: 'output' }) + } else if (status === JOB_STATUS_FAILED) { + expect(restored.jobs[0]?.error).toMatchObject({ message: 'retained failure' }) + } + for (const filters of [{ status: [JOB_STATUS_CREATED, status] }, {}]) { + const result = await adapter.getJobs({ filters }) + expect(result.jobs.map((job) => job.id)).toEqual([jobId]) + expect(result.total).toBe(1) + } + for (const filters of [ + { status: [JOB_STATUS_CREATED, JOB_STATUS_ACTIVE] }, + { status: [] }, + { status, description: 'not-present' }, + ]) { + const result = await adapter.getJobs({ filters }) + expect(result.jobs).toEqual([]) + expect(result.total).toBe(0) + } + await expect( + adapter.getJobs({ filters: { status: 'unknown' as typeof status } }), + ).rejects.toThrow() + }) + } + it('should get jobs with pagination', async () => { // Create multiple jobs for (let i = 0; i < 5; i++) { @@ -671,13 +1240,20 @@ function runAdapterTests(adapterFactory: AdapterFactory) { }) expectToBeDefined(jobId1) - - // Fetch and complete one job - await adapter.fetch({ batch: 1 }) - await adapter.completeJob({ - jobId: jobId1, - output: { result: 'done' }, - }) + expectToBeDefined(jobId2) + + // Creation times can tie; complete the actual claimed job, not an assumed FIFO winner. + const fetched = await adapter.fetch({ batch: 1 }) + expect(fetched).toHaveLength(1) + const completedId = fetched[0]!.id + expect([jobId1, jobId2]).toContain(completedId) + const createdId = completedId === jobId1 ? jobId2 : jobId1 + expect( + await adapter.completeJob({ + jobId: completedId, + output: { result: 'done' }, + }), + ).toBe(true) // Filter by completed status const completedJobs = await adapter.getJobs({ @@ -686,8 +1262,8 @@ function runAdapterTests(adapterFactory: AdapterFactory) { }, }) - expect(completedJobs.jobs.length).toBe(1) - expect(completedJobs.jobs[0]?.id).toBe(jobId1) + expect(completedJobs.jobs.map((job) => job.id)).toEqual([completedId]) + expect(completedJobs.total).toBe(1) // Filter by created status const createdJobs = await adapter.getJobs({ @@ -696,7 +1272,8 @@ function runAdapterTests(adapterFactory: AdapterFactory) { }, }) - expect(createdJobs.jobs.some((job) => job.id === jobId2)).toBe(true) + expect(createdJobs.jobs.map((job) => job.id)).toEqual([createdId]) + expect(createdJobs.total).toBe(1) }) it('should filter jobs by action name', async () => { diff --git a/packages/duron/test/client.test.ts b/packages/duron/test/client.test.ts index aa1d698..930deb0 100644 --- a/packages/duron/test/client.test.ts +++ b/packages/duron/test/client.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { type SQL, sql } from 'drizzle-orm' import { z } from 'zod' import { defineAction } from '../src/action.js' @@ -520,6 +521,43 @@ function runClientTests(adapterFactory: AdapterFactory) { await client.start() }) + it('should preserve global listing pages and complete projection (seeded creation times)', async () => { + const ids: string[] = [] + for (let index = 0; index < 6; index++) { + ids.push(await client.runAction('testAction', { message: `Listing ${index}` })) + } + expect((await database.fetch({ batch: 6 })).length).toBe(6) + const { db } = database as unknown as { db: { execute: (query: SQL) => Promise } } + for (const [index, id] of ids.entries()) { + const storage = index % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') { + expect( + await database.completeJob({ jobId: id, output: { result: `Saved ${index}` } }), + ).toBe(true) + } + await db.execute(sql`UPDATE duron.${sql.identifier(`jobs_${storage}`)} + SET created_at = ${`2026-01-0${6 - index}T00:00:00Z`}::timestamptz + WHERE id = ${id}`) + } + for (let page = 1; page <= 4; page++) { + const result = await client.getJobs({ + page, + pageSize: 2, + sort: { field: 'createdAt', order: 'desc' }, + }) + expect(result.jobs.map((job) => job.id)).toEqual(ids.slice((page - 1) * 2, page * 2)) + expect(result).toMatchObject({ total: 6, page, pageSize: 2 }) + for (const job of result.jobs) { + const index = ids.indexOf(job.id) + expect(job.input).toEqual({ message: `Listing ${index}` }) + expect(job.output).toEqual(index % 2 === 0 ? null : { result: `Saved ${index}` }) + expect(job.status).toBe(index % 2 === 0 ? JOB_STATUS_ACTIVE : JOB_STATUS_COMPLETED) + expect(job.createdAt).toEqual(new Date(`2026-01-0${6 - index}T00:00:00Z`)) + if (index % 2 !== 0) expect(typeof job.durationMs).toBe('number') + } + } + }) + it('should get jobs with pagination', async () => { // Create multiple jobs for (let i = 0; i < 5; i++) { diff --git a/packages/duron/test/server.test.ts b/packages/duron/test/server.test.ts index 24bc680..f7948d2 100644 --- a/packages/duron/test/server.test.ts +++ b/packages/duron/test/server.test.ts @@ -1,11 +1,13 @@ import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { type SQL, sql } from 'drizzle-orm' import { z } from 'zod/mini' import { defineAction } from '../src/action.js' import { ActionStatsSchema, JobSchema, JobStepSchema } from '../src/adapters/schemas.js' import { Client } from '../src/client.js' import { + JOB_STATUS_ACTIVE, JOB_STATUS_CANCELLED, JOB_STATUS_COMPLETED, JOB_STATUS_CREATED, @@ -21,7 +23,7 @@ import { RetryJobResponseSchema, } from '../src/server.js' -import { type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' +import { type Adapter, type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' import { expectToBeDefined } from './asserts.js' // Helper schemas for JSON responses (dates come as strings in JSON) @@ -78,6 +80,7 @@ function runServerTests(adapterFactory: AdapterFactory) { describe(`Server Tests with ${adapterFactory.name}`, () => { let client: Client let server: ReturnType + let database: Adapter let deleteDb: () => Promise const testAction = defineAction()({ @@ -121,6 +124,7 @@ function runServerTests(adapterFactory: AdapterFactory) { async () => { const adapterInstance = await adapterFactory.create({}) deleteDb = adapterInstance.deleteDb + database = adapterInstance.adapter client = new Client({ database: adapterInstance.adapter, @@ -269,6 +273,44 @@ function runServerTests(adapterFactory: AdapterFactory) { }) describe('GET /api/jobs', () => { + it('should serve global listing pages with output and serialized dates (seeded creation times)', async () => { + const ids: string[] = [] + for (let index = 0; index < 6; index++) { + ids.push(await client.runAction('testAction', { message: `Listing ${index}` })) + } + expect((await database.fetch({ batch: 6 })).length).toBe(6) + const { db } = database as unknown as { db: { execute: (query: SQL) => Promise } } + for (const [index, id] of ids.entries()) { + const storage = index % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') { + expect( + await database.completeJob({ jobId: id, output: { result: `Saved ${index}` } }), + ).toBe(true) + } + await db.execute(sql`UPDATE duron.${sql.identifier(`jobs_${storage}`)} + SET created_at = ${`2026-01-0${6 - index}T00:00:00Z`}::timestamptz + WHERE id = ${id}`) + } + for (let page = 1; page <= 4; page++) { + const response = await server.handle( + new Request(`http://localhost/api/jobs?page=${page}&pageSize=2&sort=createdAt:desc`), + ) + expect(response.status).toBe(200) + const result = GetJobsResponseParsedSchema.parse(await response.json()) + expect(result.jobs.map((job) => job.id)).toEqual(ids.slice((page - 1) * 2, page * 2)) + expect(result).toMatchObject({ total: 6, page, pageSize: 2 }) + for (const job of result.jobs) { + const index = ids.indexOf(job.id) + expect(job.input).toEqual({ message: `Listing ${index}` }) + expect(job.output).toEqual(index % 2 === 0 ? null : { result: `Saved ${index}` }) + expect(job.status).toBe(index % 2 === 0 ? JOB_STATUS_ACTIVE : JOB_STATUS_COMPLETED) + expect(job.createdAt).toBe(`2026-01-0${6 - index}T00:00:00.000Z`) + if (index % 2 !== 0) expect(typeof job.durationMs).toBe('number') + expect(job).not.toHaveProperty('steps') + } + } + }) + it('should get jobs with pagination', async () => { // Create multiple jobs for (let i = 0; i < 5; i++) { From 2c9584f4c6584085fbb2dd5762e9a563bee6f15d Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 7 Nov 2026 11:43:45 -0300 Subject: [PATCH 004/100] Preserve elapsed retained-step timestamps across DST Apply the SQL-07 UTC-intermediate correction to time-travel shifts so all retained endpoints receive the same elapsed delta from transaction time. Preserve archive Date conversion limits, null finishes, graph guards and retained metadata. Add native-precision UTC, New York and Lord Howe regressions for both storage paths and engines, plus public override dispatch controls. Isolate the create-step fixture counter per test after the required both-engine gate exposed baseline cross-suite leakage; keep its expectations unchanged. Verified root typecheck, lint, tests and formatting, core build, scoped both-engine suites and Client Query Methods. Independent Standards and Spec reviews cover the pinned-base diff. No Node runtime verification or broader recovery-suite pass is claimed. --- packages/duron/src/adapters/postgres/base.ts | 9 +- packages/duron/test/create-step.test.ts | 9 +- packages/duron/test/time-travel.test.ts | 241 +++++++++++++++++++ 3 files changed, 252 insertions(+), 7 deletions(-) diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index a626fd0..76dc30a 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -725,10 +725,11 @@ export abstract class PostgresBaseAdapter< -- All parallel siblings and their descendants SELECT id FROM parallel_descendants ), - -- Calculate time offset: shift preserved steps to start from "now" + -- One elapsed delta from the transaction-frozen SQL time and earliest retained start. + -- UTC intermediates avoid calendar-day/DST shifts; prior Date restoration may lose fractions. time_offset AS ( SELECT - now() - MIN(s.started_at) AS offset_interval + (now() AT TIME ZONE 'UTC') - (MIN(s.started_at) AT TIME ZONE 'UTC') AS offset_interval FROM ${this.tables.jobStepsActiveTable} s WHERE s.id IN (SELECT id FROM steps_to_keep) ), @@ -736,10 +737,10 @@ export abstract class PostgresBaseAdapter< shift_preserved_times AS ( UPDATE ${this.tables.jobStepsActiveTable} SET - started_at = started_at + (SELECT offset_interval FROM time_offset), + started_at = ((started_at AT TIME ZONE 'UTC') + (SELECT offset_interval FROM time_offset)) AT TIME ZONE 'UTC', finished_at = CASE WHEN finished_at IS NOT NULL - THEN finished_at + (SELECT offset_interval FROM time_offset) + THEN ((finished_at AT TIME ZONE 'UTC') + (SELECT offset_interval FROM time_offset)) AT TIME ZONE 'UTC' ELSE NULL END, updated_at = now() diff --git a/packages/duron/test/create-step.test.ts b/packages/duron/test/create-step.test.ts index 08b1948..2055885 100644 --- a/packages/duron/test/create-step.test.ts +++ b/packages/duron/test/create-step.test.ts @@ -584,12 +584,15 @@ function runCreateStepTests(adapterFactory: AdapterFactory) { > let database: Adapter let deleteDb: () => Promise + let testVariables: typeof variables beforeEach( async () => { const adapterInstance = await adapterFactory.create({}) database = adapterInstance.adapter deleteDb = adapterInstance.deleteDb + // Retry steps mutate the counter; do not share it across tests or engines. + testVariables = { ...variables, counter: 0 } client = new Client({ database, @@ -609,7 +612,7 @@ function runCreateStepTests(adapterFactory: AdapterFactory) { sameNameDifferentParentsAction, fullContextNameAction, }, - variables, + variables: testVariables, syncPattern: false, recoverJobsOnStart: false, logger: 'error', @@ -812,7 +815,7 @@ function runCreateStepTests(adapterFactory: AdapterFactory) { it('should retry step definition before failing action', async () => { // Reset the counter - variables.counter = 0 + testVariables.counter = 0 const jobId = await client.runAction('failingWithRetryAction', { message: 'retry test', @@ -835,7 +838,7 @@ function runCreateStepTests(adapterFactory: AdapterFactory) { // The step should have been called 4 times (1 initial + 3 retries) // Note: counter is reset in the action handler before calling run // But the step handler increments it each time - expect(variables.counter).toBe(4) + expect(testVariables.counter).toBe(4) // Verify the step also failed const stepsResult = await client.getJobSteps({ jobId }) diff --git a/packages/duron/test/time-travel.test.ts b/packages/duron/test/time-travel.test.ts index 462fb97..5e5e177 100644 --- a/packages/duron/test/time-travel.test.ts +++ b/packages/duron/test/time-travel.test.ts @@ -4,6 +4,7 @@ import { type SQL, sql } from 'drizzle-orm' import { z } from 'zod/mini' import { defineAction } from '../src/action.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' import { Client } from '../src/client.js' import { JOB_STATUS_ACTIVE, @@ -23,6 +24,7 @@ import { postgresFactory, } from './adapters.js' import { expectToBeDefined } from './asserts.js' +import { getPostgresConnection } from './docker.js' // ============================================================================= // Test Actions for Time Travel @@ -289,6 +291,18 @@ function runTests(name: string, factory: AdapterFactory) { // ========================================================================= describe('Basic Time Travel', () => { + it.each([false, true])('preserves custom Adapter time-travel result %s', async (result) => { + const jobId = crypto.randomUUID() + const stepId = crypto.randomUUID() + // The Adapter is a public extension boundary. Client must not bypass a + // custom implementation or reinterpret its result as a built-in SQL operation. + adapterInstance.adapter.timeTravelJob = async (options) => { + expect(options).toEqual({ jobId, stepId }) + return result + } + expect(await client.timeTravelJob(jobId, stepId)).toBe(result) + }) + it('should time travel from a root step in completed job', async () => { // Run a successful job const jobId = await client.runAction('linearAction', {}) @@ -796,14 +810,241 @@ function runIsolationTests(factory: AdapterFactory) { }) } +// Seeded/native precision seam: Date results cannot expose the sub-millisecond +// differences under test. Keep PostgreSQL on one query session for SET/reset; +// provisioning and normal database deletion use the existing factory helper. +async function createElapsedFixture(factory: AdapterFactory): Promise { + if (factory.name === 'pglite') return factory.create() + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const connection = new URL(CONNECTION_URL) + return { + adapter: new PostgresAdapter({ + connection: { + host: connection.hostname, + port: Number(connection.port), + database: connection.pathname.slice(1), + username: connection.username, + password: connection.password, + max: 1, + }, + }), + connectionUrl: CONNECTION_URL, + deleteDb, + } +} + +async function elapsedSql(adapter: Adapter, query: SQL): Promise { + const { db } = adapter as unknown as { + db: { execute: (query: SQL) => Promise } + } + const result = await db.execute(query) + return 'rows' in result ? result.rows : result +} + +type RetainedTimes = { + id: string + start: string + finish: string | null + created: string + expires: string | null + history: unknown + status: string + output: unknown + updated: string +} + +function runElapsedTests(factory: AdapterFactory) { + describe(`Time Travel Elapsed Shift (${factory.name}; seeded/native precision)`, () => { + const transitions = [ + { + zone: 'UTC', + start: '2024-03-10 06:30:00.123456+00', + finish: '2024-03-10 07:30:00.654321+00', + }, + { + zone: 'UTC', + start: '2024-11-03 05:30:00.123456+00', + finish: '2024-11-03 06:30:00.654321+00', + }, + { + zone: 'America/New_York', + start: '2024-03-10 06:30:00.123456+00', + finish: '2024-03-10 07:30:00.654321+00', + }, + { + zone: 'America/New_York', + start: '2024-11-03 05:30:00.123456+00', + finish: '2024-11-03 06:30:00.654321+00', + }, + { + zone: 'Australia/Lord_Howe', + start: '2024-10-05 15:00:00.123456+00', + finish: '2024-10-05 16:00:00.654321+00', + }, + { + zone: 'Australia/Lord_Howe', + start: '2024-04-06 14:30:00.123456+00', + finish: '2024-04-06 15:30:00.654321+00', + }, + ] + it.each( + transitions.flatMap((transition) => [ + { ...transition, storage: 'active' }, + { ...transition, storage: 'archive' }, + ]), + )( + 'preserves elapsed endpoints in $zone from $start ($storage)', + async ({ zone, start, finish, storage }) => { + const { adapter, deleteDb } = await createElapsedFixture(factory) + let originalZone: string | undefined + try { + adapter.setId(crypto.randomUUID()) + const jobId = await createActiveJob(adapter, 'elapsed-shift') + const retainedId = await createCompletedStep(adapter, jobId, 'retained', null, true) + const unfinished = await adapter.createOrRecoverJobStep({ + jobId, + name: 'unfinished-descendant', + parentStepId: retainedId, + timeoutMs: 60000, + retriesLimit: 3, + }) + expectToBeDefined(unfinished) + const targetId = await createCompletedStep(adapter, jobId, 'target') + expect(await adapter.completeJob({ jobId, output: { saved: 'elapsed-job' } })).toBe(true) + if (storage === 'active') { + // Public false restoration supplies an eligible terminal graph in active storage. + expect(await adapter.timeTravelJob({ jobId, stepId: crypto.randomUUID() })).toBe(false) + } + expect(await getJobStorage(adapter, jobId)).toEqual({ + active: storage === 'active', + archived: storage === 'archive', + }) + const table = sql.identifier(`job_steps_${storage}`) + const [session] = await elapsedSql<{ zone: string; pid: number }>( + adapter, + sql` + SELECT current_setting('TimeZone') AS zone, pg_backend_pid() AS pid + `, + ) + originalZone = session!.zone + await elapsedSql(adapter, sql`SELECT set_config('TimeZone', ${zone}, false)`) + await elapsedSql( + adapter, + sql` + UPDATE duron.${table} SET + started_at = CASE WHEN id = ${retainedId} THEN ${start}::timestamptz + ELSE ${finish}::timestamptz + interval '1.580246 seconds' END, + finished_at = CASE WHEN id = ${retainedId} THEN ${finish}::timestamptz ELSE NULL END, + history_failed_attempts = '{"opaque":"retained-history"}'::jsonb + WHERE id IN (${retainedId}, ${unfinished!.id}) + `, + ) + const readTimes = ( + source: ReturnType, + afterDateConversion = false, + ) => { + // Archive restoration passes through Date. Compare the shift against that + // millisecond-normalized input, not an unsupported lossless-restoration promise. + const timestamp = (column: string) => + afterDateConversion + ? sql`date_trunc('milliseconds', ${sql.identifier(column)})` + : sql`${sql.identifier(column)}` + return elapsedSql( + adapter, + sql` + SELECT id, (extract(epoch FROM ${timestamp('started_at')}) * 1000000)::bigint::text AS start, + (extract(epoch FROM ${timestamp('finished_at')}) * 1000000)::bigint::text AS finish, + ${timestamp('created_at')}::text AS created, ${timestamp('expires_at')}::text AS expires, + history_failed_attempts AS history, status, output, + (extract(epoch FROM updated_at) * 1000000)::bigint::text AS updated + FROM duron.${source} + WHERE id IN (${retainedId}, ${unfinished!.id}) ORDER BY id + `, + ) + } + const before = await readTimes(table, storage === 'archive') + expect(before).toHaveLength(2) + expect(await adapter.timeTravelJob({ jobId, stepId: targetId })).toBe(true) + const after = await readTimes(sql.identifier('job_steps_active')) + expect(after).toHaveLength(2) + const retained = after.find((step) => step.id === retainedId)! + // Independent literals: one elapsed hour plus the original fractional + // difference (or its Date-normalized value after archive restoration). + expect(BigInt(retained.finish!) - BigInt(retained.start)).toBe( + storage === 'archive' ? 3600531000n : 3600530865n, + ) + const [reference] = await elapsedSql<{ time: string; zone: string; pid: number }>( + adapter, + sql` + SELECT (extract(epoch FROM started_at) * 1000000)::bigint::text AS time, + current_setting('TimeZone') AS zone, pg_backend_pid() AS pid + FROM duron.job_steps_active WHERE id = ${targetId} + `, + ) + expect(reference!.zone).toBe(zone) + expect(reference!.pid).toBe(session!.pid) + expect(retained.start).toBe(reference!.time) + const earliest = BigInt(before.find((step) => step.id === retainedId)!.start) + for (const [index, step] of after.entries()) { + const previous = before[index]! + expect(step.id).toBe(previous.id) + expect(BigInt(step.start) - BigInt(reference!.time)).toBe( + BigInt(previous.start) - earliest, + ) + if (previous.finish === null) expect(step.finish).toBeNull() + else + expect(BigInt(step.finish!) - BigInt(reference!.time)).toBe( + BigInt(previous.finish) - earliest, + ) + expect(step).toMatchObject({ + created: previous.created, + expires: previous.expires, + history: previous.history, + status: previous.status, + output: previous.output, + updated: reference!.time, + }) + } + expect(await adapter.getJobById(jobId)).toMatchObject({ status: JOB_STATUS_CREATED }) + expect(await adapter.getJobStepById(targetId)).toMatchObject({ + status: STEP_STATUS_ACTIVE, + output: null, + finishedAt: null, + }) + } finally { + try { + if (originalZone !== undefined) { + const [restored] = await elapsedSql<{ zone: string }>( + adapter, + sql` + SELECT set_config('TimeZone', ${originalZone}, false) AS zone + `, + ) + expect(restored!.zone).toBe(originalZone) + } + } finally { + await adapter.stop() + await deleteDb() + } + } + }, + ) + }) +} + // ============================================================================= // Run Tests for Each Adapter // ============================================================================= runTests('pglite', pgliteFactory) runIsolationTests(pgliteFactory) +runElapsedTests(pgliteFactory) // oxlint-disable-next-line useLiteralKeys if (process.env['POSTGRES_TEST'] === 'true') { runTests('postgres', postgresFactory) runIsolationTests(postgresFactory) + runElapsedTests(postgresFactory) } From 07009d630ae06b93ed7ef8d6cef89d3c769e9741 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 7 Nov 2026 16:32:22 -0300 Subject: [PATCH 005/100] Share lifecycle cleanup and use SQL heartbeat time Coordinate Client and Adapter shutdown through one internal lifecycle ledger. Track actual startup, operations, callbacks, handlers and steps through four shared phase budgets. Preserve cleanup errors and retry only safe unfinished resource obligations without reopening admission or releasing liveness early. Use SQL now() for both heartbeat upsert branches. Correct initial/periodic heartbeat error handling, PostgreSQL close timeout, and owned PGLite listener setup and cleanup. Omit forbidden late hints without changing mutation success. Add native lifecycle, clock, failure, retry and handler-entry regressions. Correct two approved recovery fixtures after exact-base attribution, and document implemented shutdown, clock limits and fetch-driven recovery. Verification: root typecheck, lint, formatting and core build passed. Root tests: 273 passed. Both-engine gate: 505 passed. Independent Standards and Spec reviews have no outstanding required findings. Node compatibility was reviewed at source/build level only; Node runtime remains untested. --- packages/docs/content/docs/multi-worker.mdx | 41 +- packages/duron/src/action-job.ts | 19 +- packages/duron/src/action-manager.ts | 5 +- packages/duron/src/adapters/adapter.ts | 713 +++++++------ packages/duron/src/adapters/postgres/base.ts | 196 +++- .../duron/src/adapters/postgres/pglite.ts | 90 +- .../duron/src/adapters/postgres/postgres.ts | 17 +- packages/duron/src/client.ts | 978 +++++++++--------- packages/duron/src/lifecycle.ts | 379 +++++++ packages/duron/src/step-manager.ts | 34 +- packages/duron/test/client.test.ts | 12 +- packages/duron/test/heartbeat-clock.test.ts | 239 +++++ .../duron/test/lifecycle-background.test.ts | 150 +++ packages/duron/test/lifecycle-budgets.test.ts | 172 +++ .../duron/test/lifecycle-close-retry.test.ts | 112 ++ packages/duron/test/lifecycle-errors.test.ts | 168 +++ .../test/lifecycle-handler-entry.test.ts | 125 +++ .../duron/test/lifecycle-listeners.test.ts | 282 +++++ packages/duron/test/lifecycle-sql.test.ts | 206 ++++ packages/duron/test/lifecycle-startup.test.ts | 156 +++ packages/duron/test/lifecycle.test.ts | 974 +++++++++++++++++ packages/duron/test/recover.test.ts | 35 +- 22 files changed, 4209 insertions(+), 894 deletions(-) create mode 100644 packages/duron/src/lifecycle.ts create mode 100644 packages/duron/test/heartbeat-clock.test.ts create mode 100644 packages/duron/test/lifecycle-background.test.ts create mode 100644 packages/duron/test/lifecycle-budgets.test.ts create mode 100644 packages/duron/test/lifecycle-close-retry.test.ts create mode 100644 packages/duron/test/lifecycle-errors.test.ts create mode 100644 packages/duron/test/lifecycle-handler-entry.test.ts create mode 100644 packages/duron/test/lifecycle-listeners.test.ts create mode 100644 packages/duron/test/lifecycle-sql.test.ts create mode 100644 packages/duron/test/lifecycle-startup.test.ts create mode 100644 packages/duron/test/lifecycle.test.ts diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 1ccecc4..228331d 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -224,15 +224,44 @@ process.on('SIGINT', async () => { Duron uses heartbeat-based liveness detection for crashed-instance recovery: -1. **Heartbeat**: Each instance periodically upserts a liveness record in the `clients` table (every `heartbeatInterval`) -2. **Periodic recovery**: Recovery runs automatically based on `recoverJobsInterval` (default: every 60 seconds) -3. **On startup**: Each worker checks for stuck jobs (jobs marked as active but owned by dead instances) -4. **Dead detection**: A client is considered dead if its `last_seen_at` is older than `heartbeatTimeout` +1. **Heartbeat**: Each instance periodically upserts a liveness record in the `clients` table (every `heartbeatInterval`). PostgreSQL and PGLite use SQL `now()` for both the first write and subsequent updates. +2. **Fetch-driven recovery**: A worker with configured actions checks recovery from `fetch()` after `recoverJobsInterval` elapses (default: 60 seconds). This interval does not create an independent recovery timer. Without a fetch, elapsed time alone does not trigger recovery. Setting `recoverJobsInterval` to `0` disables this fetch-triggered check. +3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. +4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery includes the current client ID regardless of its heartbeat and does not newly include null owners. 5. **Recovery behavior**: - **Expired jobs** (exceeded timeout): Archived as failed with error information - **Stuck jobs** (not expired): Reset to `created` status and can be picked up by any worker -On graceful shutdown, each instance deletes its liveness row so other instances can recover its jobs immediately. +After a successful drain, shutdown deletes the instance's liveness row before closing its database resources. Other instances can then discover eligible jobs on their next recovery pass without waiting for heartbeat staleness. If admitted work does not drain, Duron withholds that deletion and reports incomplete shutdown. A failed deletion is not reported as a successful release; existing staleness recovery still applies to a retained row. + +### Heartbeat clock and failure limits + +The initial heartbeat must succeed before Client startup can succeed. Startup failure triggers automatic cleanup. A periodic heartbeat failure is logged through the configured logger, is nonfatal, and is retried at the normal heartbeat cadence only while running. + +SQL `now()` is transaction-start time, not continuously advancing wall time or commit time. Using it removes the application-clock offset from new heartbeat writes, but does not provide an execution lease or prevent duplicate effects. Delayed or failed writes, event-loop stalls and SQL clock movement can still affect recovery. Native SQL precision and the strict freshness comparison are preserved. Existing rows are not migrated; an ordinary heartbeat can replace a legacy future timestamp with an earlier SQL timestamp. + +This change does not normalize other timestamps. Job complete/fail/cancel timestamps and relative prune cutoffs remain application-sourced; SQL claim, step and recovery timestamps retain their existing sources and distinct guards. Recorded timestamps need not be monotonically ordered under clock offset or movement. + +## Lifecycle and Shutdown + +`client.stop()` closes admission immediately: it cancels scheduled heartbeat/pull/prune timers, disables new event-driven work, settles pending waits with `null`, and requests action cancellation. It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler. + +Client and Adapter share four internal shutdown budgets. Each budget applies to the whole phase, not separately to nested calls or individual resources: + +| Phase | Budget | Work | +| ------------------- | --------- | ----------------------------------------------------------------------- | +| Startup settlement | 5 seconds | Observe already-issued initialization; skip remaining stages where safe | +| Admitted-work drain | 5 seconds | Observe actual ordinary operations, callbacks and action/step work | +| Database cleanup | 5 seconds | Attempt independent listener and liveness cleanup while SQL is usable | +| Owned close | 5 seconds | Close owned query/listener clients or the PGLite engine | + +Empty phases are skipped. Later cleanup phases still receive their opportunity after an earlier failure or timeout. The planned asynchronous wait is approximately twenty seconds when all phases are needed, not a hard elapsed-time or natural-process-exit guarantee. + +After the drain boundary, no new ordinary SQL may begin. Already-issued SQL is not assumed cancelled. A successful mutation that reaches notification submission too late keeps its successful result; the forbidden hint is omitted and logged as delivery unconfirmed. User JavaScript and external side effects are not forcibly terminated or fenced by these in-process gates. + +A timeout or cleanup failure rejects `stop()`. A sole error is preserved; multiple failures use `AggregateError`. Log and inspect the rejection rather than treating it as proof that resources closed or work stopped. Concurrent stop callers share cleanup. A later stop joins pending resource operations or retries only safe unfinished cleanup; it does not replay completed application work or allocate a replacement connection. Failed or withheld liveness deletion cannot be repaired after SQL has closed. A failed explicit unsubscribe remains an error for that attempt even if owned close subsequently releases its resources. + +Failed startup is cleanup-only: Duron automatically attempts cleanup and does not restart that instance. Start calls after the terminal gate return `false`; use a fresh instance for another startup attempt. A superseded pending start cannot report success. Repeated successful stop returns `true` without repeating completed cleanup. ## Best Practices @@ -269,7 +298,7 @@ Keep `heartbeatTimeout` at least 3x `heartbeatInterval` to tolerate occasional m - **Separate dashboard and workers**: Run dashboard/server in a separate process to avoid resource competition - **Monitor worker health**: Use process managers (PM2, systemd, etc.) to restart failed workers -- **Graceful shutdown**: Always handle `SIGINT`/`SIGTERM` to allow jobs to complete +- **Graceful shutdown**: Handle `SIGINT`/`SIGTERM`, await `client.stop()`, and report cleanup failures. Cancellation is cooperative; decide process-exit policy separately from resource-release evidence. ### Scaling diff --git a/packages/duron/src/action-job.ts b/packages/duron/src/action-job.ts index e722969..8174e88 100644 --- a/packages/duron/src/action-job.ts +++ b/packages/duron/src/action-job.ts @@ -17,6 +17,7 @@ import { isTimeoutError, serializeError, } from './errors.js' +import { lifecycleFor } from './lifecycle.js' import { validateSchema } from './standard-schema.js' import { StepManager } from './step-manager.js' import waitForAbort from './utils/wait-for-abort.js' @@ -127,6 +128,11 @@ export class ActionJob> { jobLogger, ) + if (!lifecycleFor(this.#database).accepting) { + throw new ActionCancelError(this.#action.name, this.#job.id) + } + this.#abortController.signal.throwIfAborted() + this.#timeoutId = setTimeout(() => { const timeoutError = new ActionTimeoutError( this.#action.name, @@ -146,8 +152,17 @@ export class ActionJob> { const spanContext = trace.setSpan(context.active(), this.#jobSpan) await Promise.race([ - context - .with(spanContext, () => this.#action.handler(ctx)) + lifecycleFor(this.#database) + .run(() => + context.with(spanContext, () => { + // The tracked invocation is deferred. Stop can win after preparation. + if (!lifecycleFor(this.#database).accepting) { + throw new ActionCancelError(this.#action.name, this.#job.id) + } + this.#abortController.signal.throwIfAborted() + return this.#action.handler(ctx) + }), + ) .then((res) => { if (res !== undefined) { result = res diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index ef8c0c5..d851737 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -5,6 +5,7 @@ import type { Logger } from 'pino' import { ActionJob } from './action-job.js' import type { Action } from './action.js' import type { Adapter, Job } from './adapters/adapter.js' +import { lifecycleFor } from './lifecycle.js' export interface ActionManagerOptions> { action: TAction @@ -51,11 +52,11 @@ export class ActionManager> { // Create fastq queue with action concurrency limit this.#queue = fastq.promise(async (job: Job) => { - if (this.#stopped) { + if (this.#stopped || !lifecycleFor(this.#database).accepting) { return } - await this.#executeJob(job) + await lifecycleFor(this.#database).run(() => this.#executeJob(job)) }, this.#concurrencyLimit) } diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index b869f55..7805e6d 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -9,6 +9,7 @@ import { JOB_STATUS_FAILED, type JobStatus, } from '../constants.js' +import { lifecycleFor } from '../lifecycle.js' import type { ArchiveStats, @@ -138,82 +139,39 @@ export interface AdapterEvents { */ export abstract class Adapter extends EventEmitter { #id!: string - #started: boolean = false - #stopped: boolean = false - #starting: Promise | null = null - #stopping: Promise | null = null + #closed = false + #lifecycle = lifecycleFor(this) #logger: Logger | null = null - // ============================================================================ - // Lifecycle Methods - // ============================================================================ - - /** - * Start the adapter. - * Performs any necessary initialization, such as running migrations or setting up listeners. - * - * @returns Promise resolving to `true` if started successfully, `false` otherwise - */ - async start() { - try { - if (!this.#id) { - throw new Error('Adapter ID is not set') - } - - if (this.#stopping || this.#stopped) { - return false - } - - if (this.#started) { - return true - } - - if (this.#starting) { - return this.#starting - } + constructor() { + super() + this.#lifecycle.obligation( + 'adapter database cleanup', + 'database cleanup', + () => this._stop(), + () => this._canCleanup(), + ) + this.#lifecycle.obligation('adapter owned resources', 'owned close', async () => { + await this._close() + this.#closed = true + }) + } - this.#starting = (async () => { + /** Start once; failed startup automatically enters cleanup-only state. */ + async start(): Promise { + return this.#lifecycle.start( + this, + async () => { + if (!this.#id) throw new Error('Adapter ID is not set') await this._start() - this.#started = true - this.#starting = null - return true - })() - - return this.#starting - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.start()') - throw error - } + }, + () => this.stop(), + ) } - /** - * Stop the adapter. - * Performs cleanup, such as closing database connections. - * - * @returns Promise resolving to `true` if stopped successfully, `false` otherwise - */ - async stop() { - try { - if (this.#stopped) { - return true - } - - if (this.#stopping) { - return this.#stopping - } - - this.#stopping = (async () => { - await this._stop() - this.#stopped = true - this.#stopping = null - return true - })() - - return this.#stopping - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.stop()') - throw error - } + /** Join the shared four-phase cleanup attempt. Never reopen admission. */ + async stop(): Promise { + return this.#lifecycle.stop() } // ============================================================================ @@ -277,19 +235,23 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to the job ID, or `null` if creation failed */ async createJob(options: CreateJobOptions): Promise { - try { - await this.start() - const parsedOptions = CreateJobOptionsSchema.parse(options) - const result = await this._createJob(parsedOptions) - const jobId = JobIdResultSchema.parse(result) - if (jobId !== null) { - await this._notify('job-available', { jobId }) + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = CreateJobOptionsSchema.parse(options) + const result = await this._createJob(parsedOptions) + const jobId = JobIdResultSchema.parse(result) + if (jobId !== null) { + await this._notify('job-available', { jobId }) + } + return jobId + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.createJob()') + throw error } - return jobId - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.createJob()') - throw error - } + }) } /** @@ -298,23 +260,27 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if completed, `false` otherwise */ async completeJob(options: CompleteJobOptions): Promise { - try { - await this.start() - const parsedOptions = CompleteJobOptionsSchema.parse(options) - const result = await this._completeJob(parsedOptions) - const success = BooleanResultSchema.parse(result) - if (success) { - await this._notify('job-status-changed', { - jobId: parsedOptions.jobId, - status: JOB_STATUS_COMPLETED, - clientId: this.id, - }) + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = CompleteJobOptionsSchema.parse(options) + const result = await this._completeJob(parsedOptions) + const success = BooleanResultSchema.parse(result) + if (success) { + await this._notify('job-status-changed', { + jobId: parsedOptions.jobId, + status: JOB_STATUS_COMPLETED, + clientId: this.id, + }) + } + return success + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.completeJob()') + throw error } - return success - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.completeJob()') - throw error - } + }) } /** @@ -323,23 +289,27 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if failed, `false` otherwise */ async failJob(options: FailJobOptions): Promise { - try { - await this.start() - const parsedOptions = FailJobOptionsSchema.parse(options) - const result = await this._failJob(parsedOptions) - const success = BooleanResultSchema.parse(result) - if (success) { - await this._notify('job-status-changed', { - jobId: parsedOptions.jobId, - status: JOB_STATUS_FAILED, - clientId: this.id, - }) + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = FailJobOptionsSchema.parse(options) + const result = await this._failJob(parsedOptions) + const success = BooleanResultSchema.parse(result) + if (success) { + await this._notify('job-status-changed', { + jobId: parsedOptions.jobId, + status: JOB_STATUS_FAILED, + clientId: this.id, + }) + } + return success + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.failJob()') + throw error } - return success - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.failJob()') - throw error - } + }) } /** @@ -348,23 +318,27 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if cancelled, `false` otherwise */ async cancelJob(options: CancelJobOptions): Promise { - try { - await this.start() - const parsedOptions = CancelJobOptionsSchema.parse(options) - const result = await this._cancelJob(parsedOptions) - const success = BooleanResultSchema.parse(result) - if (success) { - await this._notify('job-status-changed', { - jobId: parsedOptions.jobId, - status: JOB_STATUS_CANCELLED, - clientId: this.id, - }) + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = CancelJobOptionsSchema.parse(options) + const result = await this._cancelJob(parsedOptions) + const success = BooleanResultSchema.parse(result) + if (success) { + await this._notify('job-status-changed', { + jobId: parsedOptions.jobId, + status: JOB_STATUS_CANCELLED, + clientId: this.id, + }) + } + return success + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.cancelJob()') + throw error } - return success - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.cancelJob()') - throw error - } + }) } /** @@ -373,19 +347,23 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to the job ID, or `null` if creation failed */ async retryJob(options: RetryJobOptions): Promise { - try { - await this.start() - const parsedOptions = RetryJobOptionsSchema.parse(options) - const result = await this._retryJob(parsedOptions) - const jobId = JobIdResultSchema.parse(result) - if (jobId !== null) { - await this._notify('job-available', { jobId }) + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = RetryJobOptionsSchema.parse(options) + const result = await this._retryJob(parsedOptions) + const jobId = JobIdResultSchema.parse(result) + if (jobId !== null) { + await this._notify('job-available', { jobId }) + } + return jobId + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.retryJob()') + throw error } - return jobId - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.retryJob()') - throw error - } + }) } /** @@ -397,19 +375,23 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if time travel succeeded, `false` otherwise */ async timeTravelJob(options: TimeTravelJobOptions): Promise { - try { - await this.start() - const parsedOptions = TimeTravelJobOptionsSchema.parse(options) - const result = await this._timeTravelJob(parsedOptions) - const success = BooleanResultSchema.parse(result) - if (success) { - await this._notify('job-available', { jobId: parsedOptions.jobId }) + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = TimeTravelJobOptionsSchema.parse(options) + const result = await this._timeTravelJob(parsedOptions) + const success = BooleanResultSchema.parse(result) + if (success) { + await this._notify('job-available', { jobId: parsedOptions.jobId }) + } + return success + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.timeTravelJob()') + throw error } - return success - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.timeTravelJob()') - throw error - } + }) } /** @@ -419,15 +401,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if deleted, `false` otherwise */ async deleteJob(options: DeleteJobOptions): Promise { - try { - await this.start() - const parsedOptions = DeleteJobOptionsSchema.parse(options) - const result = await this._deleteJob(parsedOptions) - return BooleanResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.deleteJob()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = DeleteJobOptionsSchema.parse(options) + const result = await this._deleteJob(parsedOptions) + return BooleanResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.deleteJob()') + throw error + } + }) } /** @@ -437,15 +423,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to the number of jobs deleted */ async deleteJobs(options?: DeleteJobsOptions): Promise { - try { - await this.start() - const parsedOptions = options ? DeleteJobsOptionsSchema.parse(options) : undefined - const result = await this._deleteJobs(parsedOptions) - return NumberResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.deleteJobs()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = options ? DeleteJobsOptionsSchema.parse(options) : undefined + const result = await this._deleteJobs(parsedOptions) + return NumberResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.deleteJobs()') + throw error + } + }) } /** @@ -454,15 +444,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to an array of fetched jobs */ async fetch(options: FetchOptions): Promise { - try { - await this.start() - const parsedOptions = FetchOptionsSchema.parse(options) - const result = await this._fetch(parsedOptions) - return JobsArrayResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.fetch()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = FetchOptionsSchema.parse(options) + const result = await this._fetch(parsedOptions) + return JobsArrayResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.fetch()') + throw error + } + }) } /** @@ -471,15 +465,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to the number of jobs recovered */ async recoverJobs(options: RecoverJobsOptions): Promise { - try { - await this.start() - const parsedOptions = RecoverJobsOptionsSchema.parse(options) - const result = await this._recoverJobs(parsedOptions) - return NumberResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.recoverJobs()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = RecoverJobsOptionsSchema.parse(options) + const result = await this._recoverJobs(parsedOptions) + return NumberResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.recoverJobs()') + throw error + } + }) } /** @@ -491,13 +489,17 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `void` */ async heartbeat(): Promise { - try { - await this.start() - await this._heartbeat() - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.heartbeat()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + await this._heartbeat() + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.heartbeat()') + throw error + } + }) } // ============================================================================ @@ -512,15 +514,19 @@ export abstract class Adapter extends EventEmitter { async createOrRecoverJobStep( options: CreateOrRecoverJobStepOptions, ): Promise { - try { - await this.start() - const parsedOptions = CreateOrRecoverJobStepOptionsSchema.parse(options) - const result = await this._createOrRecoverJobStep(parsedOptions) - return CreateOrRecoverJobStepResultNullableSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.createOrRecoverJobStep()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = CreateOrRecoverJobStepOptionsSchema.parse(options) + const result = await this._createOrRecoverJobStep(parsedOptions) + return CreateOrRecoverJobStepResultNullableSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.createOrRecoverJobStep()') + throw error + } + }) } /** @@ -529,15 +535,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if completed, `false` otherwise */ async completeJobStep(options: CompleteJobStepOptions): Promise { - try { - await this.start() - const parsedOptions = CompleteJobStepOptionsSchema.parse(options) - const result = await this._completeJobStep(parsedOptions) - return BooleanResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.completeJobStep()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = CompleteJobStepOptionsSchema.parse(options) + const result = await this._completeJobStep(parsedOptions) + return BooleanResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.completeJobStep()') + throw error + } + }) } /** @@ -546,15 +556,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if failed, `false` otherwise */ async failJobStep(options: FailJobStepOptions): Promise { - try { - await this.start() - const parsedOptions = FailJobStepOptionsSchema.parse(options) - const result = await this._failJobStep(parsedOptions) - return BooleanResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.failJobStep()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = FailJobStepOptionsSchema.parse(options) + const result = await this._failJobStep(parsedOptions) + return BooleanResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.failJobStep()') + throw error + } + }) } /** @@ -563,15 +577,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if delayed, `false` otherwise */ async delayJobStep(options: DelayJobStepOptions): Promise { - try { - await this.start() - const parsedOptions = DelayJobStepOptionsSchema.parse(options) - const result = await this._delayJobStep(parsedOptions) - return BooleanResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.delayJobStep()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = DelayJobStepOptionsSchema.parse(options) + const result = await this._delayJobStep(parsedOptions) + return BooleanResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.delayJobStep()') + throw error + } + }) } /** @@ -580,15 +598,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to `true` if cancelled, `false` otherwise */ async cancelJobStep(options: CancelJobStepOptions): Promise { - try { - await this.start() - const parsedOptions = CancelJobStepOptionsSchema.parse(options) - const result = await this._cancelJobStep(parsedOptions) - return BooleanResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.cancelJobStep()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = CancelJobStepOptionsSchema.parse(options) + const result = await this._cancelJobStep(parsedOptions) + return BooleanResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.cancelJobStep()') + throw error + } + }) } // ============================================================================ @@ -737,17 +759,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to the job, or `null` if not found */ async getJobById(jobId: string): Promise { - try { - const parsedJobId = z.string().parse(jobId) - const result = await this._getJobById(parsedJobId) - if (result === null) { - return null + return this.#lifecycle.run(async () => { + try { + const parsedJobId = z.string().parse(jobId) + const result = await this._getJobById(parsedJobId) + if (result === null) { + return null + } + return JobSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.getJobById()') + throw error } - return JobSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.getJobById()') - throw error - } + }) } /** @@ -759,14 +783,16 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to { steps, total }, where total is the number of matching steps */ async getJobSteps(options: GetJobStepsOptions): Promise { - try { - const parsedOptions = GetJobStepsOptionsSchema.parse(options) - const result = await this._getJobSteps(parsedOptions) - return GetJobStepsResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.getJobSteps()') - throw error - } + return this.#lifecycle.run(async () => { + try { + const parsedOptions = GetJobStepsOptionsSchema.parse(options) + const result = await this._getJobSteps(parsedOptions) + return GetJobStepsResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.getJobSteps()') + throw error + } + }) } /** @@ -777,14 +803,16 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to jobs result with pagination info */ async getJobs(options?: GetJobsOptions): Promise { - try { - const parsedOptions = options ? GetJobsOptionsSchema.parse(options) : undefined - const result = await this._getJobs(parsedOptions) - return GetJobsResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.getJobs()') - throw error - } + return this.#lifecycle.run(async () => { + try { + const parsedOptions = options ? GetJobsOptionsSchema.parse(options) : undefined + const result = await this._getJobs(parsedOptions) + return GetJobsResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.getJobs()') + throw error + } + }) } /** @@ -794,17 +822,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to the step, or `null` if not found */ async getJobStepById(stepId: string): Promise { - try { - const parsedStepId = z.string().parse(stepId) - const result = await this._getJobStepById(parsedStepId) - if (result === null) { - return null + return this.#lifecycle.run(async () => { + try { + const parsedStepId = z.string().parse(stepId) + const result = await this._getJobStepById(parsedStepId) + if (result === null) { + return null + } + return JobStepSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.getJobStepById()') + throw error } - return JobStepSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.getJobStepById()') - throw error - } + }) } /** @@ -814,17 +844,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to job status result, or `null` if not found */ async getJobStatus(jobId: string): Promise { - try { - const parsedJobId = z.string().parse(jobId) - const result = await this._getJobStatus(parsedJobId) - if (result === null) { - return null + return this.#lifecycle.run(async () => { + try { + const parsedJobId = z.string().parse(jobId) + const result = await this._getJobStatus(parsedJobId) + if (result === null) { + return null + } + return JobStatusResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.getJobStatus()') + throw error } - return JobStatusResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.getJobStatus()') - throw error - } + }) } /** @@ -834,17 +866,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to step status result, or `null` if not found */ async getJobStepStatus(stepId: string): Promise { - try { - const parsedStepId = z.string().parse(stepId) - const result = await this._getJobStepStatus(parsedStepId) - if (result === null) { - return null + return this.#lifecycle.run(async () => { + try { + const parsedStepId = z.string().parse(stepId) + const result = await this._getJobStepStatus(parsedStepId) + if (result === null) { + return null + } + return JobStepStatusResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.getJobStepStatus()') + throw error } - return JobStepStatusResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.getJobStepStatus()') - throw error - } + }) } /** @@ -853,13 +887,15 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to action statistics */ async getActions(): Promise { - try { - const result = await this._getActions() - return GetActionsResultSchema.parse(result) - } catch (error) { - this.#logger?.error(error, 'Error in Adapter.getActions()') - throw error - } + return this.#lifecycle.run(async () => { + try { + const result = await this._getActions() + return GetActionsResultSchema.parse(result) + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.getActions()') + throw error + } + }) } // ============================================================================ @@ -935,15 +971,19 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to the number of jobs deleted */ async pruneArchive(options: PruneArchiveOptions): Promise { - try { - await this.start() - const parsedOptions = PruneArchiveOptionsSchema.parse(options) - const result = await this._pruneArchive(parsedOptions) - return NumberResultSchema.parse(result) - } catch (error) { - this.logger?.error(error, 'Error in Adapter.pruneArchive()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = PruneArchiveOptionsSchema.parse(options) + const result = await this._pruneArchive(parsedOptions) + return NumberResultSchema.parse(result) + } catch (error) { + this.logger?.error(error, 'Error in Adapter.pruneArchive()') + throw error + } + }) } /** @@ -952,13 +992,17 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to void */ async truncateArchive(): Promise { - try { - await this.start() - await this._truncateArchive() - } catch (error) { - this.logger?.error(error, 'Error in Adapter.truncateArchive()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + await this._truncateArchive() + } catch (error) { + this.logger?.error(error, 'Error in Adapter.truncateArchive()') + throw error + } + }) } /** @@ -967,14 +1011,18 @@ export abstract class Adapter extends EventEmitter { * @returns Promise resolving to archive stats */ async getArchiveStats(): Promise { - try { - await this.start() - const result = await this._getArchiveStats() - return ArchiveStatsSchema.parse(result) - } catch (error) { - this.logger?.error(error, 'Error in Adapter.getArchiveStats()') - throw error - } + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const result = await this._getArchiveStats() + return ArchiveStatsSchema.parse(result) + } catch (error) { + this.logger?.error(error, 'Error in Adapter.getArchiveStats()') + throw error + } + }) } // ============================================================================ @@ -1023,6 +1071,13 @@ export abstract class Adapter extends EventEmitter { */ protected abstract _stop(): Promise + protected _canCleanup(): boolean { + return !this.#closed && !this.#lifecycle.closing + } + + /** Release owned resources after database cleanup, including when cleanup fails. */ + protected async _close(): Promise {} + /** * Send a notification event. * This is adapter-specific (e.g., PostgreSQL NOTIFY). diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 76dc30a..ddc1111 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -26,6 +26,7 @@ import { STEP_STATUS_COMPLETED, STEP_STATUS_FAILED, } from '../../constants.js' +import { lifecycleFor } from '../../lifecycle.js' import { Adapter, type ArchiveStats, @@ -98,6 +99,9 @@ export abstract class PostgresBaseAdapter< private pruneTimer: ReturnType | null = null private pruneConfig: PruneSchedulerConfig | null = null private lastPrunedAt: Date | null = null + private initialized = false + protected ownedClosed = false + private listenerObligations: Array<{ done: boolean }> = [] // ============================================================================ // Constructor @@ -119,6 +123,8 @@ export abstract class PostgresBaseAdapter< this.tables = createSchema(this.schema) this._initDb() + this._guardTransactions() + lifecycleFor(this).onQuiesce(() => this._stopScheduler()) } /** @@ -126,6 +132,26 @@ export abstract class PostgresBaseAdapter< */ protected abstract _initDb(): void + protected _assertSql(): void { + lifecycleFor(this).assertContinuation() + if (!this._canCleanup()) throw new Error('Lifecycle SQL resources are unavailable') + } + + private _guardTransactions(): void { + const transaction = this.db.transaction.bind(this.db) + this.db.transaction = (work, config) => { + this._assertSql() + return transaction(async (tx) => { + this._assertSql() + const result = await work(tx) + // The driver owns COMMIT/ROLLBACK outside Drizzle's statement logger. + // Reject here so it can roll back instead of committing a late callback. + this._assertSql() + return result + }, config) + } + } + // ============================================================================ // Lifecycle Methods // ============================================================================ @@ -137,6 +163,7 @@ export abstract class PostgresBaseAdapter< * @returns Promise resolving to `true` if started successfully, `false` otherwise */ protected async _start() { + if (!lifecycleFor(this).accepting) return // Prune ancient client liveness rows (garbage collection for instances // that died long ago without a graceful release). The threshold is // deliberately generous — recovery uses its own much smaller threshold, @@ -146,30 +173,93 @@ export abstract class PostgresBaseAdapter< DELETE FROM ${this.tables.clientsTable} WHERE last_seen_at < now() - interval '24 hours' `) - } catch { - // Table may not exist yet (before migration) — skip pruning + } catch (error) { + if (!this._isUninitializedLivenessAbsence(error)) throw error } - await this._listen(`job-status-changed`, (payload: string) => { - if (this.listenerCount('job-status-changed') > 0) { + if (!lifecycleFor(this).accepting) return + await this._listenForEvents(`job-status-changed`, (payload: string) => { + if (lifecycleFor(this).accepting && this.listenerCount('job-status-changed') > 0) { const { jobId, status, clientId } = JSON.parse(payload) this.emit('job-status-changed', { jobId, status, clientId }) } }) - await this._listen(`job-available`, (payload: string) => { - if (this.listenerCount('job-available') > 0) { + if (!lifecycleFor(this).accepting) return + await this._listenForEvents(`job-available`, (payload: string) => { + if (lifecycleFor(this).accepting && this.listenerCount('job-available') > 0) { const { jobId } = JSON.parse(payload) this.emit('job-available', { jobId }) } }) // Start archive prune scheduler if configured + if (!lifecycleFor(this).accepting) return this._startScheduler() + this.initialized = true + } + + protected _allowNotification(event: string, data: unknown): boolean { + if (lifecycleFor(this).ordinaryOpen) return true + const ids = + data !== null && typeof data === 'object' + ? (data as { jobId?: unknown; clientId?: unknown }) + : undefined + this.logger?.error( + { + err: new Error('Notification omitted after lifecycle drain'), + backend: this.constructor.name, + event, + channel: `${this.schema}.${event}`, + stage: 'lifecycle cutoff', + jobId: typeof ids?.jobId === 'string' ? ids.jobId : undefined, + clientId: typeof ids?.clientId === 'string' ? ids.clientId : this.id, + mutationResult: 'unchanged', + delivery: 'unconfirmed', + }, + 'Notification omitted: mutation result unchanged; delivery unconfirmed', + ) + return false + } + + private async _listenForEvents( + event: string, + callback: (payload: string) => void, + ): Promise { + const handle = await this._listen(event, callback) + this._registerListenerCleanup(event, async () => { + await handle.unlisten() + }) + } + + protected _registerListenerCleanup(event: string, cleanup: () => Promise): void { + const obligation = lifecycleFor(this).obligation( + `listener ${event}`, + 'database cleanup', + cleanup, + () => this._canCleanup(), + ) + // A handle returned late after confirmed owned closure has no live SQL resource. + obligation.done = this.ownedClosed + this.listenerObligations.push(obligation) + } + + protected override _canCleanup(): boolean { + return !this.ownedClosed && super._canCleanup() + } + + protected override async _close(): Promise { + this.ownedClosed = true + for (const obligation of this.listenerObligations) obligation.done = true } protected async _stop() { this._stopScheduler() + // A constructed adapter without an identity could never register liveness. + if (this.id === undefined) return + if (!lifecycleFor(this).drained) { + throw new Error('Liveness release withheld because admitted work did not drain') + } // Release liveness record so other instances can recover this // instance's jobs immediately instead of waiting for staleness. @@ -177,26 +267,40 @@ export abstract class PostgresBaseAdapter< await this.db .delete(this.tables.clientsTable) .where(eq(this.tables.clientsTable.client_id, this.id)) - } catch { - // Table may not exist yet (before migration) — skip release + } catch (error) { + if (!this._isUninitializedLivenessAbsence(error)) throw error } } + private _isUninitializedLivenessAbsence(error: unknown): boolean { + if (this.initialized) return false + let cause = error + const seen = new Set() + while (cause instanceof Error && !seen.has(cause)) { + seen.add(cause) + if ( + 'code' in cause && + cause.code === '42P01' && + cause.message === `relation "${this.schema}.clients" does not exist` + ) { + return true + } + cause = cause.cause + } + return false + } + /** * Renew this instance's liveness record (upsert). */ protected async _heartbeat(): Promise { - try { - await this.db - .insert(this.tables.clientsTable) - .values({ client_id: this.id, last_seen_at: new Date() }) - .onConflictDoUpdate({ - target: this.tables.clientsTable.client_id, - set: { last_seen_at: new Date() }, - }) - } catch { - // Table may not exist yet (before migration) — skip heartbeat - } + await this.db + .insert(this.tables.clientsTable) + .values({ client_id: this.id, last_seen_at: sql`now()` }) + .onConflictDoUpdate({ + target: this.tables.clientsTable.client_id, + set: { last_seen_at: sql`now()` }, + }) } // ============================================================================ @@ -220,35 +324,39 @@ export abstract class PostgresBaseAdapter< */ private _startScheduler(): void { const config = this.pruneConfig - if (!config) return + const lifecycle = lifecycleFor(this) + if (!config || !lifecycle.accepting) return - const run = async () => { - try { - // Try to acquire advisory lock - const lockResult = await this.db.execute<{ pg_try_advisory_lock: boolean }>( - sql`SELECT pg_try_advisory_lock(${this._advisoryLockKey()})`, - ) + const run = () => { + if (!lifecycle.accepting) return Promise.resolve() + return lifecycle.run(async () => { + try { + // Try to acquire advisory lock + const lockResult = await this.db.execute<{ pg_try_advisory_lock: boolean }>( + sql`SELECT pg_try_advisory_lock(${this._advisoryLockKey()})`, + ) - if (!lockResult[0]?.pg_try_advisory_lock) { - this.logger?.debug('Another process holds the prune lock, skipping') - return - } + if (!lockResult[0]?.pg_try_advisory_lock) { + this.logger?.debug('Another process holds the prune lock, skipping') + return + } - try { - this.logger?.info('Running scheduled archive prune') - const deleted = await this._pruneArchive({ - olderThan: config.olderThan, - batchSize: config.batchSize, - maxBatches: config.maxBatches, - }) - this.lastPrunedAt = new Date() - this.logger?.info({ deletedJobs: deleted }, 'Archive prune completed') - } finally { - await this.db.execute(sql`SELECT pg_advisory_unlock(${this._advisoryLockKey()})`) + try { + this.logger?.info('Running scheduled archive prune') + const deleted = await this._pruneArchive({ + olderThan: config.olderThan, + batchSize: config.batchSize, + maxBatches: config.maxBatches, + }) + this.lastPrunedAt = new Date() + this.logger?.info({ deletedJobs: deleted }, 'Archive prune completed') + } finally { + await this.db.execute(sql`SELECT pg_advisory_unlock(${this._advisoryLockKey()})`) + } + } catch (error) { + this.logger?.error(error, 'Error in prune scheduler') } - } catch (error) { - this.logger?.error(error, 'Error in prune scheduler') - } + }) } // Run immediately on start, then on interval diff --git a/packages/duron/src/adapters/postgres/pglite.ts b/packages/duron/src/adapters/postgres/pglite.ts index 5785dd0..02e8d42 100644 --- a/packages/duron/src/adapters/postgres/pglite.ts +++ b/packages/duron/src/adapters/postgres/pglite.ts @@ -4,6 +4,8 @@ import { drizzle } from 'drizzle-orm/pglite' import { migrate } from 'drizzle-orm/pglite/migrator' import { defineRelations } from 'drizzle-orm/relations' +import { lifecycleFor } from '../../lifecycle.js' + import { type AdapterOptions, PostgresBaseAdapter } from './base.js' import type createSchema from './schema.js' @@ -19,6 +21,8 @@ export type DB = ReturnType { + #listenerCounts = new Map() + #removeListeners = new Set<() => void>() /** * Start the adapter. * Runs migrations if enabled and sets up database listeners. @@ -37,8 +41,19 @@ export class PGLiteAdapter extends PostgresBaseAdapter { await super._start() } - protected override async _stop() { - await this.db?.$client.close() + protected override async _close() { + for (const remove of this.#removeListeners) remove() + try { + if (!this.db.$client.closed) await this.db.$client.close() + } finally { + // A rejected reply does not erase positive engine-closure evidence. Keep + // that error for this attempt, but discharge the released listener resources. + if (this.db.$client.closed) await super._close() + } + } + + protected override _canCleanup(): boolean { + return !this.db.$client.closed && super._canCleanup() } /** @@ -64,10 +79,13 @@ export class PGLiteAdapter extends PostgresBaseAdapter { } const { schema: _schema, ...tables } = this.tables const relations = defineRelations(tables) + // Pinned Drizzle no-cache execution calls this immediately before issuing SQL, + // including builders and migration/session queries. It is not cancellation. + const logger = { logQuery: () => this._assertSql() } if (connection === ':memory:') { - this.db = drizzle({ relations }) as unknown as DB + this.db = drizzle({ relations, logger }) as unknown as DB } else { - this.db = drizzle({ connection, relations }) as unknown as DB + this.db = drizzle({ connection, relations, logger }) as unknown as DB } } @@ -79,6 +97,7 @@ export class PGLiteAdapter extends PostgresBaseAdapter { * @returns Promise resolving to `void` */ protected override async _notify(event: string, data: any): Promise { + if (!this._allowNotification(event, data)) return await this.db?.$client.query(`NOTIFY "${this.schema}.${event}", '${JSON.stringify(data)}'`) } @@ -93,15 +112,64 @@ export class PGLiteAdapter extends PostgresBaseAdapter { event: string, callback: (payload: string) => void, ): Promise<{ unlisten: () => void }> { - const unlisten = await this.db?.$client.listen( - `"${this.schema}.${event}"`, - (payload: string) => { - callback(payload) - }, + const channel = `${this.schema}.${event}` + this._assertSql() + const { rows } = await this.db.$client.query<{ identifier: string }>( + 'SELECT quote_ident($1) AS identifier', + [channel], ) + const identifier = rows[0]!.identifier + // Stop may win while quoting the identifier. Do not acquire another resource. + if (!lifecycleFor(this).accepting) return { unlisten: () => undefined } + + const off = this.db.$client.onNotification((receivedChannel, payload) => { + if (receivedChannel === channel && lifecycleFor(this).accepting) callback(payload) + }) + this.#listenerCounts.set(channel, (this.#listenerCounts.get(channel) ?? 0) + 1) + let localRemoved = false + const remove = () => { + if (localRemoved) return + localRemoved = true + off() + this.#removeListeners.delete(remove) + const count = (this.#listenerCounts.get(channel) ?? 1) - 1 + if (count) this.#listenerCounts.set(channel, count) + else this.#listenerCounts.delete(channel) + } + this.#removeListeners.add(remove) + + let released = false + let pending: Promise | null = null + const unlisten = (): Promise => { + if (released) return Promise.resolve() + if (pending) return pending + remove() + pending = Promise.resolve() + .then(async () => { + // A replacement can register while this cleanup waits to issue SQL. + // Check ownership here, not before the queued continuation. + if (!this.#listenerCounts.has(channel)) { + this._assertSql() + await this.db.$client.query(`UNLISTEN ${identifier}`) + } + released = true + }) + .catch((error: unknown) => { + pending = null + throw error + }) + return pending + } - return { - unlisten, + try { + this._assertSql() + await this.db.$client.query(`LISTEN ${identifier}`) + return { unlisten } + } catch (error) { + remove() + // A failed reply cannot prove LISTEN did not execute. Keep SQL cleanup owed. + this._registerListenerCleanup(event, unlisten) + throw error } } } diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index f01cc7d..065e7f2 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -5,6 +5,8 @@ import { migrate } from 'drizzle-orm/postgres-js/migrator' import { defineRelations } from 'drizzle-orm/relations' import type { Options as PostgresOptions } from 'postgres' +import { lifecycleFor } from '../../lifecycle.js' + import { type AdapterOptions, PostgresBaseAdapter } from './base.js' import type createSchema from './schema.js' @@ -49,6 +51,9 @@ export class PostgresAdapter extends PostgresBaseAdapter this._assertSql() }, }) } @@ -79,10 +84,10 @@ export class PostgresAdapter extends PostgresBaseAdapter { + if (!this._allowNotification(event, data)) return this.logger?.debug({ event, data }, `[PostgresAdapter] Notify ${event}`) await this.db.$client .notify(`${this.schema}.${event}`, JSON.stringify(data)) @@ -116,8 +122,9 @@ export class PostgresAdapter extends PostgresBaseAdapter void, ): Promise<{ unlisten: () => void }> { + this._assertSql() return await this.db.$client.listen(`${this.schema}.${event}`, (payload: string) => { - callback(payload) + if (lifecycleFor(this).accepting) callback(payload) }) } } diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 7398554..1e34462 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -32,6 +32,7 @@ import { JOB_STATUS_FAILED, type JobStatus, } from './constants.js' +import { type Lifecycle, lifecycleFor } from './lifecycle.js' import { validateSchema } from './standard-schema.js' /** @@ -346,9 +347,7 @@ export class Client< #tracer: Tracer #variables: Record #logger: Logger - #started: boolean = false - #stopped: boolean = false - #starting: Promise | null = null + #lifecycle: Lifecycle #stopping: Promise | null = null #pullInterval: NodeJS.Timeout | null = null #heartbeatTimer: NodeJS.Timeout | null = null @@ -384,6 +383,8 @@ export class Client< this.#options = BaseOptionsSchema.parse(options) this.#id = options.id ?? globalThis.crypto.randomUUID() this.#database = options.database + this.#lifecycle = lifecycleFor(this.#database) + this.#lifecycle.onQuiesce(() => this.#quiesce()) this.#actions = options.actions ?? null this.#variables = options?.variables ?? {} this.#logger = this.#normalizeLogger(options?.logger) @@ -499,63 +500,68 @@ export class Client< ? StandardSchemaV1.InferInput> : never, ): Promise { - await this.start() + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() - const action = this.#actions?.[actionName] - if (!action) { - throw new Error(`Action ${String(actionName)} not found`) - } + const action = this.#actions?.[actionName] + if (!action) { + throw new Error(`Action ${String(actionName)} not found`) + } - // Validate input if schema is provided - let validatedInput: any = input ?? {} - if (action.input) { - validatedInput = await validateSchema(action.input, validatedInput) - } + // Validate input if schema is provided + let validatedInput: any = input ?? {} + if (action.input) { + validatedInput = await validateSchema(action.input, validatedInput) + } - // Determine groupKey and concurrency limit using concurrency handler or defaults - const concurrencyCtx: ConcurrencyHandlerContext = { - input: validatedInput, - var: this.#variables as TVariables, - } + // Determine groupKey and concurrency limit using concurrency handler or defaults + const concurrencyCtx: ConcurrencyHandlerContext = { + input: validatedInput, + var: this.#variables as TVariables, + } - let groupKey = '@default' - if (action.groups?.groupKey) { - groupKey = await action.groups.groupKey(concurrencyCtx) - } + let groupKey = '@default' + if (action.groups?.groupKey) { + groupKey = await action.groups.groupKey(concurrencyCtx) + } - let concurrencyLimit = this.#options.groupConcurrencyLimit - if (action.groups?.concurrency) { - concurrencyLimit = await action.groups.concurrency(concurrencyCtx) - } + let concurrencyLimit = this.#options.groupConcurrencyLimit + if (action.groups?.concurrency) { + concurrencyLimit = await action.groups.concurrency(concurrencyCtx) + } - // Calculate description if provided - let description: string | null = null - if (action.description) { - description = await action.description(concurrencyCtx) - } + // Calculate description if provided + let description: string | null = null + if (action.description) { + description = await action.description(concurrencyCtx) + } - // Create job in database - const jobId = await this.#database.createJob({ - queue: action.name, - groupKey, - input: validatedInput, - timeoutMs: action.expire, - checksum: action.checksum, - concurrencyLimit, - concurrencyStepLimit: action.steps.concurrency, - description, - }) + this.#lifecycle.assertContinuation() + + // Create job in database + const jobId = await this.#database.createJob({ + queue: action.name, + groupKey, + input: validatedInput, + timeoutMs: action.expire, + checksum: action.checksum, + concurrencyLimit, + concurrencyStepLimit: action.steps.concurrency, + description, + }) - if (!jobId) { - throw new Error(`Failed to create job for action ${String(actionName)}`) - } + if (!jobId) { + throw new Error(`Failed to create job for action ${String(actionName)}`) + } - this.#logger.debug( - { jobId, actionName: String(actionName), groupKey }, - '[Duron] Action sent/created', - ) + this.#logger.debug( + { jobId, actionName: String(actionName), groupKey }, + '[Duron] Action sent/created', + ) - return jobId + return jobId + }) } /** @@ -584,104 +590,107 @@ export class Client< timeout?: number }, ): Promise> { - // Check if already aborted before starting - if (options?.signal?.aborted) { - throw new Error('Operation was aborted') - } + return this.#lifecycle.run(async () => { + // Check if already aborted before starting + if (options?.signal?.aborted) { + throw new Error('Operation was aborted') + } - // Create the job - const jobId = await this.runAction(actionName, input) + // Create the job + const jobId = await this.runAction(actionName, input) + if (!this.#lifecycle.accepting) throw new Error('Client is not accepting work') - // Set up abort handler to cancel the job if signal is aborted - let abortHandler: (() => void) | undefined - if (options?.signal) { - abortHandler = () => { - this.cancelJob(jobId).catch((err) => { - this.#logger.error({ err, jobId }, '[Duron] Error cancelling job on abort') - }) + // Set up abort handler to cancel the job if signal is aborted + let abortHandler: (() => void) | undefined + if (options?.signal) { + abortHandler = () => { + this.cancelJob(jobId).catch((err) => { + this.#logger.error({ err, jobId }, '[Duron] Error cancelling job on abort') + }) + } + options.signal.addEventListener('abort', abortHandler, { once: true }) } - options.signal.addEventListener('abort', abortHandler, { once: true }) - } - // Set up timeout handler to cancel the job if timeout is reached - let timeoutId: NodeJS.Timeout | undefined - let timeoutAbortController: AbortController | undefined - if (options?.timeout) { - timeoutAbortController = new AbortController() - timeoutId = setTimeout(() => { - timeoutAbortController!.abort() - this.cancelJob(jobId).catch((err) => { - this.#logger.error({ err, jobId }, '[Duron] Error cancelling job on timeout') - }) - }, options.timeout) - } - - try { - // Combine signals if both are provided - let waitSignal: AbortSignal | undefined - if (options?.signal && timeoutAbortController) { - waitSignal = AbortSignal.any([options.signal, timeoutAbortController.signal]) - } else if (options?.signal) { - waitSignal = options.signal - } else if (timeoutAbortController) { - waitSignal = timeoutAbortController.signal + // Set up timeout handler to cancel the job if timeout is reached + let timeoutId: NodeJS.Timeout | undefined + let timeoutAbortController: AbortController | undefined + if (options?.timeout) { + timeoutAbortController = new AbortController() + timeoutId = setTimeout(() => { + timeoutAbortController!.abort() + this.cancelJob(jobId).catch((err) => { + this.#logger.error({ err, jobId }, '[Duron] Error cancelling job on timeout') + }) + }, options.timeout) } - // Wait for the job to complete - const job = await this.waitForJob(jobId, { signal: waitSignal }) + try { + // Combine signals if both are provided + let waitSignal: AbortSignal | undefined + if (options?.signal && timeoutAbortController) { + waitSignal = AbortSignal.any([options.signal, timeoutAbortController.signal]) + } else if (options?.signal) { + waitSignal = options.signal + } else if (timeoutAbortController) { + waitSignal = timeoutAbortController.signal + } - // Clean up - if (timeoutId) { - clearTimeout(timeoutId) - } - if (options?.signal && abortHandler) { - options.signal.removeEventListener('abort', abortHandler) - } + // Wait for the job to complete + const job = await this.waitForJob(jobId, { signal: waitSignal }) - // Handle null result (aborted or timed out) - if (!job) { - if (options?.signal?.aborted) { - throw new Error('Operation was aborted') + // Clean up + if (timeoutId) { + clearTimeout(timeoutId) } - if (timeoutAbortController?.signal.aborted) { - throw new Error('Operation timed out') + if (options?.signal && abortHandler) { + options.signal.removeEventListener('abort', abortHandler) } - throw new Error('Job not found') - } - // Handle cancelled job - if (job.status === JOB_STATUS_CANCELLED) { - if (options?.signal?.aborted) { - throw new Error('Operation was aborted') + // Handle null result (aborted or timed out) + if (!job) { + if (options?.signal?.aborted) { + throw new Error('Operation was aborted') + } + if (timeoutAbortController?.signal.aborted) { + throw new Error('Operation timed out') + } + throw new Error('Job not found') } - if (timeoutAbortController?.signal.aborted) { - throw new Error('Operation timed out') + + // Handle cancelled job + if (job.status === JOB_STATUS_CANCELLED) { + if (options?.signal?.aborted) { + throw new Error('Operation was aborted') + } + if (timeoutAbortController?.signal.aborted) { + throw new Error('Operation timed out') + } + throw new Error('Job was cancelled') } - throw new Error('Job was cancelled') - } - // Handle failed job - if (job.status === JOB_STATUS_FAILED) { - const errorMessage = job.error?.message ?? 'Job failed' - const error = new Error(errorMessage) - if (job.error?.stack) { - error.stack = job.error.stack + // Handle failed job + if (job.status === JOB_STATUS_FAILED) { + const errorMessage = job.error?.message ?? 'Job failed' + const error = new Error(errorMessage) + if (job.error?.stack) { + error.stack = job.error.stack + } + throw error } - throw error - } - // Return the job result with typed input/output - return job as TypedJobResult - } catch (err) { - // Clean up on error - if (timeoutId) { - clearTimeout(timeoutId) - } - if (options?.signal && abortHandler) { - options.signal.removeEventListener('abort', abortHandler) + // Return the job result with typed input/output + return job as TypedJobResult + } catch (err) { + // Clean up on error + if (timeoutId) { + clearTimeout(timeoutId) + } + if (options?.signal && abortHandler) { + options.signal.removeEventListener('abort', abortHandler) + } + throw err } - throw err - } + }) } /** @@ -692,37 +701,41 @@ export class Client< * @returns Promise resolving to the array of fetched jobs */ async fetch(options: FetchOptions = {}) { - await this.start() + return this.#lifecycle.run(async () => { + await this.start() - if (!this.#actions) { - return [] - } + if (!this.#actions) { + return [] + } - // Run recovery periodically (time-based, always multi-process) - const now = Date.now() - if ( - this.#options.recoverJobsInterval > 0 && - now - this.#lastRecoveryAt > this.#options.recoverJobsInterval - ) { - this.#lastRecoveryAt = now - await this.#database.recoverJobs({ - checksums: Object.values(this.#actions).map((action) => action.checksum), - staleTimeoutMs: this.#options.heartbeatTimeout, - }) - } + // Run recovery periodically (time-based, always multi-process) + const now = Date.now() + if ( + this.#options.recoverJobsInterval > 0 && + now - this.#lastRecoveryAt > this.#options.recoverJobsInterval + ) { + this.#lastRecoveryAt = now + await this.#database.recoverJobs({ + checksums: Object.values(this.#actions).map((action) => action.checksum), + staleTimeoutMs: this.#options.heartbeatTimeout, + }) + } - // Fetch jobs from each action's queue - // Concurrency limits are determined from the latest job created for each groupKey - const jobs = await this.#database.fetch({ - batch: options.batchSize ?? this.#options.batchSize, - }) + this.#lifecycle.assertContinuation() - // Process fetched jobs - for (const job of jobs) { - this.#executeJob(job) - } + // Fetch jobs from each action's queue + // Concurrency limits are determined from the latest job created for each groupKey + const jobs = await this.#database.fetch({ + batch: options.batchSize ?? this.#options.batchSize, + }) - return jobs + // Process fetched jobs + for (const job of jobs) { + this.#executeJob(job) + } + + return jobs + }) } /** @@ -734,22 +747,25 @@ export class Client< * @returns Promise resolving to `true` if cancelled, `false` otherwise */ async cancelJob(jobId: string) { - await this.start() - - let cancelled = false - for (const manager of this.#actionManagers.values()) { - cancelled = manager.cancelJob(jobId) - if (cancelled) { - break + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + + let cancelled = false + for (const manager of this.#actionManagers.values()) { + cancelled = manager.cancelJob(jobId) + if (cancelled) { + break + } } - } - if (!cancelled) { - // If the job is not being processed, cancel it in the database - await this.#database.cancelJob({ jobId }) - } + if (!cancelled) { + // If the job is not being processed, cancel it in the database + await this.#database.cancelJob({ jobId }) + } - return cancelled + return cancelled + }) } /** @@ -759,8 +775,11 @@ export class Client< * @returns Promise resolving to the new job ID, or `null` if retry failed */ async retryJob(jobId: string): Promise { - await this.start() - return this.#database.retryJob({ jobId }) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.retryJob({ jobId }) + }) } /** @@ -774,8 +793,11 @@ export class Client< * @returns Promise resolving to `true` if time travel succeeded, `false` otherwise */ async timeTravelJob(jobId: string, stepId: string): Promise { - await this.start() - return this.#database.timeTravelJob({ jobId, stepId }) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.timeTravelJob({ jobId, stepId }) + }) } /** @@ -786,8 +808,11 @@ export class Client< * @returns Promise resolving to `true` if deleted, `false` otherwise */ async deleteJob(jobId: string): Promise { - await this.start() - return this.#database.deleteJob({ jobId }) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.deleteJob({ jobId }) + }) } /** @@ -798,8 +823,11 @@ export class Client< * @returns Promise resolving to the number of jobs deleted */ async deleteJobs(options?: GetJobsOptions): Promise { - await this.start() - return this.#database.deleteJobs(options) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.deleteJobs(options) + }) } // ============================================================================ @@ -813,8 +841,11 @@ export class Client< * @returns Promise resolving to the job, or `null` if not found */ async getJobById(jobId: string): Promise { - await this.start() - return this.#database.getJobById(jobId) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.getJobById(jobId) + }) } /** @@ -826,8 +857,11 @@ export class Client< * @returns Promise resolving to { steps, total }, where total is the number of matching steps */ async getJobSteps(options: GetJobStepsOptions): Promise { - await this.start() - return this.#database.getJobSteps(options) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.getJobSteps(options) + }) } /** @@ -838,8 +872,11 @@ export class Client< * @returns Promise resolving to jobs result with pagination info */ async getJobs(options?: GetJobsOptions): Promise { - await this.start() - return this.#database.getJobs(options) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.getJobs(options) + }) } /** @@ -849,8 +886,11 @@ export class Client< * @returns Promise resolving to the step, or `null` if not found */ async getJobStepById(stepId: string): Promise { - await this.start() - return this.#database.getJobStepById(stepId) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.getJobStepById(stepId) + }) } /** @@ -860,8 +900,11 @@ export class Client< * @returns Promise resolving to job status result, or `null` if not found */ async getJobStatus(jobId: string): Promise { - await this.start() - return this.#database.getJobStatus(jobId) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.getJobStatus(jobId) + }) } /** @@ -871,8 +914,11 @@ export class Client< * @returns Promise resolving to step status result, or `null` if not found */ async getJobStepStatus(stepId: string): Promise { - await this.start() - return this.#database.getJobStepStatus(stepId) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.getJobStepStatus(stepId) + }) } /** @@ -897,90 +943,94 @@ export class Client< signal?: AbortSignal }, ): Promise { - await this.start() - - // Set up the shared event listener if not already set up - this.#setupJobStatusListener() - - // Register the wait BEFORE checking status to prevent TOCTOU race - // If the job completes between status check and wait registration, - // the NOTIFY would be missed - let timeoutId: NodeJS.Timeout | undefined - let abortHandler: (() => void) | undefined - - return new Promise((resolve) => { - // Check if already aborted before setting up wait - if (options?.signal?.aborted) { - resolve(null) - return - } - - // Set up timeout if provided - if (options?.timeout) { - timeoutId = setTimeout(() => { - this.#removeJobWait(jobId, resolve) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + if (!this.#lifecycle.accepting) return null + + // Set up the shared event listener if not already set up + this.#setupJobStatusListener() + + // Register the wait BEFORE checking status to prevent TOCTOU race + // If the job completes between status check and wait registration, + // the NOTIFY would be missed + let timeoutId: NodeJS.Timeout | undefined + let abortHandler: (() => void) | undefined + + return new Promise((resolve) => { + // Check if already aborted before setting up wait + if (options?.signal?.aborted) { resolve(null) - }, options.timeout) - } + return + } - // Set up abort signal if provided - if (options?.signal) { - abortHandler = () => { - this.#removeJobWait(jobId, resolve) - resolve(null) + // Set up timeout if provided + if (options?.timeout) { + timeoutId = setTimeout(() => { + this.#removeJobWait(jobId, resolve) + resolve(null) + }, options.timeout) } - options.signal.addEventListener('abort', abortHandler) - } - // Add this wait request to the pending waits BEFORE checking status - if (!this.#pendingJobWaits.has(jobId)) { - this.#pendingJobWaits.set(jobId, new Set()) - } - this.#pendingJobWaits.get(jobId)!.add({ - resolve, - timeoutId, - signal: options?.signal, - abortHandler, - }) + // Set up abort signal if provided + if (options?.signal) { + abortHandler = () => { + this.#removeJobWait(jobId, resolve) + resolve(null) + } + options.signal.addEventListener('abort', abortHandler) + } + + // Add this wait request to the pending waits BEFORE checking status + if (!this.#pendingJobWaits.has(jobId)) { + this.#pendingJobWaits.set(jobId, new Set()) + } + this.#pendingJobWaits.get(jobId)!.add({ + resolve, + timeoutId, + signal: options?.signal, + abortHandler, + }) - // Now check if the job is already in a terminal state - // If so, remove the wait and resolve immediately - // Errors settle the wait as null to avoid hangs and leaked wait entries - this.getJobStatus(jobId) - .then((existingJobStatus) => { - if (existingJobStatus) { + // Now check if the job is already in a terminal state + // If so, remove the wait and resolve immediately + // Errors settle the wait as null to avoid hangs and leaked wait entries + void this.#lifecycle + .run(async () => { + const existingJobStatus = await this.getJobStatus(jobId) + if (!this.#lifecycle.accepting) return const terminalStatuses: JobStatus[] = [ JOB_STATUS_COMPLETED, JOB_STATUS_FAILED, JOB_STATUS_CANCELLED, ] - if (terminalStatuses.includes(existingJobStatus.status)) { - // Job is already terminal, remove the wait and resolve + if (existingJobStatus && terminalStatuses.includes(existingJobStatus.status)) { + const job = await this.getJobById(jobId) + if (!this.#lifecycle.accepting) return + // Keep the wait registered while detail is pending so stop can settle it. this.#removeJobWait(jobId, resolve) - return this.getJobById(jobId).then((job) => { - if (!job) { - resolve(null) - } else { - resolve({ - id: job.id, - actionName: job.actionName, - status: job.status, - groupKey: job.groupKey, - description: job.description, - input: job.input, - output: job.output, - error: job.error, - }) - } - }) + resolve( + job + ? { + id: job.id, + actionName: job.actionName, + status: job.status, + groupKey: job.groupKey, + description: job.description, + input: job.input, + output: job.output, + error: job.error, + } + : null, + ) } - } - }) - .catch((error) => { - this.#logger.error({ error, jobId }, '[Duron] [waitForJob] Error checking job status') - this.#removeJobWait(jobId, resolve) - resolve(null) - }) + }) + .catch((error: unknown) => { + this.#logger.error({ error, jobId }, '[Duron] [waitForJob] Error checking job status') + this.#removeJobWait(jobId, resolve) + resolve(null) + }) + }) }) } @@ -990,8 +1040,11 @@ export class Client< * @returns Promise resolving to action statistics */ async getActions(): Promise { - await this.start() - return this.#database.getActions() + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.getActions() + }) } /** @@ -1001,38 +1054,41 @@ export class Client< * @returns Promise resolving to action metadata */ async getActionsMetadata(): Promise> { - await this.start() + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() - if (!this.#actions) { - return [] - } + if (!this.#actions) { + return [] + } - return Object.values(this.#actions).map((action) => { - let mockInput = {} - if (action.input) { - if (!this.#mockInputSchemas.has(action.name)) { - // Generate mock from JSON Schema if available - const hasJsonSchema = - '~standard' in action.input && 'jsonSchema' in (action.input as any)['~standard'] - if (hasJsonSchema) { - try { - const jsonSchema = (action.input as any)['~standard'].jsonSchema.input({ - target: 'draft-2020-12', - }) - mockInput = generateMockFromJsonSchema(jsonSchema) - } catch { - // Fallback to empty object if mock generation fails - mockInput = {} + return Object.values(this.#actions).map((action) => { + let mockInput = {} + if (action.input) { + if (!this.#mockInputSchemas.has(action.name)) { + // Generate mock from JSON Schema if available + const hasJsonSchema = + '~standard' in action.input && 'jsonSchema' in (action.input as any)['~standard'] + if (hasJsonSchema) { + try { + const jsonSchema = (action.input as any)['~standard'].jsonSchema.input({ + target: 'draft-2020-12', + }) + mockInput = generateMockFromJsonSchema(jsonSchema) + } catch { + // Fallback to empty object if mock generation fails + mockInput = {} + } } + this.#mockInputSchemas.set(action.name, mockInput) } - this.#mockInputSchemas.set(action.name, mockInput) + mockInput = this.#mockInputSchemas.get(action.name) } - mockInput = this.#mockInputSchemas.get(action.name) - } - return { - name: action.name, - mockInput, - } + return { + name: action.name, + mockInput, + } + }) }) } @@ -1046,8 +1102,11 @@ export class Client< * @returns Promise resolving to archive statistics */ async getArchiveStats(): Promise { - await this.start() - return this.#database.getArchiveStats() + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.getArchiveStats() + }) } /** @@ -1057,8 +1116,11 @@ export class Client< * @returns Promise resolving to number of deleted jobs */ async pruneArchive(options: PruneArchiveOptions): Promise { - await this.start() - return this.#database.pruneArchive(options) + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.pruneArchive(options) + }) } /** @@ -1068,8 +1130,11 @@ export class Client< * @returns Promise resolving when complete */ async truncateArchive(): Promise { - await this.start() - return this.#database.truncateArchive() + return this.#lifecycle.run(async () => { + await this.start() + this.#lifecycle.assertContinuation() + return this.#database.truncateArchive() + }) } // ============================================================================ @@ -1082,132 +1147,76 @@ export class Client< * * @returns Promise resolving to `true` if started successfully, `false` otherwise */ - async start() { - if (this.#stopping || this.#stopped) { - return false - } - - if (this.#started) { - return true - } - - if (this.#starting) { - return this.#starting - } - - this.#starting = (async () => { - const dbStarted = await this.#database.start() - if (!dbStarted) { - return false - } - - // Initial heartbeat to register this instance as alive - await this.#database.heartbeat() - this.#scheduleHeartbeat() - - if (this.#actions) { - if (this.#options.recoverJobsOnStart) { + async start(): Promise { + return this.#lifecycle.start( + this, + async () => { + if (!(await this.#database.start()) || !this.#lifecycle.accepting) return false + await this.#database.heartbeat() + if (!this.#lifecycle.accepting) return false + if (this.#actions && this.#options.recoverJobsOnStart) { await this.#database.recoverJobs({ checksums: Object.values(this.#actions).map((action) => action.checksum), staleTimeoutMs: this.#options.heartbeatTimeout, }) + if (!this.#lifecycle.accepting) return false } - - // Setup sync pattern - if (this.#options.syncPattern === 'pull' || this.#options.syncPattern === 'hybrid') { - this.#startPullLoop() - } - - if (this.#options.syncPattern === 'push' || this.#options.syncPattern === 'hybrid') { - this.#setupPushListener() + this.#scheduleHeartbeat() + if (this.#actions) { + if (this.#options.syncPattern === 'pull' || this.#options.syncPattern === 'hybrid') + this.#startPullLoop() + if (this.#options.syncPattern === 'push' || this.#options.syncPattern === 'hybrid') + this.#setupPushListener() } - } - - this.#started = true - this.#starting = null - return true - })() + return true + }, + () => this.stop(), + ) + } - return this.#starting + /** Quiesce synchronously, then preserve public Adapter.stop override dispatch. */ + async stop(): Promise { + if (this.#stopping) return this.#stopping + this.#stopping = Promise.resolve() + .then(() => this.#database.stop()) + .finally(() => { + this.#stopping = null + }) + this.#lifecycle.quiesce() + return this.#stopping } - /** - * Stop the Duron instance. - * Stops the pull loop, aborts all running jobs, waits for queues to drain, and stops the database. - * - * @returns Promise resolving to `true` if stopped successfully, `false` otherwise - */ - async stop() { - if (this.#stopped) { - return true + #quiesce(): Promise { + if (this.#heartbeatTimer) { + clearTimeout(this.#heartbeatTimer) + this.#heartbeatTimer = null } - - if (this.#stopping) { - return this.#stopping + if (this.#pullInterval) { + clearTimeout(this.#pullInterval) + this.#pullInterval = null } - - // Wait for any in-flight start() to complete before proceeding - if (this.#starting) { - await this.#starting + if (this.#jobStatusListener) { + this.#database.off('job-status-changed', this.#jobStatusListener) + this.#jobStatusListener = null + this.#jobStatusListenerSetup = false } - - this.#stopping = (async () => { - // Stop heartbeat timer - if (this.#heartbeatTimer) { - clearTimeout(this.#heartbeatTimer) - this.#heartbeatTimer = null - } - - // Stop pull loop - if (this.#pullInterval) { - clearTimeout(this.#pullInterval) - this.#pullInterval = null - } - - // Remove event listeners BEFORE stopping database to prevent use-after-close - if (this.#jobStatusListener) { - this.#database.off('job-status-changed', this.#jobStatusListener) - this.#jobStatusListener = null - this.#jobStatusListenerSetup = false - } - if (this.#pushListener) { - this.#database.off('job-available', this.#pushListener) - this.#pushListener = null - this.#pushListenerSetup = false - } - - // Clean up all pending job waits - for (const waits of this.#pendingJobWaits.values()) { - for (const wait of waits) { - if (wait.timeoutId) { - clearTimeout(wait.timeoutId) - } - if (wait.signal && wait.abortHandler) { - wait.signal.removeEventListener('abort', wait.abortHandler) - } - wait.resolve(null) - } - } - this.#pendingJobWaits.clear() - - // Wait for action managers to drain - await Promise.all( - Array.from(this.#actionManagers.values()).map(async (manager) => { - await manager.stop() - }), - ) - - const dbStopped = await this.#database.stop() - if (!dbStopped) { - return false + if (this.#pushListener) { + this.#database.off('job-available', this.#pushListener) + this.#pushListener = null + this.#pushListenerSetup = false + } + for (const waits of this.#pendingJobWaits.values()) { + for (const wait of waits) { + if (wait.timeoutId) clearTimeout(wait.timeoutId) + if (wait.signal && wait.abortHandler) + wait.signal.removeEventListener('abort', wait.abortHandler) + wait.resolve(null) } - - this.#stopped = true - this.#stopping = null - return true - })() - - return this.#stopping + } + this.#pendingJobWaits.clear() + return Promise.all([...this.#actionManagers.values()].map((manager) => manager.stop())).then( + () => undefined, + ) } // ============================================================================ @@ -1219,7 +1228,7 @@ export class Client< * This listener is shared across all waitForJob calls to avoid multiple listeners. */ #setupJobStatusListener() { - if (this.#jobStatusListenerSetup) { + if (this.#jobStatusListenerSetup || !this.#lifecycle.accepting) { return } @@ -1230,42 +1239,50 @@ export class Client< status: JobStatus | 'retried' clientId: string }) => { - const pendingWaits = this.#pendingJobWaits.get(event.jobId) - if (!pendingWaits || pendingWaits.size === 0) { - return - } - - // Fetch the job once for all pending waits - const job = await this.getJobById(event.jobId) - - // Transform to JobResult - const result: JobResult | null = job - ? { - id: job.id, - actionName: job.actionName, - status: job.status, - groupKey: job.groupKey, - description: job.description, - input: job.input, - output: job.output, - error: job.error, + if (!this.#lifecycle.accepting) return + return this.#lifecycle + .run(async () => { + const pendingWaits = this.#pendingJobWaits.get(event.jobId) + if (!pendingWaits || pendingWaits.size === 0) { + return } - : null - - // Resolve all pending waits for this job - const waitsToResolve = Array.from(pendingWaits) - this.#pendingJobWaits.delete(event.jobId) - for (const wait of waitsToResolve) { - // Clean up timeout and abort signal - if (wait.timeoutId) { - clearTimeout(wait.timeoutId) - } - if (wait.signal && wait.abortHandler) { - wait.signal.removeEventListener('abort', wait.abortHandler) - } - wait.resolve(result) - } + // Fetch the job once for all pending waits + const job = await this.getJobById(event.jobId) + if (!this.#lifecycle.accepting) return + + // Transform to JobResult + const result: JobResult | null = job + ? { + id: job.id, + actionName: job.actionName, + status: job.status, + groupKey: job.groupKey, + description: job.description, + input: job.input, + output: job.output, + error: job.error, + } + : null + + // Resolve all pending waits for this job + const waitsToResolve = Array.from(pendingWaits) + this.#pendingJobWaits.delete(event.jobId) + + for (const wait of waitsToResolve) { + // Clean up timeout and abort signal + if (wait.timeoutId) { + clearTimeout(wait.timeoutId) + } + if (wait.signal && wait.abortHandler) { + wait.signal.removeEventListener('abort', wait.abortHandler) + } + wait.resolve(result) + } + }) + .catch((error: unknown) => { + this.#logger.error({ error, jobId: event.jobId }, '[Duron] Status callback failed') + }) } this.#database.on('job-status-changed', this.#jobStatusListener) @@ -1309,7 +1326,7 @@ export class Client< * @param job - The job to execute */ #executeJob(job: Job) { - if (!this.#actions) { + if (!this.#actions || !this.#lifecycle.accepting) { return } @@ -1358,20 +1375,24 @@ export class Client< * to avoid overlapping calls if a heartbeat is slow. */ #scheduleHeartbeat() { - if (this.#stopped) { + if (!this.#lifecycle.accepting) { return } - this.#heartbeatTimer = setTimeout(async () => { - if (this.#stopped) { - return - } - try { - await this.#database.heartbeat() - } catch { - // Heartbeat failure is non-fatal — recovery will detect staleness - } - this.#scheduleHeartbeat() + this.#heartbeatTimer = setTimeout(() => { + if (!this.#lifecycle.accepting) return + void this.#lifecycle + .run(async () => { + try { + await this.#database.heartbeat() + } catch (error) { + this.#logger.error({ error }, '[Duron] Periodic heartbeat failed') + } + this.#scheduleHeartbeat() + }) + .catch((error: unknown) => { + this.#logger.error({ error }, '[Duron] Heartbeat callback failed') + }) }, this.#options.heartbeatInterval) } @@ -1384,22 +1405,22 @@ export class Client< return } - const pull = async () => { - if (this.#stopped) { - return - } - - try { - await this.fetch({ - batchSize: this.#options.batchSize, + const pull = () => { + if (!this.#lifecycle.accepting) return + void this.#lifecycle + .run(async () => { + try { + await this.fetch({ batchSize: this.#options.batchSize }) + } catch (error) { + this.#logger.error({ error }, '[Duron] [PullLoop] Error in pull loop') + } + if (this.#lifecycle.accepting) { + this.#pullInterval = setTimeout(pull, this.#options.pullInterval) + } + }) + .catch((error: unknown) => { + this.#logger.error({ error }, '[Duron] Pull callback failed') }) - } catch (error) { - this.#logger.error({ error }, '[Duron] [PullLoop] Error in pull loop') - } - - if (!this.#stopped) { - this.#pullInterval = setTimeout(pull, this.#options.pullInterval) - } } // Start immediately @@ -1411,18 +1432,19 @@ export class Client< * Listens for 'job-available' events and fetches jobs when notified. */ #setupPushListener() { - if (this.#pushListenerSetup) { + if (this.#pushListenerSetup || !this.#lifecycle.accepting) { return } this.#pushListenerSetup = true this.#pushListener = () => { - this.fetch({ - batchSize: 1, - }).catch((error) => { - this.#logger.error({ error }, '[Duron] [PushListener] Error fetching job') - }) + if (!this.#lifecycle.accepting) return + void this.#lifecycle + .run(() => this.fetch({ batchSize: 1 })) + .catch((error: unknown) => { + this.#logger.error({ error }, '[Duron] [PushListener] Error fetching job') + }) } this.#database.on('job-available', this.#pushListener) diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts new file mode 100644 index 0000000..0999839 --- /dev/null +++ b/packages/duron/src/lifecycle.ts @@ -0,0 +1,379 @@ +import { AsyncLocalStorage } from 'node:async_hooks' + +type Phase = 'startup settlement' | 'admitted-work drain' | 'database cleanup' | 'owned close' +type Context = { lifecycle: Lifecycle; kind: 'startup' | 'operation' | 'cleanup'; active: boolean } +const context = new AsyncLocalStorage() +const lifecycles = new WeakMap() + +// Internal only: Client, Adapter and execution managers share the adapter's ledger. +export function lifecycleFor(adapter: object): Lifecycle { + let lifecycle = lifecycles.get(adapter) + if (!lifecycle) { + lifecycle = new Lifecycle() + lifecycles.set(adapter, lifecycle) + } + return lifecycle +} + +// A deadline bounds observation, not execution. The losing promise remains observed. +class ShutdownBudget { + readonly #deadline = performance.now() + 5_000 + + constructor(readonly phase: Phase) {} + + async observe(work: Promise): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + work, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`Incomplete shutdown: ${this.phase} exceeded five seconds`)), + Math.max(0, this.#deadline - performance.now()), + ) + }), + ]) + } finally { + if (timer !== undefined) clearTimeout(timer) + } + } +} + +export function throwLifecycleErrors(errors: unknown[], message: string): void { + if (errors.length === 1) throw errors[0] + if (errors.length > 1) throw new AggregateError(errors, message) +} + +// Completion is separate from the errors observed by a particular stop attempt. +class CleanupObligation { + done = false + pending: Promise | null = null + failure: { error: unknown } | null = null + + constructor( + readonly name: string, + readonly phase: 'database cleanup' | 'owned close', + readonly execute: () => Promise, + readonly usable: () => boolean, + ) {} + + attempt(): Promise { + if (this.done) return Promise.resolve() + if (this.pending) return this.pending + if (!this.usable()) { + return Promise.reject(this.failure?.error ?? new Error(`Unresolved cleanup: ${this.name}`)) + } + this.pending = Promise.resolve() + .then(this.execute) + .then( + () => { + this.done = true + }, + (error: unknown) => { + this.failure = { error } + this.pending = null + throw error + }, + ) + return this.pending + } +} + +type LifecycleFailure = { error: unknown; phase: Phase; obligation?: string } +type StopAttempt = { + promise: Promise + failures: readonly LifecycleFailure[] + failure?: { error: unknown } +} +type Start = { + raw: Promise + outcome: Promise + started: boolean + // null means automatic cleanup is awaiting public stop override dispatch. + cleanupAttempt?: StopAttempt | null +} + +function failureContext(failures: readonly LifecycleFailure[], offset = 0): string { + return failures + .map( + (failure, index) => + `[${index + offset}] ${failure.phase}${failure.obligation ? ` (${failure.obligation})` : ''}`, + ) + .join('; ') +} + +/** + * Internal integration contract for Client, Adapter and their existing managers. + * This module is not a public configuration or resource-management API. + * + * - Obtain the same ledger with lifecycleFor(adapter); never create nested budgets. + * - start(owner, work, cleanup) tracks actual initialization separately from the + * caller's cleanup-aware outcome. Keep calls through public lifecycle overrides. + * - run(work) admits and observes the ENTIRE operation/callback promise. Pass raw + * user-handler work separately when an abort race can settle its observer first. + * Active operation contexts permit nested finalization during the drain window. + * - onQuiesce hooks synchronously remove timers/listeners, settle waits and request + * cancellation. Their asynchronous cancellation work is included in the drain. + * - accepting controls new scheduling/handler admission; assertContinuation gates + * subsequent SQL issuance. Neither gate cancels already-issued SQL or user code. + * - obligation tracks a specific cleanup promise, its positive completion and its + * last failure. Join pending work; retry only when usable permits it. Mark done + * from independent positive release evidence, not from a timeout or mere attempt. + * + * New notification/prune/wait/claim/worker mechanisms must integrate their actual + * promises and resources here, with their own native regression evidence. Do not + * add independent shutdown loops, timers or a speculative future-resource layer. + * Built-in SQL statement/transaction guards live in the SQL adapters; their pinned + * Drizzle no-cache issuance seam must be revalidated when those dependencies change. + */ +export class Lifecycle { + #terminal = false + #ordinaryOpen = true + #drained = false + #starts = new Map() + #startupWork = new Set>() + #work = new Set>() + #quiesce = new Set<() => void | Promise>() + #quiesceFailures: unknown[] = [] + #obligations = new Set() + #stopping: StopAttempt | null = null + #lastStop: StopAttempt | null = null + #phase: Phase | null = null + + get accepting(): boolean { + return !this.#terminal + } + get ordinaryOpen(): boolean { + return this.#ordinaryOpen + } + get drained(): boolean { + return this.#drained + } + get closing(): boolean { + for (const task of this.#obligations) { + if (task.phase === 'owned close' && task.pending && !task.done) return true + } + return false + } + isStarted(owner: object): boolean { + return this.#starts.get(owner)?.started ?? false + } + + onQuiesce(callback: () => void | Promise): void { + this.#quiesce.add(callback) + } + + obligation( + name: string, + phase: 'database cleanup' | 'owned close', + execute: () => Promise, + usable: () => boolean = () => true, + ): CleanupObligation { + const obligation = new CleanupObligation(name, phase, execute, usable) + this.#obligations.add(obligation) + return obligation + } + + start( + owner: object, + work: () => Promise, + cleanup: () => Promise, + ): Promise { + if (this.#terminal) return Promise.resolve(false) + let start = this.#starts.get(owner) + if (!start) { + const raw = this.#inContext('startup', async () => { + if (!this.accepting) return false + return (await work()) !== false && this.accepting + }) + this.#observe(raw, this.#startupWork) + const record: Start = { raw, outcome: Promise.resolve(false), started: false } + record.outcome = (async () => { + let started: boolean + try { + started = await raw + } catch (error) { + record.cleanupAttempt = this.#lastStop + try { + await (record.cleanupAttempt?.promise ?? cleanup()) + } catch (cleanupError) { + const attempt = record.cleanupAttempt + const report = + attempt?.failure && Object.is(attempt.failure.error, cleanupError) + ? attempt.failures + : undefined + const failures = report?.length + ? report.map((failure) => failure.error) + : [cleanupError] + const detail = report?.length + ? failureContext(report, 1) + : '[1] public cleanup override' + throwLifecycleErrors( + [error, ...failures], + `Startup and lifecycle cleanup failed: [0] startup; ${detail}`, + ) + } finally { + delete record.cleanupAttempt + } + throw error + } + if (!this.accepting) { + await (this.#lastStop?.promise ?? cleanup()) + return false + } + record.started = started + return started + })() + // Nested startup dispatch observes raw work, avoiding start -> stop -> start waits. + // Its caller-facing outcome still performs and observes automatic cleanup. + void record.outcome.catch(() => undefined) + this.#starts.set(owner, record) + start = record + } + const caller = context.getStore() + return caller?.lifecycle === this && caller.active ? start.raw : start.outcome + } + + run(work: () => Promise): Promise { + const caller = context.getStore() + if ( + !this.#ordinaryOpen || + (this.#terminal && + !(caller?.lifecycle === this && caller.active && caller.kind === 'operation')) + ) { + return Promise.reject(new Error('Lifecycle is not accepting work')) + } + const promise = this.#inContext('operation', work) + this.#observe(promise, this.#work) + return promise + } + + assertContinuation(): void { + const caller = context.getStore() + if ( + caller?.lifecycle === this && + caller.active && + caller.kind === 'cleanup' && + this.#phase === 'database cleanup' && + !this.closing + ) + return + if (!this.#ordinaryOpen) throw new Error('Lifecycle ordinary work has drained') + } + + quiesce(): void { + if (this.#terminal) return + this.#terminal = true + for (const callback of this.#quiesce) { + const token: Context = { lifecycle: this, kind: 'operation', active: true } + let work: Promise + try { + work = Promise.resolve(context.run(token, callback)) + } catch (error) { + work = Promise.reject(error) + } + const completion = work + .catch((error: unknown) => { + this.#quiesceFailures.push(error) + }) + .finally(() => { + token.active = false + }) + this.#observe(completion, this.#work) + } + } + + stop(): Promise { + if (this.#stopping) return this.#stopping.promise + // Install before invoking quiesce hooks, which may reenter public lifecycle calls. + const attempt: StopAttempt = { promise: Promise.resolve(false), failures: [] } + attempt.promise = Promise.resolve() + .then(() => this.#cleanup(attempt)) + .catch((error: unknown) => { + attempt.failure = { error } + throw error + }) + .finally(() => { + this.#stopping = null + }) + this.#stopping = attempt + this.#lastStop = attempt + for (const start of this.#starts.values()) { + if (start.cleanupAttempt === null) start.cleanupAttempt = attempt + } + this.quiesce() + return attempt.promise + } + + async #cleanup(attempt: StopAttempt): Promise { + const failures: LifecycleFailure[] = [] + await this.#settlePhase('startup settlement', this.#startupWork, failures) + this.#drained = await this.#settlePhase('admitted-work drain', this.#work, failures) + this.#ordinaryOpen = false + failures.push( + ...this.#quiesceFailures.map( + (error): LifecycleFailure => ({ error, phase: 'admitted-work drain' }), + ), + ) + for (const phase of ['database cleanup', 'owned close'] as const) { + const obligations = [...this.#obligations].filter( + (task) => task.phase === phase && !task.done, + ) + if (!obligations.length) continue + this.#phase = phase + const budget = new ShutdownBudget(phase) + const work = obligations.map((task) => + this.#inContext('cleanup', () => task.attempt()).catch((error: unknown) => { + failures.push({ error, phase, obligation: task.name }) + }), + ) + await budget.observe(Promise.all(work)).catch((error: unknown) => { + failures.push({ error, phase }) + }) + } + this.#phase = null + // Late settlement updates obligations, not the already-reported attempt snapshot. + attempt.failures = failures.slice() + throwLifecycleErrors( + attempt.failures.map((failure) => failure.error), + `Lifecycle cleanup failed: ${failureContext(attempt.failures)}`, + ) + return true + } + + async #settlePhase( + phase: Phase, + pending: Set>, + failures: LifecycleFailure[], + ): Promise { + if (!pending.size) return true + this.#phase = phase + const settle = async () => { + while (pending.size) await Promise.allSettled(pending) + } + try { + await new ShutdownBudget(phase).observe(settle()) + return true + } catch (error) { + failures.push({ error, phase }) + return false + } + } + + #observe(work: Promise, pending: Set>): void { + pending.add(work) + void work.then( + () => pending.delete(work), + () => pending.delete(work), + ) + } + + #inContext(kind: Context['kind'], work: () => Promise): Promise { + const token: Context = { lifecycle: this, kind, active: true } + return Promise.resolve() + .then(() => context.run(token, work)) + .finally(() => { + token.active = false + }) + } +} diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index e2fa9ce..c6ba543 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -40,6 +40,7 @@ import { serializeError, UnhandledChildStepsError, } from './errors.js' +import { type Lifecycle, lifecycleFor } from './lifecycle.js' import { validateSchema } from './standard-schema.js' /** @@ -302,6 +303,7 @@ export class StepManager { #jobId: string #actionName: string #stepStore: StepStore + #lifecycle: Lifecycle #tracer: Tracer #queue: fastq.queueAsPromised #logger: Logger @@ -331,6 +333,7 @@ export class StepManager { this.#logger = options.logger this.#tracer = options.tracer this.#stepStore = new StepStore(options.adapter) + this.#lifecycle = lifecycleFor(options.adapter) this.#queue = fastq.promise(async (task: TaskStep) => { // Create composite key: name + parentStepId (allows same name under different parents) const stepKey = `${task.parentStepId ?? 'root'}:${task.name}` @@ -338,13 +341,15 @@ export class StepManager { throw new StepAlreadyExecutedError(task.name, this.#jobId, this.#actionName) } this.#historySteps.add(stepKey) - return this.#executeStep( - task.name, - task.cb, - task.options, - task.abortSignal, - task.parentStepId, - task.parallel, + return this.#lifecycle.run(() => + this.#executeStep( + task.name, + task.cb, + task.options, + task.abortSignal, + task.parentStepId, + task.parallel, + ), ) }, options.concurrencyLimit) } @@ -657,7 +662,20 @@ export class StepManager { const spanContext = currentStepSpan ? trace.setSpan(context.active(), currentStepSpan) : context.active() - const callbackPromise = context.with(spanContext, () => cb(stepContext)) + if (!this.#lifecycle.accepting) { + throw new ActionCancelError(this.#actionName, this.#jobId) + } + stepSignal.throwIfAborted() + const callbackPromise = this.#lifecycle.run(() => + context.with(spanContext, () => { + // Recheck at actual invocation, after the ledger's queued continuation. + if (!this.#lifecycle.accepting) { + throw new ActionCancelError(this.#actionName, this.#jobId) + } + stepSignal.throwIfAborted() + return cb(stepContext) + }), + ) let result: any = null let aborted = false diff --git a/packages/duron/test/client.test.ts b/packages/duron/test/client.test.ts index 930deb0..a6090af 100644 --- a/packages/duron/test/client.test.ts +++ b/packages/duron/test/client.test.ts @@ -1108,10 +1108,14 @@ function runClientTests(adapterFactory: AdapterFactory) { expect(job1.status).toBe(JOB_STATUS_ACTIVE) // Manually expire the job by setting expires_at to the past - const adapter = databaseInstance.adapter as any - await adapter.db.execute( - `UPDATE jobs_active SET expires_at = NOW() - INTERVAL '1 minute', client_id = 'concurrency-client-2' WHERE id = '${jobId1}'`, - ) + const adapter = databaseInstance.adapter as Adapter & { + db: { execute: (query: SQL) => Promise } + } + await adapter.db.execute(sql` + UPDATE duron.jobs_active + SET expires_at = NOW() - INTERVAL '1 minute', client_id = 'concurrency-client-2' + WHERE id = ${jobId1} + `) // Create another job for the same group const jobId2 = await concurrencyClient.runAction('expiredConcurrencyAction', { diff --git a/packages/duron/test/heartbeat-clock.test.ts b/packages/duron/test/heartbeat-clock.test.ts new file mode 100644 index 0000000..d0df4af --- /dev/null +++ b/packages/duron/test/heartbeat-clock.test.ts @@ -0,0 +1,239 @@ +import { describe, expect, it } from 'bun:test' + +import { type SQL, sql } from 'drizzle-orm' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +type SqlFixture = { + execute: (query: SQL) => Promise + insert: (...args: unknown[]) => unknown +} +type ClockProbe = Adapter & { + tables: { clientsTable: { last_seen_at: { mapToDriverValue: (value: Date) => string } } } + db: SqlFixture & { + transaction: (work: (tx: SqlFixture) => Promise) => Promise + $client: { + closed?: boolean + close?: () => Promise + end?: (options: { timeout: number }) => Promise + } + } +} + +async function rows(db: SqlFixture, query: SQL): Promise { + const result = await db.execute(query) + return (Array.isArray(result) ? result : (result as { rows: unknown[] }).rows) as T[] +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Heartbeat SQL clock with ${factory.name}`, () => { + it('keeps insert and update SQL-sourced across scoped application-Date offsets and jumps', async () => { + const instance = await factory.create() + const adapter = instance.adapter as ClockProbe + adapter.setId('clock-offset') + const column = adapter.tables.clientsTable.last_seen_at + const mapDate = column.mapToDriverValue.bind(column) + let offset = 0 + let applicationDateBindings = 0 + // Labelled app-value seam: only this column's Date-to-SQL binding is offset. + // Global Date, native timers and the engine clock remain unchanged. SQL + // expressions bypass this mapper, unlike the former two application Dates. + column.mapToDriverValue = (value) => { + applicationDateBindings++ + return mapDate(new Date(value.getTime() + offset)) + } + try { + await adapter.start() + for (offset of [-60_000, 0, 60_000, -120_000, 120_000, 0]) { + for (const branch of ['insert', 'update'] as const) { + if (branch === 'insert') { + await adapter.db.execute( + sql`DELETE FROM duron.clients WHERE client_id = 'clock-offset'`, + ) + } else { + // A normal heartbeat may overwrite a legacy future value backwards. + await adapter.db.execute(sql` + UPDATE duron.clients SET last_seen_at = now() + interval '1 day' + WHERE client_id = 'clock-offset' + `) + } + const [before] = await rows<{ us: string }>( + adapter.db, + sql` + SELECT (extract(epoch FROM clock_timestamp()) * 1000000)::bigint::text AS us + `, + ) + await adapter.heartbeat() + const [stored] = await rows<{ seen: string; observed: string; fresh: boolean }>( + adapter.db, + sql` + SELECT (extract(epoch FROM last_seen_at) * 1000000)::bigint::text AS seen, + (extract(epoch FROM clock_timestamp()) * 1000000)::bigint::text AS observed, + last_seen_at > now() - interval '15 seconds' AS fresh + FROM duron.clients WHERE client_id = 'clock-offset' + `, + ) + expect(BigInt(stored!.seen)).toBeGreaterThanOrEqual(BigInt(before!.us)) + expect(BigInt(stored!.seen)).toBeLessThanOrEqual(BigInt(stored!.observed)) + expect(stored!.fresh).toBe(true) + } + } + expect(applicationDateBindings).toBe(0) + } finally { + column.mapToDriverValue = mapDate + await adapter.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('uses exact frozen transaction now for both branches rather than statement or commit time', async () => { + const instance = await factory.create() + const adapter = instance.adapter as ClockProbe + adapter.setId('clock-frozen') + const insert = adapter.db.insert.bind(adapter.db) + try { + await adapter.start() + // Labelled frozen-reference fixture: route only the heartbeat builder to + // an owned transaction, then invoke the unchanged public heartbeat path. + await adapter.db.transaction(async (tx) => { + adapter.db.insert = tx.insert.bind(tx) + try { + await tx.execute(sql`SELECT now()`) + await Bun.sleep(30) + for (const branch of ['insert', 'update'] as const) { + if (branch === 'update') { + await tx.execute(sql` + UPDATE duron.clients SET last_seen_at = now() + interval '1 day' + WHERE client_id = 'clock-frozen' + `) + } + await adapter.heartbeat() + const [stored] = await rows<{ exact: boolean; advanced: boolean }>( + tx, + sql` + SELECT last_seen_at = now() AS exact, + clock_timestamp() > now() + interval '10 milliseconds' AS advanced + FROM duron.clients WHERE client_id = 'clock-frozen' + `, + ) + expect(stored).toEqual({ exact: true, advanced: true }) + } + } finally { + adapter.db.insert = insert + } + }) + } finally { + adapter.db.insert = insert + await adapter.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('preserves native microsecond freshness equality, owner selection and timeout boundaries', async () => { + const instance = await factory.create() + const adapter = instance.adapter as ClockProbe + adapter.setId('clock-own') + const execute = adapter.db.execute.bind(adapter.db) + const owners = [ + 'clock-minus', + 'clock-equal', + 'clock-plus', + 'clock-missing', + 'clock-own', + null, + ] + const ids: string[] = [] + try { + await adapter.start() + for (const owner of owners) { + const id = await adapter.createJob({ + queue: 'clock-boundary', + groupKey: String(owner), + input: {}, + timeoutMs: 30_000, + checksum: 'clock-boundary', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + ids.push(id!) + } + for (const timeout of [undefined, 1000, 0]) { + const milliseconds = timeout ?? 15_000 + // This fixture freezes all predicate references. Ordinary recovery is + // still multi-statement and receives no new snapshot/consistency promise. + await adapter.db.transaction(async (tx) => { + adapter.db.execute = tx.execute.bind(tx) + try { + for (const [index, owner] of owners.entries()) { + await tx.execute(sql` + UPDATE duron.jobs_active SET status = 'active', client_id = ${owner}, expires_at = NULL + WHERE id = ${ids[index]} + `) + } + await tx.execute(sql`DELETE FROM duron.clients`) + await tx.execute(sql` + INSERT INTO duron.clients (client_id, last_seen_at) VALUES + ('clock-minus', now() - (${milliseconds} * interval '1 millisecond') - interval '1 microsecond'), + ('clock-equal', now() - (${milliseconds} * interval '1 millisecond')), + ('clock-plus', now() - (${milliseconds} * interval '1 millisecond') + interval '1 microsecond'), + ('clock-own', now() + interval '1 day') + `) + const fractions = await rows<{ client_id: string; delta: string }>( + tx, + sql` + SELECT client_id, + (extract(epoch FROM (last_seen_at - (now() - (${milliseconds} * interval '1 millisecond')))) * 1000000)::bigint::text AS delta + FROM duron.clients WHERE client_id != 'clock-own' ORDER BY client_id + `, + ) + expect(fractions).toEqual([ + { client_id: 'clock-equal', delta: '0' }, + { client_id: 'clock-minus', delta: '-1' }, + { client_id: 'clock-plus', delta: '1' }, + ]) + expect( + await adapter.recoverJobs({ + checksums: ['clock-boundary'], + staleTimeoutMs: timeout, + }), + ).toBe(4) + const states = await rows<{ id: string; status: string }>( + tx, + sql` + SELECT id, status FROM duron.jobs_active + `, + ) + const byId = new Map(states.map((row) => [row.id, row.status])) + expect(ids.map((id) => byId.get(id))).toEqual([ + 'created', + 'created', + 'active', + 'created', + 'created', + 'active', + ]) + } finally { + adapter.db.execute = execute + } + }) + } + } finally { + adapter.db.execute = execute + await adapter.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + }) +} diff --git a/packages/duron/test/lifecycle-background.test.ts b/packages/duron/test/lifecycle-background.test.ts new file mode 100644 index 0000000..f7fb5b5 --- /dev/null +++ b/packages/duron/test/lifecycle-background.test.ts @@ -0,0 +1,150 @@ +import { describe, expect, it } from 'bun:test' + +import type { SQL } from 'drizzle-orm' + +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +type BackgroundProbe = Adapter & { + _close: () => Promise + db: { + execute: (query: SQL) => Promise + dialect: { sqlToQuery: (query: SQL) => { sql: string } } + $client: { + closed?: boolean + close?: () => Promise + end?: (options: { timeout: number }) => Promise + } + } +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Lifecycle background work with ${factory.name}`, () => { + it('logs periodic heartbeat failure, retries at normal cadence, and does not poison stop', async () => { + const instance = await factory.create() + const adapter = instance.adapter as BackgroundProbe + const heartbeat = adapter.heartbeat.bind(adapter) + const failure = new Error('injected periodic heartbeat failure') + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const calls: number[] = [] + const reports: Array<{ fields: unknown; message: unknown }> = [] + const client = new Client({ + id: 'periodic-error', + database: adapter, + syncPattern: false, + heartbeatInterval: 30, + logger: 'silent', + }) + client.logger.error = (fields: unknown, message?: unknown) => { + reports.push({ fields, message }) + } + adapter.heartbeat = async () => { + calls.push(performance.now()) + if (calls.length === 2) throw failure + if (calls.length === 3) { + entered.resolve() + await release.promise + } + await heartbeat() + } + try { + expect(await client.start()).toBe(true) + await entered.promise + expect(reports).toEqual([ + { + fields: { error: failure }, + message: '[Duron] Periodic heartbeat failed', + }, + ]) + expect(calls[2]! - calls[1]!).toBeGreaterThanOrEqual(25) + expect(await client.start()).toBe(true) + const stopped = client.stop() + release.resolve() + expect(await stopped).toBe(true) + expect(calls).toHaveLength(3) + } finally { + release.resolve() + await client.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + for (const [name, target] of [ + ['initial', 1], + ['periodic', 2], + ] as const) { + it(`drains the actual ${name} prune callback and stops its timer immediately`, async () => { + const instance = await factory.create({ + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + const adapter = instance.adapter as BackgroundProbe + adapter.setId(`prune-${name}`) + const execute = adapter.db.execute.bind(adapter.db) + const close = adapter._close.bind(adapter) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + let lockCalls = 0 + let closeCalls = 0 + let timer: ReturnType | undefined + let stopped: Promise | undefined + // A labelled callback hold AFTER the native lock query settled. This does + // not claim new prune-lock correctness or cancel an already-issued query. + adapter.db.execute = async (query) => { + const result = await execute(query) + if ( + adapter.db.dialect.sqlToQuery(query).sql.includes('pg_try_advisory_lock') && + ++lockCalls === target + ) { + entered.resolve() + await release.promise + } + return result + } + adapter._close = async () => { + closeCalls++ + await close() + } + try { + await adapter.start() + await entered.promise + stopped = adapter.stop() + const state = await Promise.race([ + stopped.then( + () => 'stopped', + () => 'rejected', + ), + new Promise((resolve) => { + timer = setTimeout(() => resolve('draining'), 100) + }), + ]) + expect(state).toBe('draining') + expect(closeCalls).toBe(0) + expect(lockCalls).toBe(target) + release.resolve() + expect(await stopped).toBe(true) + expect(closeCalls).toBe(1) + expect(lockCalls).toBe(target) + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await stopped?.catch(() => undefined) + adapter.db.execute = execute + adapter._close = close + await adapter.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + } + }) +} diff --git a/packages/duron/test/lifecycle-budgets.test.ts b/packages/duron/test/lifecycle-budgets.test.ts new file mode 100644 index 0000000..141bde1 --- /dev/null +++ b/packages/duron/test/lifecycle-budgets.test.ts @@ -0,0 +1,172 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import type { GetJobsOptions, GetJobsResult } from '../src/adapters/adapter.js' +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +type BudgetProbe = Adapter & { + _start: () => Promise + _stop: () => Promise + _close: () => Promise + _getJobs: (options: GetJobsOptions) => Promise + _listen: ( + event: string, + callback: (payload: string) => void, + ) => Promise<{ + unlisten: () => void | Promise + }> + db: { + $client: { + closed?: boolean + close?: () => Promise + end?: (options: { timeout: number }) => Promise + } + } +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Shared lifecycle budgets with ${factory.name}`, () => { + it('shares four phase-wide budgets across Client and Adapter and reserves every later phase', async () => { + const instance = await factory.create() + const adapter = instance.adapter as BudgetProbe + const client = new Client({ + id: 'four-budgets', + database: adapter, + syncPattern: false, + logger: 'silent', + }) + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + const startupEntered = Promise.withResolvers() + const ordinaryEntered = Promise.withResolvers() + const startupRelease = Promise.withResolvers() + const ordinaryRelease = Promise.withResolvers() + const cleanupRelease = Promise.withResolvers() + const closeRelease = Promise.withResolvers() + const start = adapter._start.bind(adapter) + const stop = adapter._stop.bind(adapter) + const close = adapter._close.bind(adapter) + const getJobs = adapter._getJobs.bind(adapter) + const listen = adapter._listen.bind(adapter) + let starts = 0 + let cleanups = 0 + let closes = 0 + let unlistens = 0 + let firstListener = true + let timer: ReturnType | undefined + let operation: Promise | undefined + adapter._start = async () => { + starts++ + await start() + startupEntered.resolve() + await startupRelease.promise + } + adapter._getJobs = async (options) => { + const result = await getJobs(options) + ordinaryEntered.resolve() + await ordinaryRelease.promise + return result + } + adapter._listen = async (event, callback) => { + const handle = await listen(event, callback) + const held = firstListener + firstListener = false + return { + unlisten: async () => { + unlistens++ + await handle.unlisten() + if (held) await cleanupRelease.promise + }, + } + } + adapter._stop = async () => { + cleanups++ + await stop() + } + adapter._close = async () => { + closes++ + await close() + await closeRelease.promise + } + const started = client.start() + void started.catch(() => undefined) + try { + await startupEntered.promise + operation = adapter.getJobs({}) + await ordinaryEntered.promise + const first = client.stop().catch((error: unknown) => error) + const concurrent = client.stop().catch((error: unknown) => error) + const nested = adapter.stop().catch((error: unknown) => error) + const result = await Promise.race([ + first, + new Promise((resolve) => { + timer = setTimeout(() => resolve('observer deadline'), 23_000) + }), + ]) + // An observation threshold in this controlled test, not a wall-clock SLA. + expect(result).toBeInstanceOf(AggregateError) + expect(await concurrent).toBe(result) + expect(await nested).toBe(result) + const failures = (result as AggregateError).errors + for (const phase of [ + 'startup settlement', + 'admitted-work drain', + 'database cleanup', + 'owned close', + ]) { + expect( + failures.some((error) => String(error).includes(`${phase} exceeded five seconds`)), + ).toBe(true) + } + const withheld = failures.find((error) => + String(error).includes('Liveness release withheld'), + ) + expect(withheld).toBeInstanceOf(Error) + expect(starts).toBe(1) + expect(cleanups).toBe(1) + expect(unlistens).toBe(2) + expect(closes).toBe(1) + if (observer) { + const sessions = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions[0]!['count']).toBe(0) + } else expect(adapter.db.$client.closed).toBe(true) + + startupRelease.resolve() + ordinaryRelease.resolve() + cleanupRelease.resolve() + closeRelease.resolve() + await expect(started).rejects.toBe(result) + await operation + // Late positive completion does not repair a deliberately withheld row release + // after SQL has closed, and does not repeat successful resource work. + await expect(client.stop()).rejects.toBe(withheld) + expect(cleanups).toBe(1) + expect(unlistens).toBe(2) + expect(closes).toBe(1) + } finally { + if (timer !== undefined) clearTimeout(timer) + startupRelease.resolve() + ordinaryRelease.resolve() + cleanupRelease.resolve() + closeRelease.resolve() + await started.catch(() => undefined) + await operation?.catch(() => undefined) + await client.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 40_000) + }) +} diff --git a/packages/duron/test/lifecycle-close-retry.test.ts b/packages/duron/test/lifecycle-close-retry.test.ts new file mode 100644 index 0000000..7532c81 --- /dev/null +++ b/packages/duron/test/lifecycle-close-retry.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from 'bun:test' + +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +type Row = Record +type CloseProbe = Adapter & { + _stop: () => Promise + _close: () => Promise + db: { + $client: { + query?: (text: string) => Promise<{ rows: Row[] }> + unsafe?: (text: string) => PromiseLike + closed?: boolean + close?: () => Promise + end?: (options: { timeout: number }) => Promise + } + } +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Pending close retry with ${factory.name}`, () => { + it('does not restart database cleanup while owned close is pending, but retries after a before-release failure', async () => { + const instance = await factory.create() + const adapter = instance.adapter as CloseProbe + const client = new Client({ + id: 'pending-close', + database: adapter, + syncPattern: false, + logger: 'silent', + }) + const cleanup = adapter._stop.bind(adapter) + const close = adapter._close.bind(adapter) + const cleanupFailure = new Error('injected first cleanup failure') + const closeFailure = new Error('injected close failure before native release') + const release = Promise.withResolvers() + const driver = adapter.db.$client + const nativeCount = async () => { + const statement = + "SELECT count(*)::int AS count FROM duron.clients WHERE client_id = 'pending-close'" + const rows = driver.query + ? (await driver.query(statement)).rows + : await driver.unsafe!(statement) + return rows[0]?.['count'] + } + let cleanupCalls = 0 + let closeCalls = 0 + let beforeActualClose: unknown + let second: Promise | undefined + let timer: ReturnType | undefined + adapter._stop = async () => { + if (++cleanupCalls === 1) throw cleanupFailure + await cleanup() + } + adapter._close = async () => { + if (++closeCalls === 1) { + await release.promise + throw closeFailure + } + beforeActualClose = await nativeCount() + await close() + } + try { + await client.start() + const first = await client.stop().catch((error: unknown) => error) + expect(first).toBeInstanceOf(AggregateError) + expect((first as AggregateError).errors).toContain(cleanupFailure) + expect( + (first as AggregateError).errors.some((error) => + String(error).includes('owned close exceeded'), + ), + ).toBe(true) + second = client.stop().catch((error: unknown) => error) + const state = await Promise.race([ + second.then(() => 'settled'), + new Promise((resolve) => { + timer = setTimeout(() => resolve('pending'), 100) + }), + ]) + expect(state).toBe('pending') + // The labelled close hold has not released the engine. No cleanup SQL may + // restart merely because another stop entered its database-cleanup phase. + expect(await nativeCount()).toBe(1) + expect(cleanupCalls).toBe(1) + expect(closeCalls).toBe(1) + release.resolve() + const retryFailure = await second + expect(retryFailure).toBeInstanceOf(AggregateError) + expect((retryFailure as AggregateError).errors).toEqual([cleanupFailure, closeFailure]) + expect(await client.stop()).toBe(true) + expect(cleanupCalls).toBe(2) + expect(closeCalls).toBe(2) + expect(beforeActualClose).toBe(0) + expect(await client.start()).toBe(false) + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await second?.catch(() => undefined) + adapter._stop = cleanup + adapter._close = close + await client.stop().catch(() => undefined) + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + }) +} diff --git a/packages/duron/test/lifecycle-errors.test.ts b/packages/duron/test/lifecycle-errors.test.ts new file mode 100644 index 0000000..bcb9015 --- /dev/null +++ b/packages/duron/test/lifecycle-errors.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from 'bun:test' + +import { type SQL, sql } from 'drizzle-orm' +import postgres from 'postgres' + +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +type ErrorProbe = Adapter & { + _start: () => Promise + _stop: () => Promise + _close: () => Promise + db: { + execute: (query: SQL) => Promise + $client: { + closed?: boolean + close?: () => Promise + end?: (options: { timeout: number }) => Promise + } + } +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Lifecycle errors with ${factory.name}`, () => { + it('does not suppress an expected-relation absence after successful initialization', async () => { + const instance = await factory.create() + const adapter = instance.adapter as ErrorProbe + const client = new Client({ + id: 'missing-after-start', + database: adapter, + syncPattern: false, + logger: 'silent', + }) + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + try { + await client.start() + // Native fault confined to this test's owned database/engine. + await adapter.db.execute(sql`DROP TABLE duron.clients`) + const failure = await client.stop().catch((error: unknown) => error) + expect(failure).toBeInstanceOf(Error) + expect((failure as Error).cause).toMatchObject({ code: '42P01' }) + await expect(client.stop()).rejects.toBe(failure) + if (observer) { + const sessions = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions[0]!['count']).toBe(0) + } else expect(adapter.db.$client.closed).toBe(true) + } finally { + await client.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + for (const mode of ['stop', 'start-one', 'start-many', 'start-aggregate'] as const) { + it(`preserves original errors with indexed phase context for ${mode}`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as ErrorProbe + const client = new Client({ + id: `phase-${mode}`, + database: adapter, + syncPattern: false, + logger: 'silent', + }) + const cleanup = adapter._stop.bind(adapter) + const close = adapter._close.bind(adapter) + const startupFailure = new Error('injected initial heartbeat') + const cleanupFailure = + mode === 'start-aggregate' + ? new AggregateError([new Error('nested original error')], 'injected cleanup aggregate') + : new Error('injected cleanup') + const closeFails = mode === 'stop' || mode === 'start-many' + const closeFailure = new Error('injected after owned close') + try { + if (mode === 'stop') await client.start() + else + adapter.heartbeat = async () => { + throw startupFailure + } + adapter._stop = async () => { + throw cleanupFailure + } + adapter._close = async () => { + await close() + if (closeFails) throw closeFailure + } + const result = await (mode === 'stop' ? client.stop() : client.start()).catch( + (error: unknown) => error, + ) + expect(result).toBeInstanceOf(AggregateError) + const errors = + mode === 'stop' + ? [cleanupFailure, closeFailure] + : closeFails + ? [startupFailure, cleanupFailure, closeFailure] + : [startupFailure, cleanupFailure] + expect((result as AggregateError).errors).toEqual(errors) + const firstCleanup = mode === 'stop' ? 0 : 1 + if (mode !== 'stop') expect(String(result)).toContain('[0] startup') + expect(String(result)).toContain( + `[${firstCleanup}] database cleanup (adapter database cleanup)`, + ) + if (closeFails) { + expect(String(result)).toContain( + `[${firstCleanup + 1}] owned close (adapter owned resources)`, + ) + } + adapter._stop = cleanup + adapter._close = close + // The stop caller never receives the historical startup failure. + await expect(client.stop()).rejects.toBe(cleanupFailure) + } finally { + adapter._stop = cleanup + adapter._close = close + await client.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + } + + for (const attemptStart of [false, true]) { + it(`closes an adapter without an ID after ${attemptStart ? 'failed startup' : 'construction'}`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as ErrorProbe + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + try { + if (attemptStart) { + const failure = await adapter.start().catch((error: unknown) => error) + expect(failure).toBeInstanceOf(Error) + expect(failure).not.toBeInstanceOf(AggregateError) + expect((failure as Error).message).toBe('Adapter ID is not set') + } + expect(await adapter.stop()).toBe(true) + expect(await adapter.stop()).toBe(true) + expect(await adapter.start()).toBe(false) + if (observer) { + const sessions = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions[0]!['count']).toBe(0) + } else expect(adapter.db.$client.closed).toBe(true) + } finally { + await adapter.stop().catch(() => undefined) + const driver = adapter.db.$client + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + } + }) +} diff --git a/packages/duron/test/lifecycle-handler-entry.test.ts b/packages/duron/test/lifecycle-handler-entry.test.ts new file mode 100644 index 0000000..100982e --- /dev/null +++ b/packages/duron/test/lifecycle-handler-entry.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { defineAction } from '../src/action.js' +import { Client } from '../src/client.js' +import { lifecycleFor } from '../src/lifecycle.js' + +import { pgliteFactory, postgresFactory } from './adapters.js' + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`User-handler entry with ${factory.name}`, () => { + for (const kind of ['action', 'step'] as const) { + it(`does not invoke the ${kind} callback when stop wins the tracked invocation microtask`, async () => { + const instance = await factory.create() + const lifecycle = lifecycleFor(instance.adapter) + const originalRun = lifecycle.run + const run = originalRun.bind(lifecycle) + const injected = Promise.withResolvers() + let preparing = false + let armed = false + let injections = 0 + let calls = 0 + const entryStates: boolean[] = [] + let stopped: Promise | undefined + const action = defineAction()({ + name: 'entry-control', + input: { + '~standard': { + version: 1 as const, + vendor: 'entry-control', + validate(value: unknown) { + // Enqueue validation is finished before preparing is enabled. + // Context validation is the last async preparation before action entry. + if (preparing && kind === 'action') armed = true + return { value } + }, + }, + }, + handler: async (ctx) => { + if (kind === 'action') { + calls++ + entryStates.push(lifecycle.accepting) + return + } + await ctx.step('entry-step', async () => { + calls++ + entryStates.push(lifecycle.accepting) + }) + }, + }) + const clientId = `entry-${kind}` + const client = new Client({ + id: clientId, + database: instance.adapter, + actions: { action }, + syncPattern: false, + recoverJobsOnStart: false, + heartbeatInterval: 60_000, + logger: 'error', + }) + const debug = client.logger.debug + client.logger.debug = ((...args: unknown[]) => { + // This diagnostic is immediately before synchronous step-context setup + // and the callback checks. No global/prototype instrumentation is used. + if (kind === 'step' && args[1] === '[StepManager] Step started executing') armed = true + }) as typeof debug + lifecycle.run = (work: () => Promise) => { + if (armed) { + armed = false + injections++ + // Queue real public stop before the real ledger queues work. Do not + // replace, delay, resolve or fake the actual handler/ledger promise. + queueMicrotask(() => { + stopped = client.stop() + void stopped.catch(() => undefined) + injected.resolve() + }) + } + return run(work) + } + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + try { + await client.start() + await client.runAction('action', {}) + preparing = true + const watchdog = setTimeout( + () => injected.reject(new Error('Handler entry control was not reached')), + 5_000, + ) + try { + await Promise.all([client.fetch(), injected.promise]) + } finally { + clearTimeout(watchdog) + } + expect(injections).toBe(1) + expect(await stopped).toBe(true) + expect(entryStates).toEqual([]) + expect(calls).toBe(0) + if (observer) { + const sessions = + await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + expect(sessions[0]!['count']).toBe(0) + const rows = + await observer`SELECT count(*)::int AS count FROM duron.clients WHERE client_id = ${clientId}` + expect(rows[0]!['count']).toBe(0) + } else { + const native = instance.adapter as unknown as { db: { $client: { closed: boolean } } } + expect(native.db.$client.closed).toBe(true) + } + } finally { + lifecycle.run = originalRun + client.logger.debug = debug + await client.stop().catch(() => undefined) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + } + }) +} diff --git a/packages/duron/test/lifecycle-listeners.test.ts b/packages/duron/test/lifecycle-listeners.test.ts new file mode 100644 index 0000000..6ea9399 --- /dev/null +++ b/packages/duron/test/lifecycle-listeners.test.ts @@ -0,0 +1,282 @@ +import { describe, expect, it } from 'bun:test' + +import type { PGlite } from '@electric-sql/pglite' + +import { type Adapter, pgliteFactory } from './adapters.js' + +type ListenerProbe = Adapter & { + _listen: ( + event: string, + callback: (payload: string) => void, + ) => Promise<{ + unlisten: () => void | Promise + }> + db: { $client: PGlite } +} + +// Native protected-listener probes isolate the approved listener mechanism from +// emission policy (issue06) and do not claim full custom-schema migrations. +describe('PGLite lifecycle listener ownership', () => { + it('keeps a replacement listener when its quote reply settles before queued unsubscribe SQL', async () => { + const instance = await pgliteFactory.create() + const adapter = instance.adapter as ListenerProbe + const engine = adapter.db.$client + const query = engine.query.bind(engine) + const channel = 'duron.replacement' + const first: string[] = [] + const second: string[] = [] + const quote = Promise.withResolvers>>() + try { + const previous = await adapter._listen('replacement', (payload) => first.push(payload)) + const nativeQuote = await query('SELECT quote_ident($1) AS identifier', [channel]) + let held = false + // Hold only a quote reply with the exact result already produced by native SQL. + // Resolving it queues registration before unsubscribe's deferred SQL issuance. + engine.query = ((...args: Parameters) => { + if (args[0] === 'SELECT quote_ident($1) AS identifier' && !held) { + held = true + expect(args[1]).toEqual([channel]) + return quote.promise + } + return query(...args) + }) as PGlite['query'] + const replacing = adapter._listen('replacement', (payload) => second.push(payload)) + expect(held).toBe(true) + quote.resolve(nativeQuote) + const removing = previous.unlisten() + const replacement = await replacing + await removing + const channels = await query<{ channel: string }>('SELECT pg_listening_channels() AS channel') + expect(channels.rows.map((row) => row.channel)).toContain(channel) + await query('SELECT pg_notify($1, $2)', [channel, 'replacement only']) + expect(first).toEqual([]) + expect(second).toEqual(['replacement only']) + await replacement.unlisten() + const after = await query<{ channel: string }>('SELECT pg_listening_channels() AS channel') + expect(after.rows.map((row) => row.channel)).not.toContain(channel) + } finally { + engine.query = query + await adapter.stop().catch(() => undefined) + if (!engine.closed) await engine.close() + await instance.deleteDb() + } + }) + + it('discharges listener resources on positive native closure even when the close reply rejects', async () => { + const instance = await pgliteFactory.create() + const adapter = instance.adapter as ListenerProbe + adapter.setId('closed-rejected-reply') + const engine = adapter.db.$client + const close = engine.close.bind(engine) + const listen = adapter._listen.bind(adapter) + const unlistenFailure = new Error('injected explicit unlisten failure') + const closeFailure = new Error('injected rejection AFTER native close') + let registrations = 0 + let unlistens = 0 + let closes = 0 + adapter._listen = async (event, callback) => { + const handle = await listen(event, callback) + const first = registrations++ === 0 + return { + unlisten: async () => { + unlistens++ + if (first) throw unlistenFailure + await handle.unlisten() + }, + } + } + engine.close = async () => { + closes++ + await close() + expect(engine.closed).toBe(true) + throw closeFailure + } + try { + await adapter.start() + const failure = await adapter.stop().catch((error: unknown) => error) + expect(failure).toBeInstanceOf(AggregateError) + expect((failure as AggregateError).errors).toEqual([unlistenFailure, closeFailure]) + expect(engine.closed).toBe(true) + expect(unlistens).toBe(2) + expect(closes).toBe(1) + expect(await adapter.stop()).toBe(true) + expect(unlistens).toBe(2) + expect(closes).toBe(1) + } finally { + engine.close = close + adapter._listen = listen + await adapter.stop().catch(() => undefined) + if (!engine.closed) await close() + await instance.deleteDb() + } + }) + + it('uses exact quoted channels and releases callbacks independently of SQL subscriptions', async () => { + const instance = await pgliteFactory.create({ schema: 'Listen."λ', migrateOnStart: false }) + const adapter = instance.adapter as ListenerProbe + adapter.setId('listener-native') + const engine = adapter.db.$client + const channel = 'Listen."λ.job-available' + const first: string[] = [] + const second: string[] = [] + const observed: string[] = [] + const off = engine.onNotification((received, payload) => { + if (received === channel) observed.push(payload) + }) + const channels = async () => + ( + await engine.query<{ channel: string }>('SELECT pg_listening_channels() AS channel') + ).rows.map((row) => row.channel) + try { + await engine.query('LISTEN unrelated_listener_control') + // Installed driver's old quoted-string/map path is a discriminating control. + await expect(engine.listen(`"${channel}"`, () => undefined)).rejects.toMatchObject({ + code: '42601', + }) + const a = await adapter._listen('job-available', (payload) => first.push(payload)) + const b = await adapter._listen('job-available', (payload) => second.push(payload)) + expect(await channels()).toContain(channel) + await engine.query('SELECT pg_notify($1, $2)', ['unrelated_listener_control', 'ignored']) + expect(first).toEqual([]) + expect(second).toEqual([]) + await engine.query('SELECT pg_notify($1, $2)', [channel, "O'Reilly λ"]) + expect(first).toEqual(["O'Reilly λ"]) + expect(second).toEqual(["O'Reilly λ"]) + await a.unlisten() + await a.unlisten() + expect(await channels()).toContain(channel) + await engine.query('SELECT pg_notify($1, $2)', [channel, 'second only']) + expect(first).toHaveLength(1) + expect(second).toEqual(["O'Reilly λ", 'second only']) + await b.unlisten() + expect(await channels()).not.toContain(channel) + expect(await channels()).toContain('unrelated_listener_control') + + // Re-enable only the native subscription: delivery to the independent observer + // proves that removed application callbacks are absent, not merely unsubscribed. + const quoted = ( + await engine.query<{ identifier: string }>('SELECT quote_ident($1) AS identifier', [ + channel, + ]) + ).rows[0]!.identifier + await engine.query(`LISTEN ${quoted}`) + await engine.query('SELECT pg_notify($1, $2)', [channel, 'observer only']) + expect(observed).toEqual(["O'Reilly λ", 'second only', 'observer only']) + expect(first).toHaveLength(1) + expect(second).toHaveLength(2) + await engine.query(`UNLISTEN ${quoted}`) + await engine.query('UNLISTEN unrelated_listener_control') + } finally { + off() + // This configured prefix has no migrated tables; cleanup failure is not + // mistaken for a successful start. Owned engine close still has its opportunity. + await adapter.stop().catch(() => undefined) + if (!engine.closed) await engine.close() + await instance.deleteDb() + } + expect(engine.closed).toBe(true) + }) + + it('cleans uncertain LISTEN allocation after a rejected reply and preserves the startup error', async () => { + const instance = await pgliteFactory.create() + const adapter = instance.adapter as ListenerProbe + adapter.setId('listener-partial') + const engine = adapter.db.$client + const query = engine.query.bind(engine) + const close = engine.close.bind(engine) + const failure = new Error('injected LISTEN reply failure after native success') + let injected = false + let unlistens = 0 + let beforeClose: string[] | undefined + let applicationCalls = 0 + adapter.on('job-status-changed', () => { + applicationCalls++ + }) + engine.query = async (...args: Parameters) => { + const result = await query(...args) + if (args[0].startsWith('LISTEN ') && !injected) { + injected = true + // Prove actual subscription allocation before the labelled reply fault. + const channels = await query<{ channel: string }>( + 'SELECT pg_listening_channels() AS channel', + ) + expect(channels.rows.map((row) => row.channel)).toContain('duron.job-status-changed') + throw failure + } + if (args[0].startsWith('UNLISTEN ')) unlistens++ + return result + } + engine.close = async () => { + beforeClose = ( + await query<{ channel: string }>('SELECT pg_listening_channels() AS channel') + ).rows.map((row) => row.channel) + await close() + } + try { + await expect(adapter.start()).rejects.toBe(failure) + expect(injected).toBe(true) + expect(unlistens).toBe(1) + expect(beforeClose).toEqual([]) + expect(applicationCalls).toBe(0) + expect(engine.closed).toBe(true) + expect(await adapter.stop()).toBe(true) + expect(await adapter.start()).toBe(false) + } finally { + engine.query = query + engine.close = close + await adapter.stop().catch(() => undefined) + if (!engine.closed) await close() + await instance.deleteDb() + } + }) + + it('retries failed unsubscribe only while the owned engine remains usable', async () => { + const instance = await pgliteFactory.create() + const adapter = instance.adapter as ListenerProbe + adapter.setId('listener-retry') + const engine = adapter.db.$client + const query = engine.query.bind(engine) + const close = engine.close.bind(engine) + const unsubscribeFailure = new Error('injected before native UNLISTEN') + const closeFailure = new Error('injected before native close') + let unlistens = 0 + let closes = 0 + let beforeClose: string[] | undefined + try { + await adapter.start() + engine.query = async (...args: Parameters) => { + if (args[0].startsWith('UNLISTEN ') && ++unlistens === 1) throw unsubscribeFailure + return query(...args) + } + engine.close = async () => { + if (++closes === 1) throw closeFailure + beforeClose = ( + await query<{ channel: string }>('SELECT pg_listening_channels() AS channel') + ).rows.map((row) => row.channel) + await close() + } + const error = await adapter.stop().catch((cause: unknown) => cause) + expect(error).toBeInstanceOf(AggregateError) + expect((error as AggregateError).errors).toEqual([unsubscribeFailure, closeFailure]) + expect(engine.closed).toBe(false) + const surviving = await query<{ channel: string }>( + 'SELECT pg_listening_channels() AS channel', + ) + expect(surviving.rows.map((row) => row.channel)).toEqual(['duron.job-status-changed']) + expect(await adapter.stop()).toBe(true) + expect(unlistens).toBe(3) + expect(closes).toBe(2) + expect(beforeClose).toEqual([]) + expect(engine.closed).toBe(true) + expect(await adapter.stop()).toBe(true) + expect(unlistens).toBe(3) + expect(closes).toBe(2) + } finally { + engine.query = query + engine.close = close + await adapter.stop().catch(() => undefined) + if (!engine.closed) await close() + await instance.deleteDb() + } + }) +}) diff --git a/packages/duron/test/lifecycle-sql.test.ts b/packages/duron/test/lifecycle-sql.test.ts new file mode 100644 index 0000000..00a8681 --- /dev/null +++ b/packages/duron/test/lifecycle-sql.test.ts @@ -0,0 +1,206 @@ +import { describe, expect, it } from 'bun:test' + +import type { SQL } from 'drizzle-orm' + +import type { Job } from '../src/adapters/adapter.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +type Row = Record +type SqlProbe = Adapter & { + _close: () => Promise + _getJobFromTable: (id: string, table: unknown) => Promise + db: { + execute: (query: SQL) => Promise + dialect: { sqlToQuery: (query: SQL) => { sql: string } } + transaction: (work: (tx: unknown) => Promise, config?: unknown) => Promise + $client: { + query?: (text: string, params?: unknown[]) => Promise<{ rows: Row[] }> + unsafe?: (text: string, params?: unknown[]) => PromiseLike + closed?: boolean + close?: () => Promise + end?: (options: { timeout: number }) => Promise + } + } +} + +// Public calls remain the primary seam. Holds delay a settled helper result or +// transaction callback; the close fault deliberately leaves native SQL usable. +// Native observer queries are test diagnostics, not application continuations. +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Lifecycle SQL with ${factory.name}`, () => { + it('gates imported migration continuations after startup settlement expires', async () => { + const instance = await factory.create() + const adapter = instance.adapter as SqlProbe + adapter.setId('migration-cutoff') + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const close = adapter._close.bind(adapter) + const execute = adapter.db.execute.bind(adapter.db) + const closeFailure = new Error('injected before owned close') + const driver = adapter.db.$client + let held = false + adapter.db.execute = async (query) => { + const result = await execute(query) + if ( + !held && + adapter.db.dialect.sqlToQuery(query).sql.includes('CREATE SCHEMA IF NOT EXISTS') + ) { + held = true + entered.resolve() + await release.promise + } + return result + } + adapter._close = async () => { + throw closeFailure + } + const started = adapter.start() + // Observe immediately: the original startup is deliberately held beyond stop's budget. + void started.catch(() => undefined) + try { + await entered.promise + const stopped = await adapter.stop().catch((error: unknown) => error) + expect(stopped).toBeInstanceOf(AggregateError) + const errors = (stopped as AggregateError).errors + expect(errors.some((error) => String(error).includes('startup settlement'))).toBe(true) + expect(errors).toContain(closeFailure) + release.resolve() + const startError = await started.catch((error: unknown) => error) + expect(startError).toBeInstanceOf(AggregateError) + expect(String((startError as AggregateError).errors[0])).toContain( + 'ordinary work has drained', + ) + const statement = "SELECT to_regclass('duron.clients') AS relation" + const rows = driver.query + ? (await driver.query(statement)).rows + : await driver.unsafe!(statement) + expect(rows).toMatchObject([{ relation: null }]) + adapter._close = close + expect(await adapter.stop()).toBe(true) + } finally { + release.resolve() + await started.catch(() => undefined) + adapter.db.execute = execute + adapter._close = close + await adapter.stop().catch(() => undefined) + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('blocks the next statement in an admitted read after drain even when close has failed', async () => { + const instance = await factory.create() + const adapter = instance.adapter as SqlProbe + adapter.setId('sql-read-cutoff') + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const close = adapter._close.bind(adapter) + const read = adapter._getJobFromTable.bind(adapter) + const closeFailure = new Error('injected before owned close') + const driver = adapter.db.$client + const native = async (text: string): Promise => + driver.query ? (await driver.query(text)).rows : await driver.unsafe!(text) + let completedReads = 0 + let operation: Promise | undefined + try { + await adapter.start() + adapter._getJobFromTable = async (id, table) => { + const result = await read(id, table) + if (++completedReads === 1) { + entered.resolve() + await release.promise + } + return result + } + adapter._close = async () => { + throw closeFailure + } + operation = adapter.getJobById(crypto.randomUUID()) + await entered.promise + const stopped = await adapter.stop().catch((error: unknown) => error) + expect(stopped).toBeInstanceOf(AggregateError) + expect((stopped as AggregateError).errors).toContain(closeFailure) + expect((await native('SELECT 1 AS usable'))[0]?.['usable']).toBe(1) + release.resolve() + await expect(operation).rejects.toThrow('ordinary work has drained') + expect(completedReads).toBe(1) + adapter._close = close + expect(await adapter.stop()).toBe(true) + } finally { + release.resolve() + await operation?.catch(() => undefined) + adapter._close = close + adapter._getJobFromTable = read + await adapter.stop().catch(() => undefined) + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('rolls back rather than committing a transaction callback that completes after drain', async () => { + const instance = await factory.create() + const adapter = instance.adapter as SqlProbe + adapter.setId('sql-transaction-cutoff') + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const close = adapter._close.bind(adapter) + const transaction = adapter.db.transaction.bind(adapter.db) + const closeFailure = new Error('injected before owned close') + const driver = adapter.db.$client + const native = async (text: string, params?: unknown[]): Promise => + driver.query ? (await driver.query(text, params)).rows : await driver.unsafe!(text, params) + let operation: Promise | undefined + try { + await adapter.start() + const jobId = await adapter.createJob({ + queue: 'transaction-cutoff', + groupKey: 'tx', + input: {}, + timeoutMs: 30_000, + checksum: 'tx', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + adapter.db.transaction = (work, config) => + transaction(async (tx) => { + const result = await work(tx) + entered.resolve() + await release.promise + return result + }, config) + adapter._close = async () => { + throw closeFailure + } + operation = adapter.cancelJob({ jobId: jobId! }) + await entered.promise + const stopped = await adapter.stop().catch((error: unknown) => error) + expect(stopped).toBeInstanceOf(AggregateError) + expect((stopped as AggregateError).errors).toContain(closeFailure) + release.resolve() + await expect(operation).rejects.toThrow('ordinary work has drained') + // Native state proves rollback while the failed-close engine/session is usable. + expect( + await native('SELECT status FROM duron.jobs_active WHERE id = $1', [jobId]), + ).toMatchObject([{ status: 'created' }]) + expect(await native('SELECT id FROM duron.jobs_archive WHERE id = $1', [jobId])).toEqual([]) + adapter._close = close + expect(await adapter.stop()).toBe(true) + } finally { + release.resolve() + await operation?.catch(() => undefined) + adapter._close = close + adapter.db.transaction = transaction + await adapter.stop().catch(() => undefined) + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 40_000) + }) +} diff --git a/packages/duron/test/lifecycle-startup.test.ts b/packages/duron/test/lifecycle-startup.test.ts new file mode 100644 index 0000000..54014b6 --- /dev/null +++ b/packages/duron/test/lifecycle-startup.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it } from 'bun:test' + +import { type SQL, sql } from 'drizzle-orm' +import postgres from 'postgres' + +import { defineAction } from '../src/action.js' +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +type Row = Record +type StartupProbe = Adapter & { + _close: () => Promise + _listen: ( + event: string, + callback: (payload: string) => void, + ) => Promise<{ unlisten: () => void | Promise }> + db: { + execute: (query: SQL) => Promise + dialect: { sqlToQuery: (query: SQL) => { sql: string } } + $client: { + query?: (text: string) => Promise<{ rows: Row[] }> + unsafe?: (text: string) => PromiseLike + closed?: boolean + close?: () => Promise + end?: (options: { timeout: number }) => Promise + } + } +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Partial startup with ${factory.name}`, () => { + for (const stage of [ + 'migration', + 'startup-GC', + 'first-listener', + 'second-listener', + 'recovery', + ] as const) { + it(`automatically cleans ${stage} failure with native resource proof`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as StartupProbe + const client = new Client({ + id: `failure-${stage}`, + database: adapter, + syncPattern: 'hybrid', + logger: 'silent', + actions: { noop: defineAction()({ name: 'startup-noop', handler: async () => ({}) }) }, + }) + const driver = adapter.db.$client + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + const execute = adapter.db.execute.bind(adapter.db) + const listen = adapter._listen.bind(adapter) + const close = adapter._close.bind(adapter) + const native = async (statement: string): Promise => + driver.query ? (await driver.query(statement)).rows : await driver.unsafe!(statement) + let failure: unknown = new Error(`injected ${stage} reply failure`) + let injected = false + let registrations = 0 + let closes = 0 + let remaining: unknown + const nativeFailure = async (): Promise => { + // Actual22012, or42P01 for an UNEXPECTED relation, at a labelled + // substituted SQL boundary. Not an ACL/network/migration-content claim. + try { + await execute( + stage === 'startup-GC' + ? sql`SELECT * FROM duron.unexpected_missing_relation` + : sql`SELECT 1 / 0`, + ) + } catch (error) { + failure = error + throw error + } + throw new Error('Expected native division-by-zero failure') + } + adapter.db.execute = async (query) => { + const text = adapter.db.dialect.sqlToQuery(query).sql + const selected = + stage === 'migration' + ? text.includes('CREATE SCHEMA IF NOT EXISTS') + : stage === 'startup-GC' && text.includes('DELETE FROM "duron"."clients"') + if (selected && !injected) { + injected = true + return nativeFailure() + } + return execute(query) + } + adapter._listen = async (event, callback) => { + const handle = await listen(event, callback) + registrations++ + const target = stage === 'first-listener' ? 1 : stage === 'second-listener' ? 2 : 0 + if (registrations === target) { + // Native allocation succeeded, but no handle reaches the base caller. + injected = true + throw failure + } + return handle + } + if (stage === 'recovery') + adapter.recoverJobs = async () => { + injected = true + const before = await native('SELECT count(*)::int AS count FROM duron.clients') + expect(before[0]?.['count']).toBe(1) + return nativeFailure() + } + adapter._close = async () => { + closes++ + const table = await native("SELECT to_regclass('duron.clients') AS relation") + remaining = + table[0]?.['relation'] === null + ? null + : (await native('SELECT count(*)::int AS count FROM duron.clients'))[0]?.['count'] + await close() + } + try { + const result = await client.start().catch((error: unknown) => error) + expect(injected).toBe(true) + expect(result).toBe(failure) + if (stage === 'migration' || stage === 'startup-GC' || stage === 'recovery') { + expect((failure as Error).cause).toMatchObject({ + code: stage === 'startup-GC' ? '42P01' : '22012', + }) + } + expect(remaining).toBe(stage === 'migration' ? null : 0) + expect(closes).toBe(1) + if (stage === 'first-listener') expect(registrations).toBe(1) + if (stage === 'second-listener') expect(registrations).toBe(2) + expect(await client.stop()).toBe(true) + expect(await client.start()).toBe(false) + expect(closes).toBe(1) + if (observer) { + const sessions = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions[0]!['count']).toBe(0) + } else expect(driver.closed).toBe(true) + } finally { + adapter.db.execute = execute + adapter._listen = listen + adapter._close = close + await client.stop().catch(() => undefined) + if (driver.close && !driver.closed) await driver.close() + await driver.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + } + }) +} diff --git a/packages/duron/test/lifecycle.test.ts b/packages/duron/test/lifecycle.test.ts new file mode 100644 index 0000000..0649bbb --- /dev/null +++ b/packages/duron/test/lifecycle.test.ts @@ -0,0 +1,974 @@ +import { describe, expect, it } from 'bun:test' + +import { type SQL, sql } from 'drizzle-orm' +import postgres from 'postgres' + +import { defineAction } from '../src/action.js' +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +// Fault-injected public lifecycle tests. Native observations prove resource release; +// a rejected start/fulfilled stop alone is not evidence of physical closure. +type LifecycleProbe = Adapter & { + _start: () => Promise + _stop: () => Promise + _heartbeat: () => Promise + _notify: (event: string, data: unknown) => Promise + _listen: ( + event: string, + callback: (payload: string) => void, + ) => Promise<{ unlisten: () => void | Promise }> + _getJobs: () => Promise<{ jobs: []; total: number; page: number; pageSize: number }> + db: { + execute: (query: SQL) => Promise + $client: { + query?: (text: string) => Promise<{ rows: unknown[] }> + unsafe?: (text: string) => PromiseLike + closed?: boolean + close?: () => Promise + end?: (options: { timeout: number }) => Promise + } + } +} + +// Raw native observations intentionally bypass application ORM admission during close. +async function nativeRows(adapter: LifecycleProbe, statement: string): Promise { + const driver = adapter.db.$client + return driver.query ? (await driver.query(statement)).rows : await driver.unsafe!(statement) +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Lifecycle with ${factory.name}`, () => { + it('gives stop priority over remaining listener startup stages without closing under issued startup', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('stop-priority') + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const listen = adapter._listen.bind(adapter) + let registrations = 0 + adapter._listen = async (event, callback) => { + registrations++ + const handle = await listen(event, callback) + if (registrations === 1) { + entered.resolve() + await release.promise + } + return handle + } + const start = adapter.start() + let stopped: Promise | undefined + try { + await entered.promise + stopped = adapter.stop() + release.resolve() + expect(await start).toBe(false) + expect(await stopped).toBe(true) + expect(registrations).toBe(1) + } finally { + release.resolve() + await start.catch(() => undefined) + await stopped?.catch(() => undefined) + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('attempts independent unlistens, preserves their error, and discharges listeners on owned close', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('listener-cleanup') + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + const listen = adapter._listen.bind(adapter) + const failure = new Error('injected first unlisten failure') + let allocations = 0 + let unlistens = 0 + adapter._listen = async (event, callback) => { + const handle = await listen(event, callback) + const first = allocations++ === 0 + return { + unlisten: async () => { + unlistens++ + if (first) throw failure + await handle.unlisten() + }, + } + } + try { + await adapter.start() + await adapter.heartbeat() + await expect(adapter.stop()).rejects.toBe(failure) + expect(unlistens).toBe(2) + if (observer) { + const sessions = + await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + expect(sessions[0]!['count']).toBe(0) + } else { + expect(adapter.db.$client.closed).toBe(true) + } + expect(await adapter.stop()).toBe(true) + expect(unlistens).toBe(2) + } finally { + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + for (const syncPattern of ['pull', 'push'] as const) { + it(`drains the whole ${syncPattern} callback through public fetch dispatch`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const action = defineAction()({ name: 'background-drain', handler: async () => ({}) }) + const client = new Client({ + id: 'background-drain', + database: adapter, + syncPattern, + recoverJobsOnStart: false, + actions: { action }, + pullInterval: 5, + logger: 'silent', + }) + let calls = 0 + client.fetch = async () => { + calls++ + entered.resolve() + await release.promise + return [] + } + let stopped: Promise | undefined + let timer: ReturnType | undefined + try { + await client.start() + if (syncPattern === 'push') adapter.emit('job-available', { jobId: 'controlled-hint' }) + await entered.promise + stopped = client.stop() + const first = await Promise.race([ + stopped.then( + () => 'stopped', + () => 'rejected', + ), + new Promise((resolve) => { + timer = setTimeout(() => resolve('draining'), 100) + }), + ]) + expect(first).toBe('draining') + release.resolve() + expect(await stopped).toBe(true) + expect(calls).toBe(1) + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await stopped?.catch(() => undefined) + await client.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) + await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + } + + it('settles a pending wait immediately while draining its actual terminal-detail read', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const client = new Client({ + id: 'wait-detail-drain', + database: adapter, + syncPattern: false, + logger: 'silent', + }) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const read = client.getJobById.bind(client) + let waiting: Promise | undefined + let stopped: Promise | undefined + const timers: ReturnType[] = [] + const sentinel = () => + new Promise((resolve) => { + timers.push(setTimeout(() => resolve('still pending'), 100)) + }) + try { + await client.start() + const jobId = await adapter.createJob({ + queue: 'wait-detail', + groupKey: 'wait', + input: {}, + timeoutMs: 30_000, + checksum: 'wait', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + await adapter.cancelJob({ jobId: jobId! }) + client.getJobById = async (id) => { + entered.resolve() + await release.promise + return read(id) + } + waiting = client.waitForJob(jobId!) + await entered.promise + stopped = client.stop() + expect(await Promise.race([waiting, sentinel()])).toBeNull() + expect(await Promise.race([stopped, sentinel()])).toBe('still pending') + release.resolve() + expect(await stopped).toBe(true) + expect(await waiting).toBeNull() + } finally { + for (const timer of timers) clearTimeout(timer) + release.resolve() + await waiting?.catch(() => undefined) + await stopped?.catch(() => undefined) + await client.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('drains admitted Client input work before closing its later database continuation', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const action = defineAction()({ + name: 'held-input', + groups: { + groupKey: async () => { + entered.resolve() + await release.promise + return 'held' + }, + }, + handler: async () => ({}), + }) + const client = new Client({ + id: 'input-drain', + database: adapter, + syncPattern: false, + actions: { held: action }, + logger: 'silent', + }) + let running: Promise | undefined + let stopped: Promise | undefined + let timer: ReturnType | undefined + try { + running = client.runAction('held', {}) + await entered.promise + stopped = client.stop() + const first = await Promise.race([ + stopped.then( + () => 'stopped', + () => 'rejected', + ), + new Promise((resolve) => { + timer = setTimeout(() => resolve('draining'), 100) + }), + ]) + expect(first).toBe('draining') + release.resolve() + expect(await running).toEqual(expect.any(String)) + expect(await stopped).toBe(true) + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await running?.catch(() => undefined) + await stopped?.catch(() => undefined) + await client.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('drains a public fetch override without executing its late claimed jobs', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + let executions = 0 + const action = defineAction()({ + name: 'late-fetch', + handler: async () => { + executions++ + return {} + }, + }) + const client = new Client({ + id: 'late-fetch-client', + database: adapter, + syncPattern: false, + actions: { late: action }, + logger: 'silent', + }) + const fetch = adapter.fetch.bind(adapter) + let fetching: Promise | undefined + let stopped: Promise | undefined + let timer: ReturnType | undefined + try { + await client.runAction('late', {}) + adapter.fetch = async (options) => { + const jobs = await fetch(options) + entered.resolve() + await release.promise + return jobs + } + fetching = client.fetch({ batchSize: 1 }) + await entered.promise + stopped = client.stop() + const first = await Promise.race([ + stopped.then( + () => 'stopped', + () => 'rejected', + ), + new Promise((resolve) => { + timer = setTimeout(() => resolve('draining'), 100) + }), + ]) + expect(first).toBe('draining') + release.resolve() + expect(await fetching).toHaveLength(1) + expect(await stopped).toBe(true) + expect(executions).toBe(0) + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await fetching?.catch(() => undefined) + await stopped?.catch(() => undefined) + await client.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('drains the actual periodic heartbeat callback before releasing liveness', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const client = new Client({ + id: 'heartbeat-drain', + database: adapter, + syncPattern: false, + heartbeatInterval: 5, + logger: 'silent', + }) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const heartbeat = adapter.heartbeat.bind(adapter) + let finished = false + let timer: ReturnType | undefined + let stopped: Promise | undefined + try { + await client.start() + adapter.heartbeat = async () => { + entered.resolve() + await release.promise + await heartbeat() + finished = true + } + await entered.promise + stopped = client.stop() + const first = await Promise.race([ + stopped.then( + () => 'stopped', + () => 'rejected', + ), + new Promise((resolve) => { + timer = setTimeout(() => resolve('draining'), 100) + }), + ]) + expect(first).toBe('draining') + release.resolve() + expect(await stopped).toBe(true) + expect(finished).toBe(true) + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await stopped?.catch(() => undefined) + await client.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('withholds liveness after incomplete drain and omits a late hint without changing mutation success', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const client = new Client({ + id: 'incomplete-drain', + database: adapter, + syncPattern: false, + logger: 'silent', + }) + const reports: unknown[] = [] + client.logger.error = (fields: unknown) => { + reports.push(fields) + } + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const notify = adapter._notify.bind(adapter) + const driver = adapter.db.$client + const close = driver.close?.bind(driver) + const end = driver.end?.bind(driver) + let remaining: number | undefined + const inspect = async () => { + const rows = (await nativeRows( + adapter, + "SELECT count(*)::int AS count FROM duron.clients WHERE client_id = 'incomplete-drain'", + )) as { count: number }[] + remaining = rows[0]!.count + } + if (close) + driver.close = async () => { + await inspect() + await close() + } + if (end) + driver.end = async (options) => { + await inspect() + await end(options) + } + let operation: Promise | undefined + let timer: ReturnType | undefined + try { + await client.start() + const jobId = await adapter.createJob({ + queue: 'drain-timeout', + groupKey: 'drain', + input: {}, + timeoutMs: 30_000, + checksum: 'drain', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + adapter._notify = async (event, data) => { + entered.resolve() + await release.promise + await notify(event, data) + } + operation = adapter.cancelJob({ jobId: jobId! }) + await entered.promise + const stopped = await Promise.race([ + client.stop().catch((error: unknown) => error), + new Promise((resolve) => { + timer = setTimeout(() => resolve('observer deadline'), 6_000) + }), + ]) + expect(stopped).toBeInstanceOf(Error) + const errors = stopped instanceof AggregateError ? stopped.errors : [stopped] + expect(errors.some((error) => String(error).includes('admitted-work drain'))).toBe(true) + expect(remaining).toBe(1) + release.resolve() + expect(await operation).toBe(true) + expect(reports).toHaveLength(1) + expect(reports[0]).toMatchObject({ + stage: 'lifecycle cutoff', + mutationResult: 'unchanged', + delivery: 'unconfirmed', + jobId, + }) + await expect(client.stop()).rejects.toThrow('withheld') + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await operation?.catch(() => undefined) + if (close) driver.close = close + if (end) driver.end = end + await client.stop().catch(() => undefined) + if (close && !driver.closed) await close() + await end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + for (const kind of ['action', 'step'] as const) { + it(`drains the actual ${kind} callback after cancellation wins its observer race`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + let finished = false + let timer: ReturnType | undefined + const action = defineAction()({ + name: `held-${kind}`, + handler: async (ctx) => { + const run = async () => { + entered.resolve() + await release.promise + finished = true + return { done: true } + } + return kind === 'step' ? ctx.step('held-step', run) : run() + }, + }) + const client = new Client({ + id: 'handler-drain', + database: adapter, + syncPattern: false, + actions: { held: action }, + logger: 'silent', + }) + let stopped: Promise | undefined + try { + await client.runAction('held', {}) + await client.fetch({ batchSize: 1 }) + await entered.promise + stopped = client.stop() + const first = await Promise.race([ + stopped.then( + () => 'stopped', + () => 'rejected', + ), + new Promise((resolve) => { + timer = setTimeout(() => resolve('draining'), 100) + }), + ]) + expect(first).toBe('draining') + release.resolve() + expect(await stopped).toBe(true) + expect(finished).toBe(true) + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await stopped?.catch(() => undefined) + await client.stop().catch(() => undefined) + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) + await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + } + + it('drains an admitted mutation through its notification before Client closes the adapter', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const client = new Client({ id: 'notification-drain', database: adapter, syncPattern: false }) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const notify = adapter._notify.bind(adapter) + let finished = false + let timer: ReturnType | undefined + let operation: Promise | undefined + try { + await client.start() + const jobId = await adapter.createJob({ + queue: 'drain-test', + groupKey: 'drain', + input: {}, + timeoutMs: 30_000, + checksum: 'drain', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(jobId).not.toBeNull() + adapter._notify = async (event, data) => { + entered.resolve() + await release.promise + await notify(event, data) + finished = true + } + operation = adapter.cancelJob({ jobId: jobId! }) + await entered.promise + const stopped = client.stop() + const first = await Promise.race([ + stopped.then(() => 'stopped'), + new Promise((resolve) => { + timer = setTimeout(() => resolve('draining'), 100) + }), + ]) + expect(first).toBe('draining') + release.resolve() + expect(await operation).toBe(true) + expect(await stopped).toBe(true) + expect(finished).toBe(true) + } finally { + if (timer !== undefined) clearTimeout(timer) + release.resolve() + await operation?.catch(() => undefined) + await client.stop().catch(() => undefined) + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('requires a successful native initial heartbeat before Client startup can succeed', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const client = new Client({ + id: 'client-native-heartbeat', + database: adapter, + syncPattern: false, + }) + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + try { + await adapter.start() + // Seeded native fault: heartbeat SQL must propagate its real rejection. + await adapter.db.execute(sql` + CREATE FUNCTION duron.reject_heartbeat() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'injected heartbeat failure' USING ERRCODE = '42501'; END + $$ + `) + await adapter.db.execute(sql` + CREATE TRIGGER reject_heartbeat BEFORE INSERT OR UPDATE ON duron.clients + FOR EACH ROW EXECUTE FUNCTION duron.reject_heartbeat() + `) + await expect(client.start()).rejects.toThrow('Failed query') + if (observer) { + const sessions = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions[0]!['count']).toBe(0) + } else { + expect(adapter.db.$client.closed).toBe(true) + } + expect(await client.stop()).toBe(true) + } finally { + await client.stop().catch(() => undefined) + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('cleans up failed Client startup while stop reports cleanup rather than the startup error', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + const client = new Client({ + id: 'client-failed-start', + database: adapter, + syncPattern: false, + }) + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + const failure = new Error('injected initial heartbeat failure') + adapter.heartbeat = async () => { + throw failure + } + try { + await expect(client.start()).rejects.toBe(failure) + if (observer) { + const sessions = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions[0]!['count']).toBe(0) + } else { + expect(adapter.db.$client.closed).toBe(true) + } + expect(await client.stop()).toBe(true) + expect(await client.start()).toBe(false) + } finally { + await client.stop().catch(() => undefined) + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('reserves owned close after database cleanup times out and records late cleanup completion', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('held-cleanup') + const cleanup = adapter._stop.bind(adapter) + const release = Promise.withResolvers() + let attempts = 0 + let deadlineTimer: ReturnType | undefined + adapter._stop = async () => { + attempts++ + await cleanup() + await release.promise + } + try { + await adapter.start() + const result = await Promise.race([ + adapter.stop().catch((error: unknown) => error), + new Promise((resolve) => { + deadlineTimer = setTimeout(() => resolve('observer deadline'), 6_000) + }), + ]) + expect(result).toBeInstanceOf(Error) + expect(String(result)).toContain('database cleanup') + if (factory.name === 'pglite') expect(adapter.db.$client.closed).toBe(true) + release.resolve() + expect(await adapter.stop()).toBe(true) + expect(attempts).toBe(1) + } finally { + if (deadlineTimer !== undefined) clearTimeout(deadlineTimer) + release.resolve() + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('bounds owned close and joins its pending operation on a later stop', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('held-close') + const driver = adapter.db.$client + const close = driver.close?.bind(driver) + const end = driver.end?.bind(driver) + const release = Promise.withResolvers() + let attempts = 0 + let deadlineTimer: ReturnType | undefined + const heldClose = async () => { + attempts++ + await release.promise + if (close) await close() + else await end!({ timeout: 5 }) + } + if (close) driver.close = heldClose + if (end) driver.end = heldClose + try { + await adapter.start() + const result = await Promise.race([ + adapter.stop().catch((error: unknown) => error), + new Promise((resolve) => { + deadlineTimer = setTimeout(() => resolve('observer deadline'), 6_000) + }), + ]) + expect(result).toBeInstanceOf(Error) + expect(String(result)).toContain('owned close') + const retry = adapter.stop() + release.resolve() + expect(await retry).toBe(true) + expect(attempts).toBe(1) + expect(await adapter.stop()).toBe(true) + } finally { + if (deadlineTimer !== undefined) clearTimeout(deadlineTimer) + release.resolve() + if (close) driver.close = close + if (end) driver.end = end + await adapter.stop().catch(() => undefined) + if (close && !driver.closed) await close() + await end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('reports a liveness cleanup error, still closes, and never retries SQL on closed resources', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('failed-release') + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + try { + await adapter.start() + await adapter.heartbeat() + // Seeded native fault: an actual server error, not ACL revocation. + await adapter.db.execute(sql` + CREATE FUNCTION duron.reject_release() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'injected liveness delete failure' USING ERRCODE = '42501'; END + $$ + `) + await adapter.db.execute(sql` + CREATE TRIGGER reject_release BEFORE DELETE ON duron.clients + FOR EACH ROW EXECUTE FUNCTION duron.reject_release() + `) + const result = await adapter.stop().catch((error: unknown) => error) + expect(result).toBeInstanceOf(Error) + if (observer) { + const sessions = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions[0]!['count']).toBe(0) + const clients = await observer`SELECT client_id FROM duron.clients` + expect(clients.map((row) => row['client_id'])).toEqual(['failed-release']) + } else { + expect(adapter.db.$client.closed).toBe(true) + } + await expect(adapter.stop()).rejects.toBe(result) + } finally { + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('deletes liveness while SQL is usable before owned close', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('healthy-release') + let remaining: number | undefined + const inspect = async () => { + const rows = (await nativeRows( + adapter, + "SELECT count(*)::int AS count FROM duron.clients WHERE client_id = 'healthy-release'", + )) as { count: number }[] + remaining = rows[0]!.count + } + const driver = adapter.db.$client + const close = driver.close?.bind(driver) + const end = driver.end?.bind(driver) + if (close) + driver.close = async () => { + await inspect() + await close() + } + if (end) + driver.end = async (options) => { + await inspect() + await end(options) + } + try { + await adapter.start() + await adapter.heartbeat() + await inspect() + expect(remaining).toBe(1) + expect(await adapter.stop()).toBe(true) + expect(remaining).toBe(0) + } finally { + if (close) driver.close = close + if (end) driver.end = end + await adapter.stop().catch(() => undefined) + if (close && !driver.closed) await close() + await end?.({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('rejects ordinary reads and writes after stop without dispatching adapter work', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('closed-admission') + let dispatched = 0 + adapter._getJobs = async () => { + dispatched++ + return { jobs: [], total: 0, page: 1, pageSize: 10 } + } + adapter._heartbeat = async () => { + dispatched++ + } + try { + expect(await adapter.stop()).toBe(true) + await expect(adapter.getJobs()).rejects.toThrow('not accepting work') + await expect(adapter.heartbeat()).rejects.toThrow('not accepting work') + expect(dispatched).toBe(0) + expect(await adapter.start()).toBe(false) + } finally { + await adapter.stop() + await instance.deleteDb() + } + }, 30_000) + + it('bounds startup settlement, closes owned resources and observes late startup without success', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('held-start') + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + let deadlineTimer: ReturnType | undefined + const originalStart = adapter._start.bind(adapter) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + adapter._start = async () => { + await originalStart() + entered.resolve() + await release.promise + } + const startResult = adapter.start().then( + (value) => ({ value, error: undefined }), + (error: unknown) => ({ value: undefined, error }), + ) + try { + await entered.promise + const before = performance.now() + const stopResult = adapter.stop().catch((error: unknown) => error) + const result = await Promise.race([ + stopResult, + new Promise((resolve) => { + deadlineTimer = setTimeout(() => resolve('observer deadline'), 6_000) + }), + ]) + expect(result).toBeInstanceOf(Error) + expect(String(result)).toContain('startup settlement') + expect(performance.now() - before).toBeLessThan(6_000) + if (observer) { + const rows = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(rows[0]!['count']).toBe(0) + } else { + expect(adapter.db.$client.closed).toBe(true) + } + release.resolve() + expect((await startResult).error).toBe(result) + expect(await adapter.start()).toBe(false) + expect(await adapter.stop()).toBe(true) + } finally { + if (deadlineTimer !== undefined) clearTimeout(deadlineTimer) + release.resolve() + await startResult + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + + it('automatically releases owned resources after startup fails and never retries startup', async () => { + const instance = await factory.create() + const adapter = instance.adapter as LifecycleProbe + adapter.setId('failed-start') + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + const originalStart = adapter._start.bind(adapter) + const failure = new Error('injected after actual startup allocation') + let attempts = 0 + adapter._start = async () => { + attempts++ + await originalStart() + throw failure + } + try { + await expect(adapter.start()).rejects.toBe(failure) + if (observer) { + const rows = await observer` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(rows[0]!['count']).toBe(0) + } else { + expect(adapter.db.$client.closed).toBe(true) + } + expect(await adapter.start()).toBe(false) + expect(attempts).toBe(1) + expect(await adapter.stop()).toBe(true) + } finally { + // Emergency release is separate from assertions about automatic cleanup. + await adapter.stop().catch(() => undefined) + if (adapter.db.$client.close && !adapter.db.$client.closed) await adapter.db.$client.close() + await adapter.db.$client.end?.({ timeout: 5 }) + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }, 30_000) + }) +} diff --git a/packages/duron/test/recover.test.ts b/packages/duron/test/recover.test.ts index a920fb2..bacba6c 100644 --- a/packages/duron/test/recover.test.ts +++ b/packages/duron/test/recover.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import postgres from 'postgres' import { z } from 'zod/mini' import { defineAction } from '../src/action.js' @@ -344,6 +345,7 @@ function runRecoverTests(adapterFactory: AdapterFactory) { 'should recover jobs from a crashed worker process', async () => { const workerId = `worker-${Date.now()}` + const heartbeatTimeout = 1_000 // 1. Create host client to create jobs const hostClient = new Client({ @@ -371,12 +373,35 @@ function runRecoverTests(adapterFactory: AdapterFactory) { expectToBeDefined(job) expect(job.status).toBe(JOB_STATUS_ACTIVE) - // 5. Kill the worker process abruptly (simulating a crash) - workerProcess.kill(9) // SIGKILL - immediate termination + // 5. Kill this owned worker and confirm actual process exit, not just signal delivery. + const crashedWorker = workerProcess + crashedWorker.kill(9) + await crashedWorker.exited workerProcess = null - // 6. Wait a moment for the worker to die - await new Promise((resolve) => setTimeout(resolve, 100)) + // 6. A crash does not delete its still-fresh heartbeat. Wait for the + // existing SQL staleness predicate instead of assuming 100ms is enough. + const observer = postgres(connectionUrl, { + max: 1, + connect_timeout: 2, + connection: { statement_timeout: 2_000 }, + }) + try { + const deadline = performance.now() + 5_000 + while (true) { + const [heartbeat] = await observer<{ stale: boolean }[]>` + SELECT last_seen_at <= now() - (${heartbeatTimeout} * interval '1 millisecond') AS stale + FROM duron.clients WHERE client_id = ${workerId} + ` + expectToBeDefined(heartbeat) + if (heartbeat.stale) break + if (performance.now() >= deadline) + throw new Error('Worker heartbeat did not become stale within five seconds') + await Bun.sleep(25) + } + } finally { + await observer.end({ timeout: 5 }) + } // 7. Create a recovery client that will recover jobs from dead processes const recoveryClient = new Client({ @@ -386,7 +411,7 @@ function runRecoverTests(adapterFactory: AdapterFactory) { syncPattern: false, recoverJobsOnStart: true, heartbeatInterval: 500, - heartbeatTimeout: 1_000, + heartbeatTimeout, logger: 'error', }) clientsToStop.push(recoveryClient) From 5f247c0c4f6fda7738028b7d52c2ab3d34981deb Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 7 Nov 2026 17:49:19 -0300 Subject: [PATCH 006/100] Make SQL notification emission safe and non-destructive Parameterize PGLite pg_notify and catch the entire built-in preparation/submission attempt on both SQL backends. Preserve successful validated mutation results and awaited delivery attempts, with original errors and delivery-unconfirmed context through the existing logger. Keep mutation wrappers, custom overrides, exact channels, native limits and lifecycle listener/cutoff ownership intact. Add both-engine public/native regressions for all six wrappers, reply uncertainty, encoding, callback cleanup and pending-attempt shutdown accounting; document advisory delivery and limits. Verified root typecheck/lint/test/fmt, core build and full POSTGRES_TEST=true suite. Independent Standards and Spec reviews bind the five-file candidate to immutable base d51b0777a22fde298d54c37189331de3a6c9daec. Node runtime remains untested under the approved source/build compatibility gate. --- packages/docs/content/docs/multi-worker.mdx | 10 + packages/duron/src/adapters/postgres/base.ts | 24 +- .../duron/src/adapters/postgres/pglite.ts | 10 +- .../duron/src/adapters/postgres/postgres.ts | 14 +- packages/duron/test/notifications.test.ts | 705 ++++++++++++++++++ 5 files changed, 753 insertions(+), 10 deletions(-) create mode 100644 packages/duron/test/notifications.test.ts diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 228331d..af44a2a 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -242,6 +242,16 @@ SQL `now()` is transaction-start time, not continuously advancing wall time or c This change does not normalize other timestamps. Job complete/fail/cancel timestamps and relative prune cutoffs remain application-sourced; SQL claim, step and recovery timestamps retain their existing sources and distinct guards. Recorded timestamps need not be monotonically ordered under clock offset or movement. +## Notification Hints + +PostgreSQL and PGLite notifications are advisory hints, not durable events or acknowledgments of a mutation. After a successful validated create/retry/complete/fail/cancel/time-travel operation, both built-in SQL adapters await one hint attempt. A preparation or submission failure is reported through the configured adapter logger without replacing the original successful mutation result. No logger means no promised external error report. Errors include the original cause, backend/channel, stage and available job/client IDs, not the full payload. + +A rejected notification reply does not prove nondelivery: listeners may already have received the hint. Duron does not automatically replay the mutation or retry the hint. Mutation, validation, startup and listener-registration failures still reject normally; custom adapter overrides and throwing custom loggers keep their own behavior. False/null mutation results do not produce a hint. + +The whole `${schema}.${event}` string is one exact channel, including dots, case and quotes. Built-in payloads remain `{jobId}` for availability and `{jobId,status,clientId}` for terminal status. Emission uses bound `pg_notify` arguments; native channel/text/payload limits still apply, with no truncation, renaming or chunking. PostgreSQL channels are limited to 63 bytes and payloads to fewer than 8,000 bytes in the tested default configurations. This transport handling does not establish full custom-schema migration support. + +There is no ordinary notification deadline or background delivery queue. A stuck attempt can delay its caller even after the mutation commits. Shutdown observes it under the shared lifecycle budgets below; a timeout is not cancellation or proof of nondelivery. Notifications alone do not provide missed-event recovery. Recovery remains fetch-driven as described above, and this transport change adds no wait/worker reconciliation or recovery events. + ## Lifecycle and Shutdown `client.stop()` closes admission immediately: it cancels scheduled heartbeat/pull/prune timers, disables new event-driven work, settles pending waits with `null`, and requests action cancellation. It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler. diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index ddc1111..7f7063f 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -201,25 +201,41 @@ export abstract class PostgresBaseAdapter< protected _allowNotification(event: string, data: unknown): boolean { if (lifecycleFor(this).ordinaryOpen) return true + this._reportNotificationFailure( + event, + data, + 'lifecycle cutoff', + new Error('Notification omitted after lifecycle drain'), + ) + return false + } + + protected _reportNotificationFailure( + event: string, + data: unknown, + stage: 'preparation' | 'submission' | 'lifecycle cutoff', + err: unknown, + ): void { const ids = data !== null && typeof data === 'object' ? (data as { jobId?: unknown; clientId?: unknown }) : undefined this.logger?.error( { - err: new Error('Notification omitted after lifecycle drain'), + err, backend: this.constructor.name, event, channel: `${this.schema}.${event}`, - stage: 'lifecycle cutoff', + stage, jobId: typeof ids?.jobId === 'string' ? ids.jobId : undefined, clientId: typeof ids?.clientId === 'string' ? ids.clientId : this.id, mutationResult: 'unchanged', delivery: 'unconfirmed', }, - 'Notification omitted: mutation result unchanged; delivery unconfirmed', + stage === 'lifecycle cutoff' + ? 'Notification omitted: mutation result unchanged; delivery unconfirmed' + : 'Notification attempt failed: mutation result unchanged; delivery unconfirmed', ) - return false } private async _listenForEvents( diff --git a/packages/duron/src/adapters/postgres/pglite.ts b/packages/duron/src/adapters/postgres/pglite.ts index 02e8d42..d3137cf 100644 --- a/packages/duron/src/adapters/postgres/pglite.ts +++ b/packages/duron/src/adapters/postgres/pglite.ts @@ -98,7 +98,15 @@ export class PGLiteAdapter extends PostgresBaseAdapter { */ protected override async _notify(event: string, data: any): Promise { if (!this._allowNotification(event, data)) return - await this.db?.$client.query(`NOTIFY "${this.schema}.${event}", '${JSON.stringify(data)}'`) + let stage: 'preparation' | 'submission' = 'preparation' + try { + const channel = `${this.schema}.${event}` + const payload = JSON.stringify(data) + stage = 'submission' + await this.db.$client.query('SELECT pg_notify($1, $2)', [channel, payload]) + } catch (err) { + this._reportNotificationFailure(event, data, stage, err) + } } /** diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index 065e7f2..c12aaa8 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -104,11 +104,15 @@ export class PostgresAdapter extends PostgresBaseAdapter { if (!this._allowNotification(event, data)) return this.logger?.debug({ event, data }, `[PostgresAdapter] Notify ${event}`) - await this.db.$client - .notify(`${this.schema}.${event}`, JSON.stringify(data)) - .catch((err: Error) => { - this.logger?.error({ err, data }, `[PostgresAdapter] Failed to notify ${event}`) - }) + let stage: 'preparation' | 'submission' = 'preparation' + try { + const channel = `${this.schema}.${event}` + const payload = JSON.stringify(data) + stage = 'submission' + await this.db.$client.notify(channel, payload) + } catch (err) { + this._reportNotificationFailure(event, data, stage, err) + } } /** diff --git a/packages/duron/test/notifications.test.ts b/packages/duron/test/notifications.test.ts new file mode 100644 index 0000000..3458829 --- /dev/null +++ b/packages/duron/test/notifications.test.ts @@ -0,0 +1,705 @@ +import { describe, expect, it, spyOn } from 'bun:test' + +import type { PGlite } from '@electric-sql/pglite' +import { identifier, query as templateQuery } from '@electric-sql/pglite/template' +import pino from 'pino' +import postgres from 'postgres' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +const noop = () => {} + +type Row = Record +type Mutation = 'createJob' | 'retryJob' | 'completeJob' | 'failJob' | 'cancelJob' | 'timeTravelJob' +type MutationHooks = { [K in Mutation as `_${K}`]: Adapter[K] } +type NotificationProbe = Adapter & + MutationHooks & { + _close: () => Promise + _notify: (event: string, data: unknown) => Promise + _listen: ( + event: string, + callback: (payload: string) => void, + ) => Promise<{ unlisten: () => void | Promise }> + db: { + $client: { + notify?: (channel: string, payload: string) => PromiseLike + query?: PGlite['query'] + unsafe?: (text: string, params?: unknown[]) => PromiseLike + } + } + } + +function captureErrors(adapter: Adapter) { + const reports: unknown[] = [] + const logger = pino({ level: 'silent' }) + logger.error = (fields: unknown) => { + reports.push(fields) + } + adapter.setLogger(logger) + return reports +} + +// Approved concrete-driver seam: intercept ONLY notification submission, never +// mutation SQL. Real database reads and callbacks remain independent observations. +function interceptSubmission( + adapter: NotificationProbe, + submit: (channel: string, payload: string, native: () => Promise) => Promise, +) { + const driver = adapter.db.$client + if (driver.notify) { + const notify = driver.notify + driver.notify = (channel, payload) => + submit(channel, payload, async () => notify.call(driver, channel, payload)) + return () => { + driver.notify = notify + } + } + const query = driver.query! + driver.query = ((...args: Parameters) => { + const [text, params] = args + if (text === 'SELECT pg_notify($1, $2)') { + return submit(params![0] as string, params![1] as string, () => query.apply(driver, args)) + } + return query.apply(driver, args) + }) as PGlite['query'] + return () => { + driver.query = query + } +} + +it('keeps installed PGLite identifier-helper and escaped-listen-map controls discriminating', async () => { + const instance = await pgliteFactory.create({ schema: 'Quote"Name', migrateOnStart: false }) + const adapter = instance.adapter as NotificationProbe + adapter.setId('pglite-rejected-candidates') + const engine = adapter.db.$client as PGlite + const channel = 'Quote"Name.event' + const oldCalls: string[] = [] + const selectedCalls: string[] = [] + const nativeCalls: string[] = [] + const off = engine.onNotification((received, payload) => { + if (received === channel) nativeCalls.push(payload) + }) + let selected: { unlisten: () => void | Promise } | undefined + try { + const candidate = templateQuery`LISTEN ${identifier`${channel}`}` + await expect(engine.query(candidate.query, candidate.params)).rejects.toMatchObject({ + code: '42601', + }) + const quoted = ( + await engine.query<{ identifier: string }>('SELECT quote_ident($1) AS identifier', [channel]) + ).rows[0]!.identifier + const oldUnlisten = await engine.listen(quoted, (payload) => oldCalls.push(payload)) + selected = await adapter._listen('event', (payload) => selectedCalls.push(payload)) + await adapter._notify('event', { jobId: 'native-control' }) + expect(nativeCalls).toEqual(['{"jobId":"native-control"}']) + expect(selectedCalls).toEqual(nativeCalls) + expect(oldCalls).toEqual([]) // SQL subscription exists, but old map key disagrees. + await oldUnlisten() + // The installed map path can fulfill without releasing the native channel. + expect( + (await engine.query<{ channel: string }>('SELECT pg_listening_channels() AS channel')).rows, + ).toEqual([{ channel }]) + await selected.unlisten() + expect((await engine.query('SELECT pg_listening_channels()')).rows).toEqual([]) + } finally { + off() + await selected?.unlisten() + await adapter.stop() + expect(engine.closed).toBe(true) + await instance.deleteDb() + } +}) + +const jobOptions = { + queue: 'notification-test', + groupKey: 'notification-test', + input: {}, + timeoutMs: 30_000, + checksum: 'notification-test', + concurrencyLimit: 1, + concurrencyStepLimit: 1, +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Notifications with ${factory.name}`, () => { + for (const method of [ + 'createJob', + 'retryJob', + 'completeJob', + 'failJob', + 'cancelJob', + 'timeTravelJob', + ] as const) { + for (const schedule of ['before delivery', 'after delivery'] as const) { + it(`preserves ${method} result and committed state on rejected reply ${schedule}, without replay`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as NotificationProbe + adapter.setId('mutation-reply-fault') + const reports = captureErrors(adapter) + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + const readState = async (id: string) => { + const statement = + 'SELECT id, status FROM duron.jobs_active WHERE id = $1 UNION ALL SELECT id, status FROM duron.jobs_archive WHERE id = $1' + return observer + ? [...(await observer.unsafe(statement, [id]))] + : (await adapter.db.$client.query!(statement, [id])).rows + } + const failure = new Error(`injected rejected reply ${schedule}`) + let restore = noop + let hook: ReturnType | undefined + let attempts = 0 + let notifiedId = '' + let committed: Row[] = [] + let timer: ReturnType | undefined + try { + await adapter.start() + let jobId: string | null = null + let stepId = '' + if (method !== 'createJob') { + jobId = await adapter.createJob(jobOptions) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId!]) + if (method === 'timeTravelJob') { + const step = await adapter.createOrRecoverJobStep({ + jobId: jobId!, + name: 'target', + timeoutMs: 30_000, + retriesLimit: 3, + }) + expect(step).not.toBeNull() + stepId = step!.id + expect(await adapter.completeJobStep({ stepId, output: { retained: true } })).toBe( + true, + ) + expect( + await adapter.completeJob({ jobId: jobId!, output: { retained: true } }), + ).toBe(true) + } + if (method === 'retryJob') + expect( + await adapter.failJob({ jobId: jobId!, error: { message: 'retry fixture' } }), + ).toBe(true) + } + const terminal = + method === 'completeJob' + ? 'completed' + : method === 'failJob' + ? 'failed' + : method === 'cancelJob' + ? 'cancelled' + : null + const event = terminal ? 'job-status-changed' : 'job-available' + const received = Promise.withResolvers() + const deliveries: unknown[] = [] + // Install a new native handle after fixture notifications have settled. + // It observes actual delivery, not a successful submission reply. + const listen = adapter._listen.bind(adapter) + const handle = await listen(event, (payload) => { + const value: unknown = JSON.parse(payload) + deliveries.push(value) + received.resolve(value) + }) + try { + hook = spyOn(adapter, `_${method}`) + restore = interceptSubmission(adapter, async (channel, payload, native) => { + attempts++ + const decoded = JSON.parse(payload) as { jobId: string } + notifiedId = decoded.jobId + committed = await readState(notifiedId) + expect(committed).toEqual([{ id: notifiedId, status: terminal ?? 'created' }]) + expect(channel).toBe(`duron.${event}`) + const expected = terminal + ? { jobId: notifiedId, status: terminal, clientId: 'mutation-reply-fault' } + : { jobId: notifiedId } + expect(decoded).toEqual(expected) + if (schedule === 'after delivery') { + await native() + expect( + await Promise.race([ + received.promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error('Native delivery not observed')), + 2_000, + ) + }), + ]), + ).toEqual(expected) + } + throw failure + }) + const result = + method === 'createJob' + ? await adapter.createJob(jobOptions) + : method === 'retryJob' + ? await adapter.retryJob({ jobId: jobId! }) + : method === 'completeJob' + ? await adapter.completeJob({ jobId: jobId!, output: { saved: true } }) + : method === 'failJob' + ? await adapter.failJob({ + jobId: jobId!, + error: { message: 'saved failure' }, + }) + : method === 'cancelJob' + ? await adapter.cancelJob({ jobId: jobId! }) + : await adapter.timeTravelJob({ jobId: jobId!, stepId }) + expect(result).toBe( + method === 'createJob' || method === 'retryJob' ? notifiedId : true, + ) + expect(await readState(notifiedId)).toEqual(committed) + expect(await adapter.getJobById(notifiedId)).toMatchObject({ + id: notifiedId, + status: terminal ?? 'created', + }) + expect(hook).toHaveBeenCalledTimes(1) + expect(attempts).toBe(1) + expect(deliveries).toHaveLength(schedule === 'after delivery' ? 1 : 0) + expect(reports).toHaveLength(1) + expect(reports[0]).toMatchObject({ + err: failure, + stage: 'submission', + jobId: notifiedId, + mutationResult: 'unchanged', + delivery: 'unconfirmed', + }) + expect(reports[0]).not.toHaveProperty('data') + } finally { + restore() + hook?.mockRestore() + await handle.unlisten() + } + } finally { + clearTimeout(timer) + restore() + hook?.mockRestore() + await adapter.stop() + await observer?.end({ timeout: 5 }) + await instance.deleteDb() + } + }) + } + } + + for (const withLogger of [true, false]) { + it(`catches preparation failure after real cancellation (logger ${withLogger})`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as NotificationProbe + adapter.setId('preparation-fault') + const reports = withLogger ? captureErrors(adapter) : [] + const notify = adapter._notify.bind(adapter) + const failure = new Error('injected JSON preparation failure') + let attempts = 0 + let restore = noop + try { + const jobId = await adapter.createJob(jobOptions) + restore = interceptSubmission(adapter, async () => { + attempts++ + throw new Error('Unexpected submission') + }) + adapter._notify = async (event, data) => { + expect(await adapter.getJobById(jobId!)).toMatchObject({ status: 'cancelled' }) + // Fault only JSON preparation; preserve built-in dispatch and payload IDs. + await notify(event, { + ...(data as object), + toJSON() { + throw failure + }, + }) + } + expect(await adapter.cancelJob({ jobId: jobId! })).toBe(true) + expect(await adapter.getJobById(jobId!)).toMatchObject({ status: 'cancelled' }) + expect(attempts).toBe(0) + expect(reports).toHaveLength(withLogger ? 1 : 0) + if (withLogger) + expect(reports[0]).toMatchObject({ + err: failure, + stage: 'preparation', + jobId, + delivery: 'unconfirmed', + mutationResult: 'unchanged', + }) + } finally { + adapter._notify = notify + restore() + await adapter.stop() + await instance.deleteDb() + } + }) + } + + it('preserves false/null, mutation/schema failures and custom override dispatch outside transport policy', async () => { + const instance = await factory.create() + const adapter = instance.adapter as NotificationProbe + adapter.setId('wrapper-contracts') + const failure = new Error('outside built-in emission policy') + const notify = adapter._notify.bind(adapter) + let attempts = 0 + adapter._notify = async () => { + attempts++ + throw failure + } + try { + await adapter.start() + const jobId = crypto.randomUUID() + expect(await adapter.completeJob({ jobId, output: {} })).toBe(false) + expect(await adapter.failJob({ jobId, error: { message: 'missing' } })).toBe(false) + expect(await adapter.cancelJob({ jobId })).toBe(false) + expect(await adapter.retryJob({ jobId })).toBeNull() + expect(await adapter.timeTravelJob({ jobId, stepId: crypto.randomUUID() })).toBe(false) + // Built-in INSERT normally returns an ID; null/invalid/throwing hook + // controls explicitly test the public extension/result-validation boundary. + const hook = spyOn(adapter, '_createJob') + try { + hook.mockResolvedValueOnce(null) + expect(await adapter.createJob(jobOptions)).toBeNull() + hook.mockResolvedValueOnce(undefined as never) + await expect(adapter.createJob(jobOptions)).rejects.toThrow() + hook.mockRejectedValueOnce(failure) + await expect(adapter.createJob(jobOptions)).rejects.toBe(failure) + await expect( + adapter.createJob({ ...jobOptions, queue: undefined as never }), + ).rejects.toThrow() + expect(hook).toHaveBeenCalledTimes(3) + expect(attempts).toBe(0) + } finally { + hook.mockRestore() + } + // A custom notification override still controls its own failure contract. + await expect(adapter.createJob(jobOptions)).rejects.toBe(failure) + expect(attempts).toBe(1) + } finally { + adapter._notify = notify + await adapter.stop() + await instance.deleteDb() + } + }) + + it('does not shield a throwing custom error logger', async () => { + const instance = await factory.create() + const adapter = instance.adapter as NotificationProbe + adapter.setId('logger-fault') + const failure = new Error('custom logger failure') + const logger = pino({ level: 'silent' }) + let restore = noop + try { + const jobId = await adapter.createJob(jobOptions) + logger.error = () => { + throw failure + } + adapter.setLogger(logger) + restore = interceptSubmission(adapter, async () => { + throw new Error('transport failure') + }) + await expect(adapter.cancelJob({ jobId: jobId! })).rejects.toBe(failure) + expect(await adapter.getJobById(jobId!)).toMatchObject({ status: 'cancelled' }) + } finally { + restore() + await adapter.stop() + await instance.deleteDb() + } + }) + + it('delivers exact configured channels, preserves duplicate callbacks and releases owned native resources', async () => { + // Protected transport fixture, NOT a claim of custom-schema migrations. + const schema = `MiX.'".λ` + const instance = await factory.create({ schema, migrateOnStart: false }) + const adapter = instance.adapter as NotificationProbe + adapter.setId('native-channel-control') + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + const first: string[] = [] + const second: string[] = [] + const unrelated: string[] = [] + const handles: { unlisten: () => void | Promise }[] = [] + const delivery = async (data: unknown, event = 'Exact.Event') => { + const received = Promise.withResolvers() + const barrier = await adapter._listen(event, () => received.resolve()) + let timer: ReturnType | undefined + try { + await adapter._notify(event, data) + await Promise.race([ + received.promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error('Missing native exact-channel delivery')), + 2_000, + ) + }), + ]) + } finally { + clearTimeout(timer) + await barrier.unlisten() + } + } + try { + const a = await adapter._listen('Exact.Event', (payload) => first.push(payload)) + const b = await adapter._listen('Exact.Event', (payload) => second.push(payload)) + const other = await adapter._listen('exact.event', (payload) => unrelated.push(payload)) + handles.push(a, b, other) + if (observer) { + // Force a query connection as well as the real dedicated LISTEN pool. + await adapter.db.$client.unsafe!('SELECT 1') + const sessions = + await observer`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + expect(sessions.length).toBeGreaterThanOrEqual(2) + } else { + const rows = ( + await adapter.db.$client.query!<{ channel: string }>( + 'SELECT pg_listening_channels() AS channel', + ) + ).rows + expect(rows.map((row) => row.channel)).toContain(`${schema}.Exact.Event`) + expect(rows.map((row) => row.channel)).toContain(`${schema}.exact.event`) + } + await delivery({ jobId: 'unrelated' }, 'exact.event') + expect(first).toEqual([]) + expect(second).toEqual([]) + const payload = { jobId: `O'Reilly."λ`, status: 'completed', clientId: `Case.'".λ` } + await delivery(payload) + expect(first).toEqual([JSON.stringify(payload)]) + expect(second).toEqual(first) + expect(unrelated).toEqual(['{"jobId":"unrelated"}']) + await a.unlisten() + await a.unlisten() + await delivery({ jobId: 'second' }) + expect(first).toHaveLength(1) + expect(second).toHaveLength(2) + await b.unlisten() + // Re-register only an observer: native delivery proves old callbacks were + // removed, not merely hidden by an unsubscribed channel. + await delivery({ jobId: 'observer only' }) + expect(first).toHaveLength(1) + expect(second).toHaveLength(2) + if (!observer) { + const rows = ( + await adapter.db.$client.query!<{ channel: string }>( + 'SELECT pg_listening_channels() AS channel', + ) + ).rows + expect(rows.map((row) => row.channel)).not.toContain(`${schema}.Exact.Event`) + expect(rows.map((row) => row.channel)).toContain(`${schema}.exact.event`) + } + } finally { + for (const handle of handles) await handle.unlisten() + await adapter.stop() + if (observer) { + expect( + await observer`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()`, + ).toHaveLength(0) + await observer.end({ timeout: 5 }) + } + await instance.deleteDb() + } + }) + + it.each(['a'.repeat(57), `${'λ'.repeat(28)}a`])( + 'preserves native byte limits without truncation or replay: %s', + async (event) => { + const instance = await factory.create({ migrateOnStart: false }) + const adapter = instance.adapter as NotificationProbe + adapter.setId('native-byte-limits') + const reports = captureErrors(adapter) + const encoder = new TextEncoder() + // duron. is six bytes; both ASCII and Unicode full channels are 63 bytes. + const deliveries: string[] = [] + const received = Promise.withResolvers() + const handle = await adapter._listen(event, (payload) => { + deliveries.push(payload) + received.resolve() + }) + let timer: ReturnType | undefined + try { + const data = { jobId: 'x'.repeat(7987) } + expect(encoder.encode(JSON.stringify(data))).toHaveLength(7999) + expect(encoder.encode(`duron.${event}`)).toHaveLength(63) + await adapter._notify(event, data) + await Promise.race([ + received.promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('Missing 7999-byte payload')), 2_000) + }), + ]) + expect(deliveries).toEqual([JSON.stringify(data)]) + expect(reports).toEqual([]) + await adapter._notify(`${event}a`, { jobId: '64 byte channel' }) + const unicodeEvent = 'λ'.repeat(30) // prefix6 +60 =66 bytes, not36 characters. + expect(encoder.encode(`duron.${unicodeEvent}`)).toHaveLength(66) + await adapter._notify(unicodeEvent, { jobId: '66 byte channel' }) + await adapter._notify(event, { jobId: 'x'.repeat(7988) }) + expect(reports).toHaveLength(3) + for (const report of reports) { + expect(report).toMatchObject({ + stage: 'submission', + delivery: 'unconfirmed', + mutationResult: 'unchanged', + }) + expect(report).not.toHaveProperty('data') + expect((report as { err: { code: string } }).err.code).toBe('22023') + } + expect(deliveries).toHaveLength(1) + } finally { + clearTimeout(timer) + await handle.unlisten() + await adapter.stop() + await instance.deleteDb() + } + }, + ) + + it('awaits a stuck issued hint and retains actual-work accounting through the shared drain deadline', async () => { + const instance = await factory.create() + const adapter = instance.adapter as NotificationProbe + adapter.setId('pending-notification') + const reports = captureErrors(adapter) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const failure = new Error('injected late notification reply failure') + const close = adapter._close.bind(adapter) + let restore = noop + let operation: Promise | undefined + let settled = false + let attempts = 0 + let closes = 0 + let livenessAtClose: Row[] = [] + try { + const jobId = await adapter.createJob(jobOptions) + await adapter.heartbeat() + restore = interceptSubmission(adapter, async (_channel, _payload, native) => { + attempts++ + await native() + entered.resolve() + await release.promise + throw failure + }) + adapter._close = async () => { + closes++ + const driver = adapter.db.$client + const statement = 'SELECT client_id AS id FROM duron.clients WHERE client_id = $1' + livenessAtClose = driver.query + ? (await driver.query(statement, ['pending-notification'])).rows + : [...(await driver.unsafe!(statement, ['pending-notification']))] + await close() + } + operation = adapter.cancelJob({ jobId: jobId! }).finally(() => { + settled = true + }) + void operation.catch(() => undefined) + let admissionTimer: ReturnType | undefined + try { + await Promise.race([ + entered.promise, + new Promise((_, reject) => { + admissionTimer = setTimeout( + () => reject(new Error('Notification was not issued')), + 2_000, + ) + }), + ]) + } finally { + clearTimeout(admissionTimer) + } + expect(await adapter.getJobById(jobId!)).toMatchObject({ status: 'cancelled' }) + expect(settled).toBe(false) + const started = performance.now() + const stopped = await adapter.stop().catch((error: unknown) => error) + expect(stopped).toBeInstanceOf(AggregateError) + expect( + (stopped as AggregateError).errors.some((error) => + String(error).includes('admitted-work drain exceeded five seconds'), + ), + ).toBe(true) + expect(performance.now() - started).toBeGreaterThanOrEqual(4_900) + expect(closes).toBe(1) + expect(livenessAtClose).toEqual([{ id: 'pending-notification' }]) + expect(settled).toBe(false) + release.resolve() + expect(await operation).toBe(true) + expect(attempts).toBe(1) + expect(reports).toHaveLength(1) + expect(reports[0]).toMatchObject({ + err: failure, + stage: 'submission', + mutationResult: 'unchanged', + delivery: 'unconfirmed', + }) + // Actual late settlement does not retroactively release liveness on a + // closed resource or convert the earlier incomplete stop into success. + await expect(adapter.stop()).rejects.toThrow() + expect(closes).toBe(1) + } finally { + release.resolve() + await operation?.catch(() => undefined) + restore() + adapter._close = close + await adapter.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 20_000) + + it('preserves a committed cancellation when submission throws synchronously', async () => { + const instance = await factory.create() + const adapter = instance.adapter as NotificationProbe + adapter.setId('sync-notification-fault') + const reports = captureErrors(adapter) + const failure = new Error('injected synchronous notification submission') + let attempts = 0 + let restore = noop + try { + const jobId = await adapter.createJob(jobOptions) + restore = interceptSubmission(adapter, () => { + attempts++ + throw failure + }) + expect(await adapter.cancelJob({ jobId: jobId! })).toBe(true) + expect(await adapter.getJobById(jobId!)).toMatchObject({ status: 'cancelled' }) + expect(attempts).toBe(1) + expect(reports).toHaveLength(1) + expect(reports[0]).toMatchObject({ + err: failure, + backend: factory.name === 'postgres' ? 'PostgresAdapter' : 'PGLiteAdapter', + event: 'job-status-changed', + channel: 'duron.job-status-changed', + stage: 'submission', + jobId, + clientId: 'sync-notification-fault', + mutationResult: 'unchanged', + delivery: 'unconfirmed', + }) + expect(reports[0]).not.toHaveProperty('data') + } finally { + restore() + await adapter.stop() + await instance.deleteDb() + } + }) + it('delivers the unchanged terminal payload with a quote-bearing public adapter ID', async () => { + const instance = await factory.create() + const adapter: Adapter = instance.adapter + const clientId = `O'Reilly."Mixed.λ` + adapter.setId(clientId) + const received = Promise.withResolvers() + let timer: ReturnType | undefined + try { + const jobId = await adapter.createJob(jobOptions) + adapter.on('job-status-changed', (payload) => received.resolve(payload)) + expect(await adapter.cancelJob({ jobId: jobId! })).toBe(true) + expect(await adapter.getJobById(jobId!)).toMatchObject({ status: 'cancelled' }) + expect( + await Promise.race([ + received.promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('No terminal hint received')), 2_000) + }), + ]), + ).toEqual({ jobId, status: 'cancelled', clientId }) + } finally { + clearTimeout(timer) + await adapter.stop() + await instance.deleteDb() + } + }) + }) +} From 5ac7228cf3c3299e8b6403b1bf6c36bbdbca98cc Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 7 Nov 2026 21:05:19 -0300 Subject: [PATCH 007/100] Coordinate scheduled archive pruning on an owned session Bootstrap an isolated PostgreSQL lock client and retain one same-backend reservation for scheduled key42 ownership. Keep DELETEs and custom prune hooks on the original pool, with busy-tick skipping and scheduled-only continuation gates after loss. Integrate reservation return and prompt fault close with the shared lifecycle ledger, retaining original errors independently from positive resource release. Preserve manual pruning, partial commits and PGLite engine usability; document healthy-session-only exclusion. Add native transport, ownership, cleanup, error and both-engine regressions. Verification: root typecheck/lint/fmt/core build; root tests 307/0; full POSTGRES_TEST=true tests 596/0; focused prune 46/0. Independent Standards and Spec source reviews resolved Required findings. Node runtime remains untested; source/build compatibility only. Candidate awaits separate human acceptance. --- packages/docs/content/docs/adapters.mdx | 34 + packages/duron/src/adapters/postgres/base.ts | 152 +++- .../duron/src/adapters/postgres/postgres.ts | 18 + .../duron/src/adapters/postgres/prune-lock.ts | 181 ++++ packages/duron/src/lifecycle.ts | 22 +- .../duron/test/lifecycle-background.test.ts | 18 +- packages/duron/test/prune-batches.test.ts | 140 ++++ packages/duron/test/prune-bootstrap.test.ts | 344 ++++++++ packages/duron/test/prune-cadence.test.ts | 202 +++++ packages/duron/test/prune-loss.test.ts | 168 ++++ packages/duron/test/prune-ownership.test.ts | 787 ++++++++++++++++++ .../duron/test/prune-pglite-faults.test.ts | 107 +++ packages/duron/test/prune-relay.ts | 143 ++++ packages/duron/test/prune-replies.test.ts | 141 ++++ packages/duron/test/prune-scheduler.test.ts | 361 ++++++++ packages/duron/test/prune-scope.test.ts | 177 ++++ packages/duron/test/prune-transport.test.ts | 181 ++++ 17 files changed, 3124 insertions(+), 52 deletions(-) create mode 100644 packages/duron/src/adapters/postgres/prune-lock.ts create mode 100644 packages/duron/test/prune-batches.test.ts create mode 100644 packages/duron/test/prune-bootstrap.test.ts create mode 100644 packages/duron/test/prune-cadence.test.ts create mode 100644 packages/duron/test/prune-loss.test.ts create mode 100644 packages/duron/test/prune-ownership.test.ts create mode 100644 packages/duron/test/prune-pglite-faults.test.ts create mode 100644 packages/duron/test/prune-relay.ts create mode 100644 packages/duron/test/prune-replies.test.ts create mode 100644 packages/duron/test/prune-scheduler.test.ts create mode 100644 packages/duron/test/prune-scope.test.ts create mode 100644 packages/duron/test/prune-transport.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 6e5eced..9a1e70c 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -66,6 +66,40 @@ const client = duron({ }) ``` +## Archive retention + +Retention is opt-in for both adapters. Without `pruneArchive`, the adapter creates no prune timer or PostgreSQL lock client. + +```ts +const adapter = postgresAdapter({ + connection: process.env.DATABASE_URL!, + pruneArchive: { + olderThan: '7d', + intervalMs: 60_000, + batchSize: 1000, // Default + maxBatches: 100, // Default per pass + }, +}) +``` + +The scheduler attempts a pass immediately during startup, then at the configured interval. A tick skips if the previous acquisition, prune hook or unlock is still pending; skipped ticks are not queued. A contended lock also skips that pass. A prune error followed by a successful unlock is logged and permits the next normal tick. `lastPrunedAt` records successful scheduled hook completion, not successful unlock or proof of coordination. + +### PostgreSQL ownership and scope + +An opted-in adapter owns one additional, max-one postgres.js client for coordination. It first performs an ordinary read-only backend-identity query, then reserves that same ready backend once for the scheduler lifetime. Initial driver setup attempts are permitted only while that first bootstrap is pending. After bootstrap succeeds, coordination never reconnects or replaces the session. Each pass acquires session-level advisory key `42` and must receive a true unlock; the reservation is not returned between passes. + +Key `42` coordinates **across schemas in the same database**, not just one Duron schema. Separate databases do not contend. Avoid using this advisory key for unrelated application locks. DELETEs still run on the adapter's original query pool, including when that pool has `max: 1`. Custom `_pruneArchive` overrides remain in the dispatch path and can delegate to `super._pruneArchive`. + +Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replace the client, replay pruning or close the normal query/listener resources. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. + +### Manual pruning and failure limits + +`adapter.pruneArchive({ olderThan, batchSize, maxBatches })` remains outside scheduled coordination. Manual calls can overlap a scheduled pass or one another. `olderThan` accepts a duration string, a `Date`, or an absolute timestamp in milliseconds; rows with `finished_at` strictly before the cutoff are eligible. The returned count is the number of deleted jobs. Batches commit independently: a later failure does not roll back an earlier committed DELETE, and the library does not replay an issued DELETE. Future normal ticks can prune rows that remain eligible. Manual calls do not update the scheduled `lastPrunedAt` value. + +**Exclusion requires a healthy coordination session.** After its loss, another scheduler can acquire the lock while an already-issued DELETE continues on the old owner's query pool. Observed loss gates subsequent library-controlled scheduled SQL, but it does not cancel issued SQL or arbitrary override code. There is no fencing, rollback, instantaneous loss detection, or failure-proof mutual exclusion promise, and no ordinary prune SQL/pass deadline. + +Stop clears the timer immediately and uses the shared lifecycle's startup-settlement, admitted-work, database-cleanup and owned-close budgets. Healthy final cleanup returns the reservation once after settled work and confirmed unlock, then closes the isolated client. Uncertain ownership is not returned as reusable. A pending/rejected return cannot consume the independent close opportunity; a stop that joins an existing fault close does not restart its five-second observer. Observer expiry and fulfilled driver `end()` alone are not proof of physical release. Incomplete cleanup remains reported and tracked for later safe completion rather than being canceled or silently declared successful. + ## Database Schema Duron creates the following tables in your database: diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 7f7063f..841c470 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1,3 +1,5 @@ +import { AsyncLocalStorage } from 'node:async_hooks' + import { type SQL, and, @@ -26,7 +28,7 @@ import { STEP_STATUS_COMPLETED, STEP_STATUS_FAILED, } from '../../constants.js' -import { lifecycleFor } from '../../lifecycle.js' +import { lifecycleFor, throwLifecycleErrors } from '../../lifecycle.js' import { Adapter, type ArchiveStats, @@ -97,6 +99,11 @@ export abstract class PostgresBaseAdapter< // Scheduler state private pruneTimer: ReturnType | null = null + private pruneRunning = false + private pruneRetired = false + private pruneCoordinationErrors: unknown[] = [] + private pruneFaultClose: Promise | undefined + private readonly scheduledPrune = new AsyncLocalStorage() private pruneConfig: PruneSchedulerConfig | null = null private lastPrunedAt: Date | null = null private initialized = false @@ -133,6 +140,9 @@ export abstract class PostgresBaseAdapter< protected abstract _initDb(): void protected _assertSql(): void { + if (this.scheduledPrune.getStore() && this.pruneRetired) { + throw new Error('Scheduled prune coordination is retired') + } lifecycleFor(this).assertContinuation() if (!this._canCleanup()) throw new Error('Lifecycle SQL resources are unavailable') } @@ -323,16 +333,52 @@ export abstract class PostgresBaseAdapter< // Scheduler Methods // ============================================================================ - /** - * Generate a consistent advisory lock key from the schema name. - */ - /** - * Returns a fixed advisory lock key for the prune scheduler. - * Uses a fixed key (42) since Duron is a single-schema system. - * Multiple schemas would each get their own lock via the schema-prefixed table names. - */ - private _advisoryLockKey(): number { - return 42 + /** Scheduled pruning coordinates across schemas in the same database. */ + protected async _acquirePruneLock(): Promise { + const result = await this.db.execute(sql`SELECT pg_try_advisory_lock(42) AS acquired`) + const rows = this._map(result) + if (rows.length !== 1 || typeof rows[0]?.acquired !== 'boolean') { + throw new Error('Malformed scheduled prune acquisition result') + } + return rows[0].acquired + } + + protected async _releasePruneLock(): Promise { + const result = await this.db.execute(sql`SELECT pg_advisory_unlock(42) AS released`) + const rows = this._map(result) + if (rows.length !== 1 || rows[0]?.released !== true) { + throw new Error('False or malformed scheduled prune unlock result') + } + } + + protected _retirePruning(error: unknown): void { + this.pruneCoordinationErrors.push(error) + this.pruneRetired = true + this._stopScheduler() + if (!lifecycleFor(this).accepting) return + // The hook uses the other query pool and may remain pending indefinitely. + // Start isolated cleanup now; retain this observer's outcome for the pass's + // ordered error report instead of replacing it with a later cached success. + const closing = (this.pruneFaultClose ??= this._closePruneLock()) + if (this.pruneRunning) { + void closing.catch(() => undefined) + } else { + void closing + .catch((closeError) => { + throw new AggregateError( + [error, closeError], + 'Prune coordination and isolated close failed', + ) + }) + .then( + () => this.logger?.error(error, 'Scheduled prune coordination retired'), + (failure) => this.logger?.error(failure, 'Scheduled prune coordination retired'), + ) + } + } + + protected async _closePruneLock(): Promise { + // PGLite has no isolated resource: its engine stays available until normal stop. } /** @@ -344,35 +390,65 @@ export abstract class PostgresBaseAdapter< if (!config || !lifecycle.accepting) return const run = () => { - if (!lifecycle.accepting) return Promise.resolve() - return lifecycle.run(async () => { - try { - // Try to acquire advisory lock - const lockResult = await this.db.execute<{ pg_try_advisory_lock: boolean }>( - sql`SELECT pg_try_advisory_lock(${this._advisoryLockKey()})`, - ) - - if (!lockResult[0]?.pg_try_advisory_lock) { - this.logger?.debug('Another process holds the prune lock, skipping') - return - } - + if (!lifecycle.accepting || this.pruneRetired || this.pruneRunning) return Promise.resolve() + this.pruneRunning = true + return lifecycle + .run(async () => { + const coordinationStart = this.pruneCoordinationErrors.length + const pruneErrors: unknown[] = [] + let acquired = false try { - this.logger?.info('Running scheduled archive prune') - const deleted = await this._pruneArchive({ - olderThan: config.olderThan, - batchSize: config.batchSize, - maxBatches: config.maxBatches, - }) - this.lastPrunedAt = new Date() - this.logger?.info({ deletedJobs: deleted }, 'Archive prune completed') - } finally { - await this.db.execute(sql`SELECT pg_advisory_unlock(${this._advisoryLockKey()})`) + acquired = await this._acquirePruneLock() + } catch (error) { + this._retirePruning(error) } - } catch (error) { - this.logger?.error(error, 'Error in prune scheduler') - } - }) + if (acquired) { + try { + // A late acquisition must not start a hook after stop or loss. + if (lifecycle.accepting && !this.pruneRetired) { + const deleted = await this.scheduledPrune.run(true, () => + this._pruneArchive({ + olderThan: config.olderThan, + batchSize: config.batchSize, + maxBatches: config.maxBatches, + }), + ) + this.lastPrunedAt = new Date() + this.logger?.info({ deletedJobs: deleted }, 'Archive prune completed') + } + } catch (error) { + pruneErrors.push(error) + } finally { + try { + await this._releasePruneLock() + } catch (error) { + this._retirePruning(error) + } + } + } + const closeErrors: unknown[] = [] + // Observe a started fault close even if stop has since quiesced the + // adapter. Positive resource release does not erase its earlier error. + if (this.pruneFaultClose || (this.pruneRetired && lifecycle.accepting)) { + try { + await (this.pruneFaultClose ??= this._closePruneLock()) + } catch (error) { + closeErrors.push(error) + } + } + throwLifecycleErrors( + [ + ...pruneErrors, + ...this.pruneCoordinationErrors.slice(coordinationStart), + ...closeErrors, + ], + 'Scheduled prune failed: prune first, then coordination/release/close failures', + ) + }) + .catch((error) => this.logger?.error(error, 'Error in prune scheduler')) + .finally(() => { + this.pruneRunning = false + }) } // Run immediately on start, then on interval diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index c12aaa8..74de41c 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -8,6 +8,7 @@ import type { Options as PostgresOptions } from 'postgres' import { lifecycleFor } from '../../lifecycle.js' import { type AdapterOptions, PostgresBaseAdapter } from './base.js' +import { PostgresPruneLock } from './prune-lock.js' import type createSchema from './schema.js' // Only the table entries (exclude the `schema` PgSchema object) @@ -29,6 +30,23 @@ export type DB = ReturnType | string> { + private pruneLock: PostgresPruneLock | undefined + + protected override _acquirePruneLock(): Promise { + this.pruneLock ??= new PostgresPruneLock(this.connection, lifecycleFor(this), (error) => + this._retirePruning(error), + ) + return this.pruneLock.acquire() + } + + protected override async _releasePruneLock(): Promise { + await this.pruneLock?.release() + } + + protected override async _closePruneLock(): Promise { + await this.pruneLock?.faultClose() + } + /** * Initialize the database connection and Drizzle instance. */ diff --git a/packages/duron/src/adapters/postgres/prune-lock.ts b/packages/duron/src/adapters/postgres/prune-lock.ts new file mode 100644 index 0000000..50ef97e --- /dev/null +++ b/packages/duron/src/adapters/postgres/prune-lock.ts @@ -0,0 +1,181 @@ +import postgres, { type Options, type ReservedSql, type Sql } from 'postgres' + +import type { Lifecycle } from '../../lifecycle.js' + +/** One opt-in lock-only backend. DELETEs continue on the adapter's query pool. */ +export class PostgresPruneLock { + // Internal transport ownership; this helper is not a package entrypoint. + readonly client: Sql + readonly #obligation: ReturnType + readonly #returnObligation: ReturnType + #resolveClosed!: () => void + #closed = this.#observeNativeClose() + #session: ReservedSql | undefined + #setup: Promise | undefined + #close: Promise | undefined + #pid: number | undefined + #bootstrapPending = false + #bootstrapSucceeded = false + #uncertain = false + #closing = false + #physicallyClosed = false + #endSettled = false + #lock: 'none' | 'held' | 'unknown' = 'none' + + constructor( + connection: Options | string, + readonly lifecycle: Lifecycle, + readonly retire: (error: unknown) => void, + ) { + const options: Options = { + ...(typeof connection === 'string' ? {} : connection), + max: 1, + idle_timeout: 0, + max_lifetime: null, + onnotice: () => undefined, + onclose: () => { + // Setup may permit another attempt, but do not discard the native close + // observation if the pending bootstrap subsequently rejects instead. + this.#physicallyClosed = true + this.#resolveClosed() + if (!this.#closing && this.#bootstrapPending && !this.#bootstrapSucceeded) return + this.#confirmClosed() + if (this.#closing) return + this.#uncertain = true + this.retire(new Error('Scheduled prune coordination session was lost')) + }, + } + this.client = typeof connection === 'string' ? postgres(connection, options) : postgres(options) + this.#returnObligation = lifecycle.obligation( + 'scheduled prune lock release and reservation return', + 'database cleanup', + () => this.#returnReservation(), + () => !this.#closing && (!this.#uncertain || this.#physicallyClosed), + ) + this.#obligation = lifecycle.obligation('scheduled prune lock client', 'owned close', () => + this.close(), + ) + } + + #observeNativeClose(): Promise { + return new Promise((resolve) => { + this.#resolveClosed = resolve + }) + } + + async #establish(): Promise { + this.#bootstrapPending = true + try { + const rows = await this.client<{ pid: number }[]>`SELECT pg_backend_pid() AS pid` + this.#bootstrapSucceeded = true + if (!this.#closing) { + // A successful permitted setup attempt supersedes an earlier setup close, + // but a late reply after owned close must not erase its positive evidence. + this.#physicallyClosed = false + this.#closed = this.#observeNativeClose() + } + if (rows.length !== 1 || typeof rows[0]?.pid !== 'number') { + throw new Error('Malformed scheduled prune bootstrap identity') + } + this.#pid = rows[0].pid + // No await between bootstrap success and reserve: the exclusive client's + // ready connection must not become a new connection-establishment attempt. + if (!this.lifecycle.accepting || this.#uncertain || this.#closing) return false + this.#session = await this.client.reserve() + if (!this.lifecycle.accepting || this.#uncertain || this.#closing) return false + const identity = await this.#session<{ pid: number }[]>`SELECT pg_backend_pid() AS pid` + if (identity.length !== 1 || identity[0]?.pid !== this.#pid) { + throw new Error('Scheduled prune reservation changed backend identity') + } + return true + } catch (error) { + // A failed transition cannot establish safe reservation ownership, even + // when the transport is still alive and its observed PID is malformed. + this.#uncertain = true + throw error + } finally { + this.#bootstrapPending = false + } + } + + async acquire(): Promise { + this.#setup ??= this.#establish() + if (!(await this.#setup) || !this.lifecycle.accepting || this.#uncertain || this.#closing) { + return false + } + this.lifecycle.assertContinuation() + this.#lock = 'unknown' + const rows = await this.#session!<{ pid: number; acquired: boolean }[]>` + SELECT pg_backend_pid() AS pid, pg_try_advisory_lock(42) AS acquired + ` + if (rows.length !== 1 || rows[0]?.pid !== this.#pid || typeof rows[0]?.acquired !== 'boolean') { + throw new Error('Malformed scheduled prune acquisition or changed backend') + } + this.#lock = rows[0]!.acquired ? 'held' : 'none' + return rows[0]!.acquired + } + + async release(): Promise { + if (this.#uncertain || this.#closing) return + this.lifecycle.assertContinuation() + this.#lock = 'unknown' + const rows = await this.#session!<{ pid: number; released: boolean }[]>` + SELECT pg_backend_pid() AS pid, pg_advisory_unlock(42) AS released + ` + if (rows.length !== 1 || rows[0]?.pid !== this.#pid || rows[0]?.released !== true) { + throw new Error('False or malformed scheduled prune unlock or changed backend') + } + this.#lock = 'none' + } + + faultClose(): Promise { + return this.#obligation.observeEarlyClose() + } + + async #returnReservation(): Promise { + // Setup may settle after the drain observer. It stays observed and cannot + // allocate a reservation after the stop gate; do not mark a pending result safe. + await this.#setup?.catch(() => undefined) + // A natively closed session has no reusable reservation to return. Its + // driver's close operation remains a separate obligation and error source. + if (!this.#session || this.#physicallyClosed) return + if (this.#uncertain || this.#closing || !this.lifecycle.drained) { + throw new Error('Scheduled prune reservation cannot be safely returned') + } + if (this.#lock === 'held') await this.release() + if (this.#lock !== 'none') { + throw new Error('Scheduled prune lock release remains uncertain') + } + try { + await this.#session.release() + } catch (error) { + this.#uncertain = true + throw error + } + } + + #confirmClosed(): void { + if (!this.#physicallyClosed || !this.#endSettled) return + this.#obligation.done = true + this.#returnObligation.done = true + } + + close(): Promise { + this.#close ??= Promise.resolve().then(async () => { + this.#closing = true + // Independent of the database-cleanup return obligation: even its rejected + // or still-pending acknowledgment cannot consume the owned-close opportunity. + try { + await this.client.end({ timeout: 5 }) + if (!this.#physicallyClosed) await this.#closed + this.#obligation.done = true + } finally { + this.#endSettled = true + // A rejected reply remains this attempt's error; actual socket closure + // can nevertheless discharge resources for a later stop caller. + this.#confirmClosed() + } + }) + return this.#close + } +} diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index 0999839..1be5806 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -49,6 +49,23 @@ class CleanupObligation { done = false pending: Promise | null = null failure: { error: unknown } | null = null + #earlyCloseBudget: ShutdownBudget | null = null + + get closingIndependently(): boolean { + return this.#earlyCloseBudget !== null + } + + // An isolated resource can close before global shutdown. The raw attempt stays + // in this same ledger; a later stop observes its original deadline, not a new one. + observeEarlyClose(): Promise { + this.#earlyCloseBudget ??= new ShutdownBudget(this.phase) + return this.observe() + } + + observe(): Promise { + const work = this.attempt() + return this.#earlyCloseBudget && !this.done ? this.#earlyCloseBudget.observe(work) : work + } constructor( readonly name: string, @@ -151,7 +168,8 @@ export class Lifecycle { } get closing(): boolean { for (const task of this.#obligations) { - if (task.phase === 'owned close' && task.pending && !task.done) return true + if (task.phase === 'owned close' && task.pending && !task.done && !task.closingIndependently) + return true } return false } @@ -323,7 +341,7 @@ export class Lifecycle { this.#phase = phase const budget = new ShutdownBudget(phase) const work = obligations.map((task) => - this.#inContext('cleanup', () => task.attempt()).catch((error: unknown) => { + this.#inContext('cleanup', () => task.observe()).catch((error: unknown) => { failures.push({ error, phase, obligation: task.name }) }), ) diff --git a/packages/duron/test/lifecycle-background.test.ts b/packages/duron/test/lifecycle-background.test.ts index f7fb5b5..0a51113 100644 --- a/packages/duron/test/lifecycle-background.test.ts +++ b/packages/duron/test/lifecycle-background.test.ts @@ -1,16 +1,13 @@ import { describe, expect, it } from 'bun:test' -import type { SQL } from 'drizzle-orm' - import { Client } from '../src/client.js' import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' type BackgroundProbe = Adapter & { _close: () => Promise + _acquirePruneLock: () => Promise db: { - execute: (query: SQL) => Promise - dialect: { sqlToQuery: (query: SQL) => { sql: string } } $client: { closed?: boolean close?: () => Promise @@ -87,7 +84,7 @@ for (const factory of [ }) const adapter = instance.adapter as BackgroundProbe adapter.setId(`prune-${name}`) - const execute = adapter.db.execute.bind(adapter.db) + const acquire = adapter._acquirePruneLock.bind(adapter) const close = adapter._close.bind(adapter) const entered = Promise.withResolvers() const release = Promise.withResolvers() @@ -97,12 +94,9 @@ for (const factory of [ let stopped: Promise | undefined // A labelled callback hold AFTER the native lock query settled. This does // not claim new prune-lock correctness or cancel an already-issued query. - adapter.db.execute = async (query) => { - const result = await execute(query) - if ( - adapter.db.dialect.sqlToQuery(query).sql.includes('pg_try_advisory_lock') && - ++lockCalls === target - ) { + adapter._acquirePruneLock = async () => { + const result = await acquire() + if (++lockCalls === target) { entered.resolve() await release.promise } @@ -136,7 +130,7 @@ for (const factory of [ if (timer !== undefined) clearTimeout(timer) release.resolve() await stopped?.catch(() => undefined) - adapter.db.execute = execute + adapter._acquirePruneLock = acquire adapter._close = close await adapter.stop().catch(() => undefined) const driver = adapter.db.$client diff --git a/packages/duron/test/prune-batches.test.ts b/packages/duron/test/prune-batches.test.ts new file mode 100644 index 0000000..e5d7580 --- /dev/null +++ b/packages/duron/test/prune-batches.test.ts @@ -0,0 +1,140 @@ +import { expect, it } from 'bun:test' + +import { sql, type SQL } from 'drizzle-orm' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +type NativePruneAdapter = Adapter & { db: { execute: (query: SQL) => Promise } } + +async function archived(adapter: Adapter, name: string): Promise { + const id = await adapter.createJob({ + queue: 'prune-batches', + groupKey: name, + input: { name }, + timeoutMs: 60_000, + checksum: name, + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(id).toBeDefined() + expect(await adapter.cancelJob({ jobId: id! })).toBe(true) + return id! +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + it(`${factory.name} direct prune preserves exact cutoffs, batch bounds, counts and validation`, async () => { + const { adapter: publicAdapter, deleteDb } = await factory.create() + const adapter = publicAdapter as NativePruneAdapter + adapter.setId('prune-cutoffs') + try { + expect(await adapter.start()).toBe(true) + const oldA = await archived(adapter, 'old-a') + const oldB = await archived(adapter, 'old-b') + const boundary = await archived(adapter, 'boundary') + const fresh = await archived(adapter, 'fresh') + // Native fixture dates, not a clock change or public-only precision claim. + await adapter.db.execute( + sql`UPDATE duron.jobs_archive SET finished_at = '1999-01-01' WHERE id IN (${oldA}, ${oldB})`, + ) + await adapter.db.execute( + sql`UPDATE duron.jobs_archive SET finished_at = '2020-01-01' WHERE id = ${boundary}`, + ) + await adapter.db.execute( + sql`UPDATE duron.jobs_archive SET finished_at = '2099-01-01' WHERE id = ${fresh}`, + ) + expect( + await adapter.pruneArchive({ + olderThan: new Date('2020-01-01'), + batchSize: 1, + maxBatches: 1, + }), + ).toBe(1) + expect((await adapter.getArchiveStats()).jobsCount).toBe(3) + expect( + await adapter.pruneArchive({ + olderThan: new Date('2020-01-01'), + batchSize: 1, + maxBatches: 10, + }), + ).toBe(1) + expect((await adapter.getArchiveStats()).jobsCount).toBe(2) + expect(await adapter.getJobById(oldA)).toBeNull() + expect(await adapter.getJobById(oldB)).toBeNull() + expect(await adapter.getJobById(boundary)).not.toBeNull() + expect(await adapter.getJobById(fresh)).not.toBeNull() + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeNull() + await expect(adapter.pruneArchive({ olderThan: 'not-a-duration' })).rejects.toThrow() + // Existing numeric options are not positive-only: preserve their no-work + // behavior rather than inventing stricter validation in this coordination fix. + expect(await adapter.pruneArchive({ olderThan: '1d', batchSize: 0 })).toBe(0) + expect(await adapter.pruneArchive({ olderThan: '1d', maxBatches: -1 })).toBe(0) + await expect(adapter.pruneArchive({ olderThan: '1d', batchSize: NaN })).rejects.toThrow() + expect((await adapter.getArchiveStats()).jobsCount).toBe(2) + } finally { + await adapter.stop() + await deleteDb() + } + }, 20_000) + + it(`${factory.name} a real later-batch failure preserves the earlier committed DELETE`, async () => { + const { adapter: publicAdapter, deleteDb } = await factory.create() + const adapter = publicAdapter as NativePruneAdapter + adapter.setId('prune-partial-commit') + try { + expect(await adapter.start()).toBe(true) + const oldA = await archived(adapter, 'partial-a') + const oldB = await archived(adapter, 'partial-b') + const fresh = await archived(adapter, 'partial-fresh') + await adapter.db.execute( + sql`UPDATE duron.jobs_archive SET finished_at = '1999-01-01' WHERE id IN (${oldA}, ${oldB})`, + ) + await adapter.db.execute( + sql`UPDATE duron.jobs_archive SET finished_at = '2099-01-01' WHERE id = ${fresh}`, + ) + await adapter.db.execute(sql`CREATE TABLE duron.prune_test_counter (n integer NOT NULL)`) + await adapter.db.execute(sql`INSERT INTO duron.prune_test_counter VALUES (0)`) + await adapter.db.execute(sql` + CREATE FUNCTION duron.fail_second_prune() RETURNS trigger LANGUAGE plpgsql AS $$ + DECLARE attempted integer; + BEGIN + UPDATE duron.prune_test_counter SET n = n + 1 RETURNING n INTO attempted; + IF attempted > 1 THEN + RAISE EXCEPTION 'injected second prune batch' USING ERRCODE = 'P0001'; + END IF; + RETURN OLD; + END $$ + `) + await adapter.db.execute(sql` + CREATE TRIGGER fail_second_prune BEFORE DELETE ON duron.jobs_archive + FOR EACH ROW EXECUTE FUNCTION duron.fail_second_prune() + `) + const failure = await adapter + .pruneArchive({ olderThan: new Date('2020-01-01'), batchSize: 1, maxBatches: 10 }) + .catch((error: unknown) => error) + expect(failure).toBeInstanceOf(Error) + expect((failure as Error).cause).toMatchObject({ + code: 'P0001', + message: 'injected second prune batch', + }) + expect((await adapter.getArchiveStats()).jobsCount).toBe(2) + expect(await adapter.getJobById(fresh)).not.toBeNull() + await adapter.db.execute(sql`DROP TRIGGER fail_second_prune ON duron.jobs_archive`) + // This is a new explicit public call, not an automatic replay of failure. + expect( + await adapter.pruneArchive({ + olderThan: new Date('2020-01-01'), + batchSize: 1, + maxBatches: 10, + }), + ).toBe(1) + expect((await adapter.getArchiveStats()).jobsCount).toBe(1) + expect(await adapter.getJobById(fresh)).not.toBeNull() + } finally { + await adapter.stop() + await deleteDb() + } + }, 20_000) +} diff --git a/packages/duron/test/prune-bootstrap.test.ts b/packages/duron/test/prune-bootstrap.test.ts new file mode 100644 index 0000000..1f9eea1 --- /dev/null +++ b/packages/duron/test/prune-bootstrap.test.ts @@ -0,0 +1,344 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' +import postgres, { type Sql } from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' +import { PruneRelay } from './prune-relay.js' + +async function eventually(check: () => Promise, timeout = 7_000): Promise { + const deadline = performance.now() + timeout + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +if (process.env['POSTGRES_TEST'] === 'true') { + for (const mode of [ + 'stop within drain', + 'stop beyond drain', + 'permitted retry', + 'stop during retry', + ] as const) { + it(`bootstrap ${mode} retains one ready reservation or stops without new work`, async () => { + const late = mode === 'stop beyond drain' + const retry = mode === 'permitted retry' || mode === 'stop during retry' + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const relay = new PruneRelay() + relay.hold = (tag, connection) => tag === 'Z' && connection.ready === 1 + let reserves = 0 + let returns = 0 + let reservedPid = 0 + let hooks = 0 + let ends = 0 + let installed = false + class PendingBootstrap extends PostgresAdapter { + protected override _acquirePruneLock(): Promise { + const work = super._acquirePruneLock() + if (!installed) { + installed = true + const { client } = (this as unknown as { pruneLock: { client: Sql } }).pruneLock + client.options.host[0] = '127.0.0.1' + client.options.port[0] = relay.port + const reserve = client.reserve.bind(client) + client.reserve = async () => { + reserves++ + const session = await reserve() + reservedPid = (await session<{ pid: number }[]>`SELECT pg_backend_pid() AS pid`)[0]! + .pid + const release = session.release.bind(session) + session.release = () => { + returns++ + release() + } + return session + } + const end = client.end.bind(client) + client.end = async (options) => { + ends++ + await end(options) + } + } + return work + } + protected override async _pruneArchive(): Promise { + hooks++ + return 0 + } + } + const adapter = new PendingBootstrap({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId(`pending-bootstrap-${mode}`) + const observer = postgres(CONNECTION_URL, { max: 1 }) + let stopped: Promise> | undefined + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(relay.held.length).toBeGreaterThan(0)) + if (retry) { + const first = relay.connections[0]! + relay.cut(first) + await eventually(async () => { + expect(relay.connections).toHaveLength(2) + expect(relay.connections[1]!.ready).toBe(1) + expect(relay.connections[1]!.pid).toBeGreaterThan(0) + }) + expect(relay.connections[1]!.pid).not.toBe(first.pid) + expect(reserves).toBe(0) + expect(hooks).toBe(0) + } + if (mode === 'permitted retry') { + relay.flush() + await eventually(async () => expect(hooks).toBeGreaterThan(0)) + expect(reservedPid).toBe(relay.connections[1]!.pid!) + } + stopped = Promise.allSettled([adapter.stop()]).then((results) => results[0]!) + if (late) await eventually(async () => expect(ends).toBe(1), 12_000) + relay.flush() + const outcome = await stopped + expect(outcome.status).toBe(late ? 'rejected' : 'fulfilled') + if (outcome.status === 'rejected') { + const errors: Error[] = + outcome.reason instanceof AggregateError ? outcome.reason.errors : [outcome.reason] + expect( + errors.some((error) => + error.message.includes('admitted-work drain exceeded five seconds'), + ), + ).toBe(true) + } + expect(reserves).toBe(mode === 'permitted retry' ? 1 : 0) + expect(returns).toBe(mode === 'permitted retry' ? 1 : 0) + if (mode !== 'permitted retry') expect(hooks).toBe(0) + expect(ends).toBe(1) + await eventually(async () => { + expect( + await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + }) + expect(relay.connections).toHaveLength(retry ? 2 : 1) + expect(relay.errors).toEqual([]) + if (late) await expect(adapter.stop()).rejects.toThrow('Liveness release withheld') + else expect(await adapter.stop()).toBe(true) + } finally { + relay.flush() + await stopped + await adapter.stop().catch(() => undefined) + await relay.close() + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 30_000) + } + for (const failure of [ + 'authentication', + 'initial readiness', + 'bootstrap reply', + 'close acknowledgment', + ] as const) { + it(`bootstrap ${failure} failure leaves no later lock backend before relay teardown`, async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const relay = new PruneRelay() + relay.hold = (tag, connection) => + (failure === 'initial readiness' || failure === 'close acknowledgment') && + tag === 'Z' && + connection.ready === 1 + const deliverClose = Promise.withResolvers() + let closeNotice = false + let stopping: Promise | undefined + const application = `bootstrap-rejection-${crypto.randomUUID()}` + let reserves = 0 + let acquisitions = 0 + let closes = 0 + let closeSettled = false + let hooks = 0 + let instrumented = false + const reports: unknown[] = [] + class BootstrapProbe extends PostgresAdapter { + protected override _acquirePruneLock(): Promise { + const work = super._acquirePruneLock() + if (!instrumented) { + instrumented = true + const { client } = (this as unknown as { pruneLock: { client: Sql } }).pruneLock + // Diagnostic endpoint only. The stock driver's existing connection + // option arrays are shared with its unopened connection; no queue patch, + // replacement client, custom socket or production transport is used. + client.options.host[0] = '127.0.0.1' + client.options.port[0] = relay.port + if (failure === 'close acknowledgment') { + const notify = client.options.onclose + // postgres.js driver option, not an EventTarget event property. + Object.assign(client.options, { + onclose: (id: number) => { + closeNotice = true + void deliverClose.promise.then(() => notify(id)) + }, + }) + } + if (failure === 'authentication') + Object.assign(client.options, { pass: 'deliberately-invalid-prune-test-password' }) + client.options.debug = (_, query) => { + if ( + failure === 'bootstrap reply' && + query.includes('SELECT pg_backend_pid() AS pid') + ) { + relay.hold = () => true + } + if (query.includes('pg_try_advisory_lock')) acquisitions++ + } + const reserve = client.reserve.bind(client) + client.reserve = async () => { + reserves++ + return reserve() + } + const end = client.end.bind(client) + client.end = async (options) => { + closes++ + await end(options) + closeSettled = true + } + } + return work + } + protected override async _pruneArchive(): Promise { + hooks++ + return 0 + } + } + const url = new URL(CONNECTION_URL) + const adapter = new BootstrapProbe({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + connection: { application_name: application }, + }, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId(application) + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + if (failure !== 'authentication') { + await eventually(async () => { + expect(relay.connections).toHaveLength(1) + expect(relay.connections[0]!.pid).toBeGreaterThan(0) + expect(relay.held.some(({ frame }) => frame[0] === 90)).toBe(true) + }) + const pid = relay.connections[0]!.pid! + if (failure === 'initial readiness' || failure === 'close acknowledgment') { + const killed = await observer<{ terminated: boolean }[]>` + SELECT pg_terminate_backend(pid) AS terminated FROM pg_stat_activity + WHERE datname = current_database() AND application_name = ${application} AND pid = ${pid} + ` + expect(killed).toHaveLength(1) + expect(killed[0]?.terminated).toBe(true) + } else { + // The server executed the identity query, but its real reply is held. + expect( + await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND application_name = ${application} + AND pid = ${pid} AND state = 'idle' AND query LIKE '%pg_backend_pid%' + `, + ).toHaveLength(1) + relay.cut(relay.connections[0]!) + } + } + if (failure === 'close acknowledgment') { + await eventually(async () => { + expect(closeNotice).toBe(true) + expect(closeSettled).toBe(true) + }) + let stopSettled = false + stopping = adapter.stop() + void stopping.then( + () => { + stopSettled = true + }, + () => { + stopSettled = true + }, + ) + await Bun.sleep(100) + expect(stopSettled).toBe(false) + deliverClose.resolve() + expect(await stopping).toBe(true) + } + await eventually(async () => expect(reports.length).toBeGreaterThan(0)) + expect(reports).toHaveLength(1) + const errors = reports[0] instanceof AggregateError ? reports[0].errors : reports + const expected = + failure === 'bootstrap reply' + ? [ + { code: 'CONNECTION_CLOSED' }, + { message: 'Incomplete shutdown: owned close exceeded five seconds' }, + ] + : [{ code: failure === 'authentication' ? '28P01' : '57P01' }] + // Real EOF during the identity reply reaches the driver's five-second end + // timeout. Its earlier observer expiry is a separate retained close error, + // not a successful close; require actual late settlement and native absence. + expect(errors).toMatchObject(expected) + expect(reserves).toBe(0) + expect(acquisitions).toBe(0) + expect(hooks).toBe(0) + expect(closes).toBe(1) + await Bun.sleep(250) + expect(relay.connections).toHaveLength(1) + expect(relay.sockets).toBe(0) + expect( + await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(failure === 'close acknowledgment' ? 0 : 2) + if (failure !== 'close acknowledgment') + expect((await adapter.getArchiveStats()).jobsCount).toBe(0) + await eventually(async () => expect(closeSettled).toBe(true)) + expect(await adapter.stop()).toBe(true) + await eventually(async () => { + expect( + await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + }) + expect(relay.errors).toEqual([]) + // All server absence/no-later-establishment assertions precede relay close. + } finally { + deliverClose.resolve() + relay.flush() + await stopping?.catch(() => undefined) + await adapter.stop().catch(() => undefined) + await relay.close() + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + } +} diff --git a/packages/duron/test/prune-cadence.test.ts b/packages/duron/test/prune-cadence.test.ts new file mode 100644 index 0000000..8cf78ff --- /dev/null +++ b/packages/duron/test/prune-cadence.test.ts @@ -0,0 +1,202 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' + +import type { PruneArchiveOptions } from '../src/adapters/adapter.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +async function eventually(check: () => Promise): Promise { + const deadline = performance.now() + 5_000 + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +type PruneSeam = Adapter & { _pruneArchive: (options: PruneArchiveOptions) => Promise } + +async function archive(adapter: Adapter, key: string): Promise { + const id = await adapter.createJob({ + queue: 'cadence', + groupKey: key, + input: {}, + timeoutMs: 60_000, + checksum: key, + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(id).toBeDefined() + expect(await adapter.cancelJob({ jobId: id! })).toBe(true) +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + // Serial because this narrowly captures the actual timer callback while public + // startup installs it. No fake clock and no scheduler replacement is used. + it.serial( + `${factory.name} skips busy ticks without catch-up and retries ordinary failure only on a fresh tick`, + async () => { + const delay = 1_234_567 + const { adapter, deleteDb } = await factory.create({ + pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: delay }, + }) + adapter.setId('controlled-cadence') + const seam = adapter as PruneSeam + const prune = seam._pruneArchive.bind(adapter) + const held = Promise.withResolvers() + const failure = new Error('injected ordinary prune hook failure') + let calls = 0 + seam._pruneArchive = async (options) => { + calls++ + if (calls === 1) { + await held.promise + throw failure + } + return prune(options) + } + const errors: unknown[] = [] + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + errors.push(error) + } + adapter.setLogger(logger) + let tick: (() => void) | undefined + const schedule = globalThis.setInterval + try { + globalThis.setInterval = (( + callback: (...args: unknown[]) => void, + ms?: number, + ...args: unknown[] + ) => { + if (ms === delay) tick = () => callback(...args) + return schedule(callback, ms, ...args) + }) as typeof setInterval + try { + expect(await adapter.start()).toBe(true) + } finally { + globalThis.setInterval = schedule + } + expect(tick).toBeDefined() + await eventually(async () => expect(calls).toBe(1)) + await archive(adapter, 'retained-on-failure') + for (let index = 0; index < 10; index++) await tick!() + expect(calls).toBe(1) + held.resolve() + await eventually(async () => expect(errors).toEqual([failure])) + await Bun.sleep(20) + expect(calls).toBe(1) + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeNull() + expect((await adapter.getArchiveStats()).jobsCount).toBe(1) + await tick!() + expect(calls).toBe(2) + expect(errors).toEqual([failure]) + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date) + expect((await adapter.getArchiveStats()).jobsCount).toBe(0) + expect(await adapter.stop()).toBe(true) + await tick!() + expect(calls).toBe(2) + } finally { + globalThis.setInterval = schedule + held.resolve() + await adapter.stop() + await deleteDb() + } + }, + 15_000, + ) + + it(`${factory.name} concurrent direct calls enter real override dispatch independently`, async () => { + const { adapter, deleteDb } = await factory.create() + adapter.setId('direct-concurrency') + const seam = adapter as PruneSeam + const prune = seam._pruneArchive.bind(adapter) + const held = Promise.withResolvers() + let calls = 0 + seam._pruneArchive = async (options) => { + calls++ + await held.promise + return prune(options) + } + let work: Promise[] = [] + try { + expect(await adapter.start()).toBe(true) + for (let index = 0; index < 3; index++) await archive(adapter, String(index)) + const options = { olderThan: new Date('2099-01-01'), batchSize: 1, maxBatches: 1 } + work = [adapter.pruneArchive(options), adapter.pruneArchive(options)] + await eventually(async () => expect(calls).toBe(2)) + held.resolve() + const [first, second] = await Promise.all(work) + const stats = await adapter.getArchiveStats() + // Concurrent DELETE snapshots may choose the same candidate. No new + // direct-call serialization/isolation guarantee is introduced here. + expect([ + [1, 1, 1], + [1, 0, 2], + [0, 1, 2], + ]).toContainEqual([first!, second!, stats.jobsCount]) + expect(stats.lastPrunedAt).toBeNull() + } finally { + held.resolve() + await Promise.allSettled(work) + await adapter.stop() + await deleteDb() + } + }, 15_000) + + it(`${factory.name} preserves prune, unlock and isolated-close errors in that order`, async () => { + const { adapter, deleteDb } = await factory.create({ + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('triple-prune-errors') + const seam = adapter as PruneSeam & { + _releasePruneLock: () => Promise + _closePruneLock: () => Promise + } + const release = seam._releasePruneLock.bind(adapter) + const pruneError = new Error('injected prune failure') + const unlockError = new Error('injected after-native-unlock failure') + const closeError = new Error('injected before-isolated-close failure') + let calls = 0 + seam._pruneArchive = async () => { + calls++ + throw pruneError + } + seam._releasePruneLock = async () => { + await release() + throw unlockError + } + seam._closePruneLock = async () => { + throw closeError + } + const reports: unknown[] = [] + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(reports).toHaveLength(1)) + expect(reports[0]).toBeInstanceOf(AggregateError) + expect((reports[0] as AggregateError).errors).toEqual([pruneError, unlockError, closeError]) + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeNull() + await Bun.sleep(100) + expect(calls).toBe(1) + expect(reports).toHaveLength(1) + // The injected early-close fault does not remove the owned normal-stop + // obligation. Its confirmed native unlock permits ordinary safe cleanup. + expect(await adapter.stop()).toBe(true) + } finally { + await adapter.stop() + await deleteDb() + } + }, 15_000) +} diff --git a/packages/duron/test/prune-loss.test.ts b/packages/duron/test/prune-loss.test.ts new file mode 100644 index 0000000..f68a294 --- /dev/null +++ b/packages/duron/test/prune-loss.test.ts @@ -0,0 +1,168 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' +import postgres from 'postgres' + +import type { PruneArchiveOptions } from '../src/adapters/adapter.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +async function eventually(check: () => Promise, timeout = 7_000): Promise { + const deadline = performance.now() + timeout + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +if (process.env['POSTGRES_TEST'] === 'true') { + it('lock loss permits another owner while issued DELETE commits, but blocks its next batch', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const beginPrune = Promise.withResolvers() + const unlockTable = Promise.withResolvers() + const tableLocked = Promise.withResolvers() + let observedLoss = false + let hookSettled = false + let hookEntered = false + const reports: unknown[] = [] + class BlockedDeletePrune extends PostgresAdapter { + protected override _retirePruning(error: unknown): void { + observedLoss = true + super._retirePruning(error) + } + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + hookEntered = true + await beginPrune.promise + try { + return await super._pruneArchive(options) + } finally { + hookSettled = true + } + } + } + const application = `issued-prune-${crypto.randomUUID()}` + const url = new URL(CONNECTION_URL) + const adapter = new BlockedDeletePrune({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + connection: { application_name: application }, + }, + pruneArchive: { + olderThan: new Date('2099-01-01'), + batchSize: 1, + maxBatches: 10, + intervalMs: 20, + }, + }) + adapter.setId(application) + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + const blocker = postgres(CONNECTION_URL, { max: 1 }) + const observer = postgres(CONNECTION_URL, { max: 1 }) + let blocking: Promise | undefined + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(hookEntered).toBe(true)) + for (let i = 0; i < 3; i++) { + const jobId = await adapter.createJob({ + queue: 'issued-delete', + groupKey: String(i), + input: { i }, + timeoutMs: 60_000, + checksum: String(i), + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(jobId).toBeDefined() + expect(await adapter.cancelJob({ jobId: jobId! })).toBe(true) + } + expect((await adapter.getArchiveStats()).jobsCount).toBe(3) + blocking = blocker.begin(async (transaction) => { + await transaction`LOCK TABLE duron.jobs_archive IN ACCESS EXCLUSIVE MODE` + tableLocked.resolve() + await unlockTable.promise + }) + await tableLocked.promise + beginPrune.resolve() + let queryPid = 0 + await eventually(async () => { + const blocked = await observer<{ pid: number }[]>` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() + AND application_name = ${application} AND wait_event_type = 'Lock' + AND query LIKE '%DELETE FROM%jobs_archive%' + ` + expect(blocked).toHaveLength(1) + queryPid = blocked[0]!.pid + }) + const owners = await observer<{ pid: number }[]>` + SELECT a.pid FROM pg_stat_activity a JOIN pg_locks l ON a.pid = l.pid + WHERE a.datname = current_database() AND a.application_name = ${application} + AND l.locktype = 'advisory' AND l.classid = 0 AND l.objid = 42 + AND l.objsubid = 1 AND l.granted + ` + expect(owners).toHaveLength(1) + expect(owners[0]!.pid).not.toBe(queryPid) + expect( + await observer` + SELECT pg_terminate_backend(pid) FROM pg_stat_activity + WHERE datname = current_database() AND application_name = ${application} + AND pid = ${owners[0]!.pid} + `, + ).toHaveLength(1) + await eventually(async () => expect(observedLoss).toBe(true)) + expect( + (await observer<{ acquired: boolean }[]>`SELECT pg_try_advisory_lock(42) AS acquired`)[0] + ?.acquired, + ).toBe(true) + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE pid = ${queryPid} AND wait_event_type = 'Lock' + `, + ).toHaveLength(1) + unlockTable.resolve() + await blocking + await eventually(async () => expect(hookSettled).toBe(true)) + await eventually(async () => expect(reports.length).toBeGreaterThan(0)) + // No fencing or cancellation claim: one already-issued batch committed. + // The remaining two are retained because the next library SQL is gated. + expect((await adapter.getArchiveStats()).jobsCount).toBe(2) + expect(await adapter.pruneArchive({ olderThan: new Date('2099-01-01') })).toBe(2) + expect((await adapter.getArchiveStats()).jobsCount).toBe(0) + expect(await adapter.stop()).toBe(true) + await blocker.end({ timeout: 5 }) + await eventually(async () => { + expect( + await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + }) + } finally { + beginPrune.resolve() + unlockTable.resolve() + await blocking?.catch(() => undefined) + await adapter.stop().catch(() => undefined) + await blocker.end({ timeout: 5 }) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 25_000) +} diff --git a/packages/duron/test/prune-ownership.test.ts b/packages/duron/test/prune-ownership.test.ts new file mode 100644 index 0000000..ecb34f0 --- /dev/null +++ b/packages/duron/test/prune-ownership.test.ts @@ -0,0 +1,787 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' +import postgres, { type Sql } from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +async function eventually(check: () => Promise, timeout = 7_000): Promise { + const deadline = performance.now() + timeout + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +// Approved labeled native-driver fault seam. All tests still call public +// start/stop and preserve real query/listener/lock clients and physical observers. +class InstrumentedPrune extends PostgresAdapter { + instrument: (client: Sql) => void = () => undefined + #installed = false + protected override _acquirePruneLock(): Promise { + const work = super._acquirePruneLock() + if (!this.#installed) { + this.#installed = true + const resource = (this as unknown as { pruneLock: { client: Sql } }).pruneLock + this.instrument(resource.client) + } + return work + } +} + +if (process.env['POSTGRES_TEST'] === 'true') { + it('retains an early close rejection when stop precedes held-hook settlement', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const finishHook = Promise.withResolvers() + const closeFailure = new Error('injected end rejection after native closure before stop') + const reports: unknown[] = [] + let entered = false + let rejectedReply = false + let ends = 0 + class HeldHook extends InstrumentedPrune { + protected override async _pruneArchive(): Promise { + entered = true + await finishHook.promise + return 0 + } + } + const adapter = new HeldHook({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('close-error-across-stop') + adapter.instrument = (client) => { + const end = client.end.bind(client) + client.end = async (options) => { + ends++ + await end(options) + rejectedReply = true + throw closeFailure + } + } + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(entered).toBe(true)) + const owners = await observer<{ pid: number }[]>` + SELECT a.pid FROM pg_stat_activity a JOIN pg_locks l ON a.pid = l.pid + WHERE a.datname = current_database() AND l.locktype = 'advisory' + AND l.classid = 0 AND l.objid = 42 AND l.objsubid = 1 AND l.granted + ` + expect(owners).toHaveLength(1) + expect( + await observer` + SELECT pg_terminate_backend(pid) FROM pg_stat_activity + WHERE datname = current_database() AND pid = ${owners[0]!.pid} + `, + ).toHaveLength(1) + await eventually(async () => expect(rejectedReply).toBe(true)) + expect( + await observer`SELECT pid FROM pg_stat_activity WHERE pid = ${owners[0]!.pid}`, + ).toHaveLength(0) + expect(reports).toHaveLength(0) + const stopping = adapter.stop() + finishHook.resolve() + expect(await stopping).toBe(true) + await eventually(async () => expect(reports).toHaveLength(1)) + expect(reports[0]).toBeInstanceOf(AggregateError) + const errors = (reports[0] as AggregateError).errors + expect(errors).toHaveLength(2) + expect(errors[0].message).toBe('Scheduled prune coordination session was lost') + expect(errors[1]).toBe(closeFailure) + expect(ends).toBe(1) + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + } finally { + finishHook.resolve() + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + it('failed public startup closes its allocated lock backend along with query and listener resources', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const allocated = Promise.withResolvers() + const failure = new Error('injected startup failure after native reservation') + let pid = 0 + let ends = 0 + class FailedStartup extends InstrumentedPrune { + protected override async _start(): Promise { + await super._start() + await allocated.promise + throw failure + } + } + const adapter = new FailedStartup({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('failed-start-owned-lock') + adapter.instrument = (client) => { + const reserve = client.reserve.bind(client) + client.reserve = async () => { + const session = await reserve() + pid = (await session<{ pid: number }[]>`SELECT pg_backend_pid() AS pid`)[0]!.pid + allocated.resolve() + return session + } + const end = client.end.bind(client) + client.end = async (options) => { + ends++ + await end(options) + } + } + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + await expect(adapter.start()).rejects.toBe(failure) + expect(pid).toBeGreaterThan(0) + expect(ends).toBe(1) + await eventually(async () => { + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + }) + expect(await adapter.stop()).toBe(true) + expect(await adapter.start()).toBe(false) + expect(ends).toBe(1) + } finally { + allocated.resolve() + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + it('retains one backend and reservation across false and successful passes without stacking', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const permitNext = Promise.withResolvers() + const acquisitions: { pid: number; acquired: boolean }[] = [] + const unlocks: { pid: number; released: boolean }[] = [] + let identityPid = 0 + let reserves = 0 + let returns = 0 + let hooks = 0 + let pause = false + class RepeatedPrune extends InstrumentedPrune { + protected override async _acquirePruneLock(): Promise { + if (pause) await permitNext.promise + return super._acquirePruneLock() + } + protected override async _pruneArchive( + options: import('../src/adapters/adapter.js').PruneArchiveOptions, + ): Promise { + hooks++ + return super._pruneArchive(options) + } + protected override async _releasePruneLock(): Promise { + await super._releasePruneLock() + if (unlocks.length === 3) pause = true + } + } + const adapter = new RepeatedPrune({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 30 }, + }) + adapter.setId('retained-session') + adapter.instrument = (client) => { + const reserve = client.reserve.bind(client) + client.reserve = async () => { + reserves++ + const session = await reserve() + const release = session.release.bind(session) + session.release = () => { + returns++ + release() + } + return new Proxy(session, { + apply(target, receiver, args) { + return Reflect.apply(target, receiver, args).then( + (rows: { pid: number; acquired?: boolean; released?: boolean }[]) => { + const row = rows[0]! + if (typeof row.acquired === 'boolean') + acquisitions.push({ pid: row.pid, acquired: row.acquired }) + else if (typeof row.released === 'boolean') + unlocks.push({ pid: row.pid, released: row.released }) + else identityPid = row.pid + return rows + }, + ) + }, + }) + } + } + const observer = postgres(CONNECTION_URL, { max: 1, onnotice: () => undefined }) + try { + expect( + (await observer<{ acquired: boolean }[]>`SELECT pg_try_advisory_lock(42) AS acquired`)[0] + ?.acquired, + ).toBe(true) + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(acquisitions.length).toBeGreaterThanOrEqual(3)) + expect(acquisitions.every((row) => row.acquired === false)).toBe(true) + expect(unlocks).toHaveLength(0) + expect(hooks).toBe(0) + expect(reserves).toBe(1) + expect(returns).toBe(0) + expect( + (await observer<{ released: boolean }[]>`SELECT pg_advisory_unlock(42) AS released`)[0] + ?.released, + ).toBe(true) + await eventually(async () => expect(pause).toBe(true)) + expect(hooks).toBe(3) + expect(unlocks).toHaveLength(3) + expect(unlocks.every((row) => row.released === true && row.pid === identityPid)).toBe(true) + expect(acquisitions.every((row) => row.pid === identityPid)).toBe(true) + expect(reserves).toBe(1) + expect(returns).toBe(0) + // Pause before another acquisition, not after it: independent acquisition + // here excludes residual native reentrant stacks on the still-live backend. + expect( + (await observer<{ acquired: boolean }[]>`SELECT pg_try_advisory_lock(42) AS acquired`)[0] + ?.acquired, + ).toBe(true) + expect( + (await observer<{ released: boolean }[]>`SELECT pg_advisory_unlock(42) AS released`)[0] + ?.released, + ).toBe(true) + const stopping = adapter.stop() + permitNext.resolve() + expect(await stopping).toBe(true) + expect(returns).toBe(1) + expect(reserves).toBe(1) + expect(await adapter.stop()).toBe(true) + expect(returns).toBe(1) + } finally { + permitNext.resolve() + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + + it('loss during a stop-held ready reservation never returns it and reports cleanup independently', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const continueReserve = Promise.withResolvers() + let pid = 0 + let returns = 0 + let hooks = 0 + const application = `reserve-loss-${crypto.randomUUID()}` + class ReservedLoss extends InstrumentedPrune { + lost = false + protected override _retirePruning(error: unknown): void { + this.lost = true + super._retirePruning(error) + } + protected override async _pruneArchive(): Promise { + hooks++ + return 0 + } + } + const url = new URL(CONNECTION_URL) + const adapter = new ReservedLoss({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + connection: { application_name: application }, + }, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId(application) + adapter.instrument = (client) => { + const reserve = client.reserve.bind(client) + client.reserve = async () => { + const session = await reserve() + const release = session.release.bind(session) + session.release = () => { + returns++ + release() + } + pid = (await session<{ pid: number }[]>`SELECT pg_backend_pid() AS pid`)[0]!.pid + await continueReserve.promise + return session + } + } + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(pid).toBeGreaterThan(0)) + const stopping = adapter.stop() + expect( + await observer` + SELECT pg_terminate_backend(pid) FROM pg_stat_activity + WHERE datname = current_database() AND application_name = ${application} AND pid = ${pid} + `, + ).toHaveLength(1) + await eventually(async () => expect(adapter.lost).toBe(true)) + continueReserve.resolve() + expect(await stopping).toBe(true) + expect(returns).toBe(0) + expect(hooks).toBe(0) + expect( + await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + expect(await adapter.stop()).toBe(true) + expect(returns).toBe(0) + } finally { + continueReserve.resolve() + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + + it('uncertain reserved identity never returns the native reservation as safe', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const reports: unknown[] = [] + let reserveCalls = 0 + let returnCalls = 0 + let identityPid = 0 + let hookCalls = 0 + class IdentityFault extends InstrumentedPrune { + protected override async _pruneArchive(): Promise { + hookCalls++ + return 0 + } + } + const adapter = new IdentityFault({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('uncertain-reserved-identity') + adapter.instrument = (client) => { + const reserve = client.reserve.bind(client) + client.reserve = async () => { + reserveCalls++ + const session = await reserve() + const release = session.release.bind(session) + session.release = () => { + returnCalls++ + release() + } + return new Proxy(session, { + apply(target, receiver, args) { + // The real reserved identity query executes. Only its observed PID is + // altered: this is malformed/changed-identity injection, not a claim + // that the native driver actually replaced a backend here. + return Reflect.apply(target, receiver, args).then((rows: { pid: number }[]) => { + identityPid = rows[0]!.pid + return [{ ...rows[0], pid: identityPid + 1 }] + }) + }, + }) + } + } + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(reports.length).toBeGreaterThan(0)) + expect(identityPid).toBeGreaterThan(0) + expect(hookCalls).toBe(0) + expect(reserveCalls).toBe(1) + expect(returnCalls).toBe(0) + await eventually(async () => { + const sessions = await observer`SELECT pid FROM pg_stat_activity WHERE pid = ${identityPid}` + expect(sessions).toHaveLength(0) + }) + expect((await adapter.getArchiveStats()).jobsCount).toBe(0) + expect(await adapter.stop()).toBe(true) + } finally { + await adapter.stop().catch(() => undefined) + await eventually(async () => { + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(0) + }) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + + it('stop joins the pending fault close without resetting its deadline or skipping other resources', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const allowEnd = Promise.withResolvers() + let endStarted = 0 + let endCalls = 0 + let returnCalls = 0 + const reports: unknown[] = [] + class FaultCloseHold extends InstrumentedPrune { + protected override async _releasePruneLock(): Promise { + await super._releasePruneLock() + await super._releasePruneLock() + } + } + const adapter = new FaultCloseHold({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('shared-fault-close-deadline') + adapter.instrument = (client) => { + const reserve = client.reserve.bind(client) + client.reserve = async () => { + const session = await reserve() + const release = session.release.bind(session) + session.release = () => { + returnCalls++ + release() + } + return session + } + const end = client.end.bind(client) + client.end = async (options) => { + endCalls++ + endStarted = performance.now() + await allowEnd.promise + await end(options) + } + } + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(endStarted).toBeGreaterThan(0)) + await adapter.heartbeat() + await Bun.sleep(2_000) + const stopping = adapter.stop() + const duplicate = adapter.stop() + const outcomes = await Promise.allSettled([stopping, duplicate]) + expect(outcomes[0]?.status).toBe('rejected') + expect(outcomes[1]?.status).toBe('rejected') + expect(performance.now() - endStarted).toBeGreaterThanOrEqual(4_900) + expect(performance.now() - endStarted).toBeLessThan(6_500) + expect(endCalls).toBe(1) + expect(returnCalls).toBe(0) + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(1) + expect(await observer`SELECT client_id FROM duron.clients`).toHaveLength(0) + expect(reports).toHaveLength(1) + allowEnd.resolve() + await eventually(async () => { + const remaining = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(remaining).toHaveLength(0) + }) + // Native disappearance can precede local onclose/end acknowledgment. + // Later public stops must join that same operation until it is confirmed. + await eventually(async () => expect(await adapter.stop()).toBe(true)) + expect(endCalls).toBe(1) + expect(returnCalls).toBe(0) + } finally { + allowEnd.resolve() + await adapter.stop().catch(() => undefined) + await eventually(async () => { + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(0) + }) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 25_000) + + it('pending return acknowledgment cannot consume the independent owned-close opportunity', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const acknowledge = Promise.withResolvers() + let returnCalls = 0 + let closeCalls = 0 + const adapter = new InstrumentedPrune({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 60_000 }, + }) + adapter.setId('pending-return-ack') + adapter.instrument = (client) => { + const end = client.end.bind(client) + const reserve = client.reserve.bind(client) + client.end = async (options) => { + closeCalls++ + await end(options) + } + client.reserve = async () => { + const session = await reserve() + const release = session.release.bind(session) + // Native release is synchronous. This deliberately delays only its JS + // acknowledgment; it is not a claimed naturally asynchronous driver API. + session.release = async () => { + returnCalls++ + release() + await acknowledge.promise + } + return session + } + } + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => { + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date) + }) + await expect(adapter.stop()).rejects.toThrow('database cleanup exceeded five seconds') + expect(returnCalls).toBe(1) + expect(closeCalls).toBe(1) + await eventually(async () => { + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(0) + }) + acknowledge.resolve() + expect(await adapter.stop()).toBe(true) + expect(returnCalls).toBe(1) + expect(closeCalls).toBe(1) + } finally { + acknowledge.resolve() + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + + it('physical lock-client closure discharges a rejected end reply without repeating it', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const failure = new Error('injected after-physical-close reply failure') + let closeCalls = 0 + const adapter = new InstrumentedPrune({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 60_000 }, + }) + adapter.setId('after-close-failure') + adapter.instrument = (client) => { + const end = client.end.bind(client) + client.end = async (options) => { + closeCalls++ + await end(options) + throw failure + } + } + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => { + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date) + }) + await expect(adapter.stop()).rejects.toBe(failure) + await eventually(async () => { + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(0) + }) + expect(await adapter.stop()).toBe(true) + expect(closeCalls).toBe(1) + } finally { + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + + it('retries a known before-close fault without repeating an uncertain return or replacing its error', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const returnFailure = new Error('injected before-native-return failure') + const closeFailure = new Error('injected before-close-method failure') + let returns = 0 + let ends = 0 + let closeAttempts = 0 + const adapter = new InstrumentedPrune({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 60_000 }, + }) + adapter.setId('independent-return-close-errors') + adapter.instrument = (client) => { + const reserve = client.reserve.bind(client) + client.reserve = async () => { + const session = await reserve() + session.release = () => { + returns++ + throw returnFailure + } + return session + } + const end = client.end.bind(client) + client.end = async (options) => { + ends++ + await end(options) + } + } + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date), + ) + const resource = (adapter as unknown as { pruneLock: { close: () => Promise } }) + .pruneLock + const close = resource.close.bind(resource) + resource.close = async () => { + if (++closeAttempts === 1) throw closeFailure + await close() + } + const first = await adapter.stop().catch((error: unknown) => error) + expect(first).toBeInstanceOf(AggregateError) + expect((first as AggregateError).errors).toEqual([returnFailure, closeFailure]) + expect(returns).toBe(1) + expect(ends).toBe(0) + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(1) + const second = await adapter.stop().catch((error: unknown) => error) + const errors = second instanceof AggregateError ? second.errors : [second] + expect(errors[0]).toBe(returnFailure) + expect(returns).toBe(1) + expect(ends).toBe(1) + await eventually(async () => { + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + }) + // Server disappearance can precede the driver's local close callback. + // Later public stops join that same operation until its positive evidence arrives. + await eventually(async () => expect(await adapter.stop()).toBe(true)) + expect(closeAttempts).toBe(2) + } finally { + await adapter.stop().catch(() => undefined) + const resource = (adapter as unknown as { pruneLock?: { client: Sql } }).pruneLock + if (resource) await resource.client.end({ timeout: 5 }).catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 25_000) + + it('a return reply failure still closes all native resources and a later stop uses release evidence', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const failure = new Error('injected after-return reply failure') + let returnCalls = 0 + let closeCalls = 0 + const adapter = new InstrumentedPrune({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 60_000 }, + }) + adapter.setId('after-return-failure') + adapter.instrument = (client) => { + const reserve = client.reserve.bind(client) + const end = client.end.bind(client) + client.end = async (options) => { + closeCalls++ + await end(options) + } + client.reserve = async () => { + const session = await reserve() + const release = session.release.bind(session) + session.release = () => { + returnCalls++ + release() + throw failure + } + return session + } + } + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => { + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date) + }) + await expect(adapter.stop()).rejects.toBe(failure) + expect(closeCalls).toBe(1) + await eventually(async () => { + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(0) + }) + expect(await adapter.stop()).toBe(true) + expect(returnCalls).toBe(1) + expect(closeCalls).toBe(1) + } finally { + await adapter.stop().catch(() => undefined) + // Emergency teardown is distinct from public stop evidence above. + const resource = (adapter as unknown as { pruneLock?: { client: Sql } }).pruneLock + if (resource) await resource.client.end({ timeout: 5 }).catch(() => undefined) + await eventually(async () => { + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(0) + }) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) +} diff --git a/packages/duron/test/prune-pglite-faults.test.ts b/packages/duron/test/prune-pglite-faults.test.ts new file mode 100644 index 0000000..1a5a449 --- /dev/null +++ b/packages/duron/test/prune-pglite-faults.test.ts @@ -0,0 +1,107 @@ +import { expect, it } from 'bun:test' + +import { sql } from 'drizzle-orm' +import pino from 'pino' + +import type { PruneArchiveOptions } from '../src/adapters/adapter.js' +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' + +async function eventually(check: () => Promise): Promise { + const deadline = performance.now() + 5_000 + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +for (const fault of ['malformed acquisition', 'malformed unlock', 'native false unlock'] as const) { + it(`PGLite ${fault} retires scheduling without replacing or closing its shared engine`, async () => { + let hooks = 0 + const reports: unknown[] = [] + class FaultyPrune extends PGLiteAdapter { + get engine() { + return this.db.$client + } + protected override _map(result: { rows: Record[] }) { + const rows = super._map(result) + // Labeled malformed-reply control, after the real engine operation. + if (fault === 'malformed acquisition' && 'acquired' in (rows[0] ?? {})) + return [{ acquired: 'unknown' }] + if (fault === 'malformed unlock' && 'released' in (rows[0] ?? {})) + return [{ released: 'unknown' }] + return rows + } + protected override async _releasePruneLock(): Promise { + if (fault === 'native false unlock') { + // Actual interference on this one owned engine makes the library's + // following unlock return PostgreSQL false, not a mocked result. + await this.db.execute(sql`SELECT pg_advisory_unlock(42)`) + } + await super._releasePruneLock() + } + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + hooks++ + return super._pruneArchive(options) + } + } + const adapter = new FaultyPrune({ + connection: ':memory:', + pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: 20 }, + }) + adapter.setId(`pglite-${fault}`) + const engine = adapter.engine + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(reports).toHaveLength(1)) + expect(reports[0]).toBeInstanceOf(Error) + expect(reports[0]).not.toBeInstanceOf(AggregateError) + expect((reports[0] as Error).message).toBe( + fault === 'malformed acquisition' + ? 'Malformed scheduled prune acquisition result' + : 'False or malformed scheduled prune unlock result', + ) + expect(hooks).toBe(fault === 'malformed acquisition' ? 0 : 1) + const stats = await adapter.getArchiveStats() + if (fault === 'malformed acquisition') expect(stats.lastPrunedAt).toBeNull() + else expect(stats.lastPrunedAt).toBeInstanceOf(Date) + const locks = await engine.query<{ count: number }>( + `SELECT count(*)::integer AS count FROM pg_locks WHERE locktype = 'advisory' AND classid = 0 AND objid = 42 AND objsubid = 1`, + ) + expect(locks.rows[0]?.count).toBe(fault === 'malformed acquisition' ? 1 : 0) + expect(adapter.engine).toBe(engine) + expect(engine.closed).toBe(false) + const id = await adapter.createJob({ + queue: 'retired-engine', + groupKey: 'one', + input: {}, + timeoutMs: 60_000, + checksum: 'retired', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(id).toBeDefined() + expect(await adapter.cancelJob({ jobId: id! })).toBe(true) + expect(await adapter.pruneArchive({ olderThan: new Date('2099-01-01') })).toBe(1) + const calls = hooks + await Bun.sleep(100) + expect(hooks).toBe(calls) + expect(reports).toHaveLength(1) + expect(adapter.engine).toBe(engine) + expect(engine.closed).toBe(false) + expect(await adapter.stop()).toBe(true) + expect(engine.closed).toBe(true) + } finally { + await adapter.stop() + } + }, 15_000) +} diff --git a/packages/duron/test/prune-relay.ts b/packages/duron/test/prune-relay.ts new file mode 100644 index 0000000..ae48bca --- /dev/null +++ b/packages/duron/test/prune-relay.ts @@ -0,0 +1,143 @@ +import type { Socket } from 'bun' + +/** Diagnostic TCP relay only. Never used by production or as adapter transport. */ +export type RelayConnection = { + number: number + pid: number | null + ready: number + down: Socket + up?: Socket + queue: Buffer[] + wire: Buffer + dead: boolean +} + +export class PruneRelay { + readonly connections: RelayConnection[] = [] + readonly errors: unknown[] = [] + readonly held: Array<{ connection: RelayConnection; frame: Buffer }> = [] + hold: (tag: string, connection: RelayConnection) => boolean = () => false + readonly #sockets = new Set>() + readonly #connecting = new Set>() + #stopped = false + readonly #listener = Bun.listen({ + hostname: '127.0.0.1', + port: 0, + socket: { + open: (down) => { + this.#sockets.add(down) + const connection: RelayConnection = { + number: this.connections.length + 1, + pid: null, + ready: 0, + down, + queue: [], + wire: Buffer.alloc(0), + dead: false, + } + down.data = connection + this.connections.push(connection) + const work = Bun.connect({ + hostname: '127.0.0.1', + port: 5440, + data: connection, + socket: { + open: (up) => { + this.#sockets.add(up) + connection.up = up + if (this.#stopped || connection.dead) { + up.terminate() + return + } + for (const bytes of connection.queue) up.write(bytes) + connection.queue.length = 0 + }, + data: (_, bytes) => this.#receive(connection, bytes), + close: (up) => { + this.#sockets.delete(up) + down.end() + }, + error: (up, error) => { + this.errors.push(error) + up.terminate() + down.terminate() + }, + connectError: (_, error) => { + this.errors.push(error) + down.terminate() + }, + }, + }).catch((error: unknown) => { + this.errors.push(error) + }) + this.#connecting.add(work) + void work.finally(() => this.#connecting.delete(work)) + }, + data: (down, bytes) => { + const connection = down.data + if (connection.dead) return + if (connection.up) connection.up.write(bytes) + else connection.queue.push(Buffer.from(bytes)) + }, + close: (down) => { + this.#sockets.delete(down) + down.data.dead = true + down.data.up?.end() + }, + error: (down, error) => { + this.errors.push(error) + down.terminate() + down.data.up?.terminate() + }, + }, + }) + + get port(): number { + return this.#listener.port + } + get sockets(): number { + return this.#sockets.size + } + + #receive(connection: RelayConnection, bytes: Uint8Array): void { + if (connection.dead) return + connection.wire = Buffer.concat([connection.wire, bytes]) + while (connection.wire.length >= 5) { + const size = connection.wire.readUInt32BE(1) + 1 + if (connection.wire.length < size) return + const frame = Buffer.from(connection.wire.subarray(0, size)) + connection.wire = connection.wire.subarray(size) + const tag = String.fromCharCode(frame[0]!) + // Record only the PID, never the server's secret cancellation key. + if (tag === 'K') connection.pid = frame.readUInt32BE(5) + if (tag === 'Z') connection.ready++ + if (this.hold(tag, connection)) this.held.push({ connection, frame }) + else connection.down.write(frame) + } + } + + flush(): void { + this.hold = () => false + for (const { connection, frame } of this.held.splice(0)) { + if (!connection.dead) connection.down.write(frame) + } + } + + cut(connection: RelayConnection): void { + connection.dead = true + connection.up?.terminate() + connection.down.terminate() + } + + async close(): Promise { + this.#stopped = true + this.#listener.stop(true) + for (const socket of this.#sockets) socket.terminate() + await Promise.allSettled(this.#connecting) + const deadline = performance.now() + 2_000 + while (this.#sockets.size) { + if (performance.now() >= deadline) throw new Error('Diagnostic prune relay sockets remain') + await Bun.sleep(5) + } + } +} diff --git a/packages/duron/test/prune-replies.test.ts b/packages/duron/test/prune-replies.test.ts new file mode 100644 index 0000000..7e6f641 --- /dev/null +++ b/packages/duron/test/prune-replies.test.ts @@ -0,0 +1,141 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' +import postgres, { type Sql } from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +async function eventually(check: () => Promise): Promise { + const deadline = performance.now() + 8_000 + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +if (process.env['POSTGRES_TEST'] === 'true') { + for (const phase of ['acquired', 'released'] as const) { + it(`malformed ${phase} reply closes the real PostgreSQL session without returning it as reusable`, async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const observer = postgres(CONNECTION_URL, { max: 1 }) + const reports: unknown[] = [] + let installed = false + let returns = 0 + let hooks = 0 + let nativeLocks = -1 + let endSettled = false + class MalformedPrune extends PostgresAdapter { + protected override _acquirePruneLock(): Promise { + const work = super._acquirePruneLock() + if (!installed) { + installed = true + const { client } = (this as unknown as { pruneLock: { client: Sql } }).pruneLock + const reserve = client.reserve.bind(client) + client.reserve = async () => { + const session = await reserve() + const release = session.release.bind(session) + session.release = () => { + returns++ + release() + } + return new Proxy(session, { + apply(target, receiver, args) { + return Reflect.apply(target, receiver, args).then( + async (rows: { pid: number; acquired?: boolean; released?: boolean }[]) => { + if (!(phase in (rows[0] ?? {}))) return rows + const locks = await observer` + SELECT pid FROM pg_locks WHERE pid = ${rows[0]!.pid} AND locktype = 'advisory' + AND classid = 0 AND objid = 42 AND objsubid = 1 AND granted + ` + nativeLocks = locks.length + // Only the observed result is corrupted after native SQL and + // an independent lock observation. Not a driver-origin claim. + return [{ ...rows[0], [phase]: 'unknown' }] + }, + ) + }, + }) + } + const end = client.end.bind(client) + client.end = async (options) => { + await end(options) + endSettled = true + } + } + return work + } + protected override async _pruneArchive(): Promise { + hooks++ + return 0 + } + } + const url = new URL(CONNECTION_URL) + const adapter = new MalformedPrune({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + }, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId(`malformed-${phase}`) + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(reports).toHaveLength(1)) + const errors: Error[] = + reports[0] instanceof AggregateError ? reports[0].errors : (reports as Error[]) + expect(errors[0]?.message).toBe( + phase === 'acquired' + ? 'Malformed scheduled prune acquisition or changed backend' + : 'False or malformed scheduled prune unlock or changed backend', + ) + for (const error of errors.slice(1)) + expect(error.message).toBe('Incomplete shutdown: owned close exceeded five seconds') + expect(nativeLocks).toBe(phase === 'acquired' ? 1 : 0) + await eventually(async () => expect(endSettled).toBe(true)) + expect(hooks).toBe(phase === 'acquired' ? 0 : 1) + expect(returns).toBe(0) + const stats = await adapter.getArchiveStats() + if (phase === 'acquired') expect(stats.lastPrunedAt).toBeNull() + else expect(stats.lastPrunedAt).toBeInstanceOf(Date) + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(2) + await Bun.sleep(100) + expect(reports).toHaveLength(1) + expect(hooks).toBe(phase === 'acquired' ? 0 : 1) + expect(await adapter.stop()).toBe(true) + expect(returns).toBe(0) + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + } finally { + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + } +} diff --git a/packages/duron/test/prune-scheduler.test.ts b/packages/duron/test/prune-scheduler.test.ts new file mode 100644 index 0000000..9bd5030 --- /dev/null +++ b/packages/duron/test/prune-scheduler.test.ts @@ -0,0 +1,361 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' +import postgres, { type Sql } from 'postgres' + +import type { PruneArchiveOptions } from '../src/adapters/adapter.js' +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { pgliteFactory } from './adapters.js' +import { getPostgresConnection } from './docker.js' + +async function eventually(check: () => Promise, timeout = 2_000): Promise { + const deadline = performance.now() + timeout + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +if (process.env['POSTGRES_TEST'] === 'true') { + it('scheduled PostgreSQL ownership leaves the original max-one query pool available', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const release = Promise.withResolvers() + class HeldPostgresPrune extends PostgresAdapter { + queryPid = 0 + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + const rows = await this.db.$client<{ pid: number }[]>`SELECT pg_backend_pid() AS pid` + this.queryPid = rows[0]!.pid + await release.promise + return super._pruneArchive(options) + } + } + const url = new URL(CONNECTION_URL) + const adapter = new HeldPostgresPrune({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + }, + pruneArchive: { olderThan: '1d', intervalMs: 60_000 }, + }) + adapter.setId('isolated-prune-lock') + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(adapter.queryPid).toBeGreaterThan(0)) + // Native ownership evidence supplements the public start/override path. + const locks = await observer<{ pid: number }[]>` + SELECT pid FROM pg_locks + WHERE locktype = 'advisory' AND classid = 0 AND objid = 42 AND objsubid = 1 + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()) + AND granted + ` + expect(locks).toHaveLength(1) + expect(locks[0]!.pid).not.toBe(adapter.queryPid) + expect((await adapter.getArchiveStats()).jobsCount).toBe(0) + release.resolve() + expect(await adapter.stop()).toBe(true) + await eventually(async () => { + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(0) + }) + } finally { + release.resolve() + await adapter.stop() + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + + it('a real false unlock retires and closes only the isolated lock resource', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const reports: unknown[] = [] + class FalseUnlockPrune extends PostgresAdapter { + calls = 0 + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + this.calls++ + return super._pruneArchive(options) + } + protected override async _releasePruneLock(): Promise { + // Labeled owned-session interference: the first unlock really succeeds, + // then the ordinary matching unlock receives a native false response. + await super._releasePruneLock() + await super._releasePruneLock() + } + } + const adapter = new FalseUnlockPrune({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('false-unlock') + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => { + expect(adapter.calls).toBe(1) + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + // Query + dedicated listener still live; isolated lock backend is gone. + expect(sessions).toHaveLength(2) + }, 7_000) + await eventually(async () => expect(reports.length).toBeGreaterThan(0)) + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date) + expect(adapter.calls).toBe(1) + expect(await adapter.stop()).toBe(true) + } finally { + // Preserve the primary assertion on an expected-red run; still observe late + // owned close and clean the independently observed resources. + await adapter.stop().catch(() => undefined) + await eventually(async () => { + const sessions = await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions).toHaveLength(0) + }) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + + it('observed owned lock-session loss blocks a held hook continuation but not direct work', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const release = Promise.withResolvers() + let entered = false + let settled = false + let observedLoss = false + let endSubmitted = false + let instrumented = false + const reports: unknown[] = [] + class LostLockPrune extends PostgresAdapter { + protected override _acquirePruneLock(): Promise { + const work = super._acquirePruneLock() + if (!instrumented) { + instrumented = true + const { client } = (this as unknown as { pruneLock: { client: Sql } }).pruneLock + const end = client.end.bind(client) + client.end = async (options) => { + endSubmitted = true + await end(options) + } + } + return work + } + protected override _retirePruning(error: unknown): void { + observedLoss = true + super._retirePruning(error) + } + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + entered = true + await release.promise + try { + return await super._pruneArchive(options) + } finally { + settled = true + } + } + } + const url = new URL(CONNECTION_URL) + const application = `prune-loss-${crypto.randomUUID()}` + const adapter = new LostLockPrune({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + connection: { application_name: application }, + }, + pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: 20 }, + }) + adapter.setId(application) + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(entered).toBe(true)) + const jobId = await adapter.createJob({ + queue: 'loss-retains-unissued-work', + groupKey: 'loss', + input: {}, + timeoutMs: 60_000, + checksum: 'loss', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(jobId).toBeDefined() + expect(await adapter.cancelJob({ jobId: jobId! })).toBe(true) + // Exactly owned database + application + advisory-owner PID. Never select + // arbitrary sessions for this native fault control. + const owners = await observer<{ pid: number }[]>` + SELECT a.pid FROM pg_stat_activity a JOIN pg_locks l ON l.pid = a.pid + WHERE a.datname = current_database() AND a.application_name = ${application} + AND l.locktype = 'advisory' AND l.classid = 0 AND l.objid = 42 + AND l.objsubid = 1 AND l.granted + ` + expect(owners).toHaveLength(1) + const killed = await observer<{ terminated: boolean }[]>` + SELECT pg_terminate_backend(pid) AS terminated FROM pg_stat_activity + WHERE datname = current_database() AND application_name = ${application} + AND pid = ${owners[0]!.pid} + ` + expect(killed[0]?.terminated).toBe(true) + // Native server absence and the actual driver loss callback are separate. + await eventually(async () => { + const sessions = + await observer`SELECT pid FROM pg_stat_activity WHERE pid = ${owners[0]!.pid}` + expect(sessions).toHaveLength(0) + }) + await eventually(async () => expect(observedLoss).toBe(true)) + // Fault cleanup must start while unrelated override work is still held, + // not wait indefinitely for the normal query-pool hook to return. + await eventually(async () => expect(endSubmitted).toBe(true)) + expect(settled).toBe(false) + release.resolve() + await eventually(async () => expect(settled).toBe(true)) + await eventually(async () => expect(reports.length).toBeGreaterThan(0)) + expect(await adapter.getJobById(jobId!)).not.toBeNull() + expect(await adapter.pruneArchive({ olderThan: new Date('2099-01-01') })).toBe(1) + expect(await adapter.stop()).toBe(true) + } finally { + release.resolve() + await adapter.stop() + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) +} + +it('PGLite scheduled retention removes archived jobs through the public adapter', async () => { + const { adapter, deleteDb } = await pgliteFactory.create({ + pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: 50 }, + }) + adapter.setId('scheduled-retention') + try { + expect(await adapter.start()).toBe(true) + const jobId = await adapter.createJob({ + queue: 'scheduled-retention', + groupKey: 'retention', + input: {}, + timeoutMs: 60_000, + checksum: 'retention', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(jobId).toBeDefined() + expect(await adapter.cancelJob({ jobId: jobId! })).toBe(true) + await eventually(async () => { + expect(await adapter.getJobById(jobId!)).toBeNull() + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date) + }) + expect(await adapter.stop()).toBe(true) + } finally { + await adapter.stop() + await deleteDb() + } +}, 15_000) + +it('keeps prune and unlock errors in order and retires only scheduling', async () => { + const pruneFailure = new Error('injected prune failure') + const unlockFailure = new Error('injected unlock failure') + const reports: unknown[] = [] + class FaultedPrune extends PGLiteAdapter { + calls = 0 + protected override async _pruneArchive(): Promise { + this.calls++ + throw pruneFailure + } + protected override async _releasePruneLock(): Promise { + throw unlockFailure + } + } + const adapter = new FaultedPrune({ + connection: ':memory:', + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('prune-errors') + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(reports.length).toBeGreaterThan(0)) + expect(reports).toHaveLength(1) + expect(reports[0]).toBeInstanceOf(AggregateError) + expect((reports[0] as AggregateError).errors).toEqual([pruneFailure, unlockFailure]) + await Bun.sleep(80) + expect(adapter.calls).toBe(1) + expect((await adapter.getArchiveStats()).jobsCount).toBe(0) + expect(await adapter.stop()).toBe(true) + } finally { + await adapter.stop() + } +}, 15_000) + +it('scheduled ticks skip a busy override without overlapping its real super call', async () => { + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + class HeldPruneAdapter extends PGLiteAdapter { + calls = 0 + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + this.calls++ + entered.resolve() + await release.promise + return super._pruneArchive(options) + } + } + const adapter = new HeldPruneAdapter({ + connection: ':memory:', + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('scheduled-nonoverlap') + try { + expect(await adapter.start()).toBe(true) + await entered.promise + await Bun.sleep(100) + expect(adapter.calls).toBe(1) + const stopping = adapter.stop() + release.resolve() + expect(await stopping).toBe(true) + expect(adapter.calls).toBe(1) + } finally { + release.resolve() + await adapter.stop() + } +}, 15_000) diff --git a/packages/duron/test/prune-scope.test.ts b/packages/duron/test/prune-scope.test.ts new file mode 100644 index 0000000..7c15f99 --- /dev/null +++ b/packages/duron/test/prune-scope.test.ts @@ -0,0 +1,177 @@ +import { expect, it } from 'bun:test' + +import postgres from 'postgres' + +import type { PruneArchiveOptions } from '../src/adapters/adapter.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +async function eventually(check: () => Promise, timeout = 5_000): Promise { + const deadline = performance.now() + timeout + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +class ScopePrune extends PostgresAdapter { + hold = Promise.resolve() + calls = 0 + contentions = 0 + protected override async _acquirePruneLock(): Promise { + const acquired = await super._acquirePruneLock() + if (!acquired) this.contentions++ + return acquired + } + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + this.calls++ + await this.hold + return super._pruneArchive(options) + } +} + +if (process.env['POSTGRES_TEST'] === 'true') { + it('configured schemas contend database-wide, another database proceeds, and direct prune stays outside coordination', async () => { + const first = await getPostgresConnection({ containerName: 'duron-postgres-test', port: 5440 }) + const other = await getPostgresConnection({ containerName: 'duron-postgres-test', port: 5440 }) + const release = Promise.withResolvers() + const pruneArchive = { olderThan: new Date('2099-01-01'), intervalMs: 30 } + const owner = new ScopePrune({ connection: first.CONNECTION_URL, pruneArchive }) + owner.hold = release.promise + owner.setId('schema-owner') + const contender = new ScopePrune({ + connection: first.CONNECTION_URL, + schema: 'prune_other', + migrateOnStart: false, + pruneArchive, + }) + contender.setId('schema-contender') + const independent = new ScopePrune({ connection: other.CONNECTION_URL, pruneArchive }) + independent.setId('database-independent') + const observer = postgres(first.CONNECTION_URL, { max: 1 }) + try { + expect(await owner.start()).toBe(true) + await eventually(async () => expect(owner.calls).toBe(1)) + const jobId = await owner.createJob({ + queue: 'schema-prune', + groupKey: 'one', + input: {}, + timeoutMs: 60_000, + checksum: 'scope', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(jobId).toBeDefined() + expect(await owner.cancelJob({ jobId: jobId! })).toBe(true) + // Native custom-schema fixture, not a claim of custom-schema migrations. + await observer`CREATE SCHEMA prune_other` + await observer`CREATE TABLE prune_other.clients (LIKE duron.clients INCLUDING ALL)` + await observer`CREATE TABLE prune_other.jobs_archive (LIKE duron.jobs_archive INCLUDING ALL)` + await observer`CREATE TABLE prune_other.job_steps_archive (LIKE duron.job_steps_archive INCLUDING ALL)` + await observer`INSERT INTO prune_other.jobs_archive SELECT * FROM duron.jobs_archive` + expect(await contender.start()).toBe(true) + await eventually(async () => expect(contender.contentions).toBeGreaterThanOrEqual(3)) + expect(contender.calls).toBe(0) + expect((await contender.getArchiveStats()).jobsCount).toBe(1) + expect(await independent.start()).toBe(true) + await eventually(async () => + expect((await independent.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date), + ) + expect(owner.calls).toBe(1) + expect(contender.calls).toBe(0) + // Direct calls must reach the actual override/super and preserve counts, + // despite a different schema's currently held scheduled key42 lock. + expect( + await contender.pruneArchive({ + olderThan: new Date('2099-01-01'), + batchSize: 1, + maxBatches: 1, + }), + ).toBe(1) + expect(contender.calls).toBe(1) + expect((await contender.getArchiveStats()).lastPrunedAt).toBeNull() + release.resolve() + await eventually(async () => + expect((await contender.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date), + ) + expect((await owner.getArchiveStats()).jobsCount).toBe(0) + expect(await owner.stop()).toBe(true) + expect(await contender.stop()).toBe(true) + expect(await independent.stop()).toBe(true) + await eventually(async () => { + expect( + await observer` + SELECT pid FROM pg_stat_activity + WHERE datname IN (${new URL(first.CONNECTION_URL).pathname.slice(1)}, ${new URL(other.CONNECTION_URL).pathname.slice(1)}) + AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + }) + } finally { + release.resolve() + await Promise.allSettled([owner.stop(), contender.stop(), independent.stop()]) + await observer.end({ timeout: 5 }) + await first.deleteDb() + await other.deleteDb() + } + }, 25_000) + + it('without retention the public adapter allocates no lock client and direct pruning still works', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const adapter = new ScopePrune({ connection: CONNECTION_URL }) + adapter.setId('opt-out') + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await Bun.sleep(100) + expect(adapter.calls).toBe(0) + expect((adapter as unknown as { pruneLock?: unknown }).pruneLock).toBeUndefined() + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(2) + expect( + await observer` + SELECT pid FROM pg_locks WHERE locktype = 'advisory' + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()) + `, + ).toHaveLength(0) + const id = await adapter.createJob({ + queue: 'manual-prune', + groupKey: 'one', + input: {}, + timeoutMs: 60_000, + checksum: 'manual', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expect(id).toBeDefined() + expect(await adapter.cancelJob({ jobId: id! })).toBe(true) + expect( + await adapter.pruneArchive({ + olderThan: new Date('2099-01-01'), + batchSize: 1, + maxBatches: 1, + }), + ).toBe(1) + expect(adapter.calls).toBe(1) + expect((adapter as unknown as { pruneLock?: unknown }).pruneLock).toBeUndefined() + expect((await adapter.getArchiveStats()).lastPrunedAt).toBeNull() + expect(await adapter.stop()).toBe(true) + } finally { + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) +} diff --git a/packages/duron/test/prune-transport.test.ts b/packages/duron/test/prune-transport.test.ts new file mode 100644 index 0000000..2cc71c2 --- /dev/null +++ b/packages/duron/test/prune-transport.test.ts @@ -0,0 +1,181 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' +import postgres, { type Sql } from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' +import { PruneRelay } from './prune-relay.js' + +async function eventually(check: () => Promise, timeout = 8_000): Promise { + const deadline = performance.now() + timeout + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(10) + } + } +} + +if (process.env['POSTGRES_TEST'] === 'true') { + for (const phase of [ + 'idle', + 'acquire reply', + 'unlock reply', + 'unlock reply after prune error', + ] as const) { + it(`post-boundary ${phase} loss never reconnects or returns the reservation`, async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const relay = new PruneRelay() + const pruneFailure = new Error('injected original prune failure before lost unlock reply') + const reports: unknown[] = [] + const statements: string[] = [] + let installed = false + let hooks = 0 + let reserves = 0 + let returns = 0 + let closed = false + let lost = false + class TransportPrune extends PostgresAdapter { + protected override _acquirePruneLock(): Promise { + const work = super._acquirePruneLock() + if (!installed) { + installed = true + const { client } = (this as unknown as { pruneLock: { client: Sql } }).pruneLock + client.options.host[0] = '127.0.0.1' + client.options.port[0] = relay.port + client.options.debug = (_, query) => { + statements.push(query) + if ( + (phase === 'acquire reply' && query.includes('pg_try_advisory_lock')) || + (phase.startsWith('unlock reply') && query.includes('pg_advisory_unlock')) + ) + relay.hold = () => true + } + const reserve = client.reserve.bind(client) + client.reserve = async () => { + reserves++ + const session = await reserve() + const release = session.release.bind(session) + session.release = () => { + returns++ + release() + } + return session + } + const end = client.end.bind(client) + client.end = async (options) => { + await end(options) + closed = true + } + } + return work + } + protected override _retirePruning(error: unknown): void { + lost = true + super._retirePruning(error) + } + protected override async _pruneArchive(): Promise { + hooks++ + if (phase === 'unlock reply after prune error') throw pruneFailure + return 0 + } + } + const url = new URL(CONNECTION_URL) + const adapter = new TransportPrune({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + }, + pruneArchive: { olderThan: '1d', intervalMs: 60_000 }, + }) + adapter.setId(`transport-${phase}`) + const logger = pino({ level: 'silent' }) + logger.error = (error: unknown) => { + reports.push(error) + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => { + expect(relay.connections).toHaveLength(1) + expect(relay.connections[0]!.pid).toBeGreaterThan(0) + if (phase === 'idle') expect(hooks).toBe(1) + else expect(relay.held.some(({ frame }) => frame[0] === 90)).toBe(true) + }) + const pid = relay.connections[0]!.pid! + // Independent server evidence: the acquire/unlock executed despite its + // withheld reply. Idle loss occurs after the successful true unlock. + await eventually(async () => { + const locks = await observer` + SELECT pid FROM pg_locks WHERE pid = ${pid} AND locktype = 'advisory' + AND classid = 0 AND objid = 42 AND objsubid = 1 AND granted + ` + expect(locks).toHaveLength(phase === 'acquire reply' ? 1 : 0) + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() + AND pid = ${pid} AND state = 'idle' + `, + ).toHaveLength(1) + }) + relay.cut(relay.connections[0]!) + await eventually(async () => expect(lost).toBe(true)) + await eventually(async () => expect(closed).toBe(true)) + await eventually(async () => expect(reports.length).toBeGreaterThan(0)) + const errors = reports.flatMap((error) => + error instanceof AggregateError ? error.errors : [error], + ) + if (phase !== 'idle') + expect( + errors.some((error) => (error as { code?: string }).code === 'CONNECTION_CLOSED'), + ).toBe(true) + if (phase === 'unlock reply after prune error') expect(errors[0]).toBe(pruneFailure) + expect(hooks).toBe(phase === 'acquire reply' ? 0 : 1) + const stats = await adapter.getArchiveStats() + if (phase === 'acquire reply' || phase === 'unlock reply after prune error') + expect(stats.lastPrunedAt).toBeNull() + else expect(stats.lastPrunedAt).toBeInstanceOf(Date) + const issued = statements.length + await Bun.sleep(250) + expect(statements).toHaveLength(issued) + expect(relay.connections).toHaveLength(1) + expect(reserves).toBe(1) + expect(returns).toBe(0) + expect(relay.sockets).toBe(0) + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(2) + expect(await adapter.stop()).toBe(true) + expect(returns).toBe(0) + expect( + await observer` + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + expect(relay.connections).toHaveLength(1) + expect(relay.errors).toEqual([]) + } finally { + relay.flush() + await adapter.stop().catch(() => undefined) + await relay.close() + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 20_000) + } +} From 0479f59074bc2c9cce1b9890cdda547f4b890f1e Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 9 Nov 2026 11:50:41 -0300 Subject: [PATCH 008/100] fix: reconcile pending waits with bounded read deadlines --- packages/docs/content/docs/client-api.mdx | 35 +- packages/duron/src/adapters/postgres/base.ts | 59 +++- .../duron/src/adapters/postgres/postgres.ts | 42 +++ packages/duron/src/client.ts | 231 +++---------- packages/duron/src/wait-manager.ts | 272 +++++++++++++++ packages/duron/src/wait-read.ts | 62 ++++ packages/duron/test/wait-cadence.test.ts | 258 ++++++++++++++ packages/duron/test/wait-cancellation.test.ts | 87 +++++ packages/duron/test/wait-capacity.test.ts | 132 +++++++ packages/duron/test/wait-cohorts.test.ts | 327 ++++++++++++++++++ packages/duron/test/wait-context.test.ts | 271 +++++++++++++++ packages/duron/test/wait-lifecycle.test.ts | 68 ++++ packages/duron/test/wait-native.test.ts | 194 +++++++++++ packages/duron/test/wait-options.test.ts | 23 ++ packages/duron/test/wait-pglite.test.ts | 88 +++++ packages/duron/test/wait-pool.test.ts | 102 ++++++ .../duron/test/wait-reconciliation.test.ts | 129 +++++++ packages/duron/test/wait-results.test.ts | 102 ++++++ packages/duron/test/wait-transport.test.ts | 148 ++++++++ 19 files changed, 2429 insertions(+), 201 deletions(-) create mode 100644 packages/duron/src/wait-manager.ts create mode 100644 packages/duron/src/wait-read.ts create mode 100644 packages/duron/test/wait-cadence.test.ts create mode 100644 packages/duron/test/wait-cancellation.test.ts create mode 100644 packages/duron/test/wait-capacity.test.ts create mode 100644 packages/duron/test/wait-cohorts.test.ts create mode 100644 packages/duron/test/wait-context.test.ts create mode 100644 packages/duron/test/wait-lifecycle.test.ts create mode 100644 packages/duron/test/wait-native.test.ts create mode 100644 packages/duron/test/wait-options.test.ts create mode 100644 packages/duron/test/wait-pglite.test.ts create mode 100644 packages/duron/test/wait-pool.test.ts create mode 100644 packages/duron/test/wait-reconciliation.test.ts create mode 100644 packages/duron/test/wait-results.test.ts create mode 100644 packages/duron/test/wait-transport.test.ts diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 27315fb..43639f8 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -88,9 +88,25 @@ const client = duron({ } ``` +### `waitReadTimeout` + +**Optional.** One elapsed budget in milliseconds per admitted wait-result read chain. Defaults to `5000`. Values must be integers from `1` through `2,147,483,647`; zero, fractions, nonnumeric values and disable values are rejected. + +The budget starts when a chain takes an actual slot, **not** while it waits in the Client FIFO. It covers pool acquisition, status/detail and active/archive reads, processing, and cleanup observation without resetting between stages. Initial participants settle `null` on expiry; established waiters remain pending. Late results are discarded, but actual capacity remains occupied until the underlying work and transaction cleanup settle. + +Built-in PostgreSQL wait reads use a transaction-bound database context with READ COMMITTED isolation and a transaction-local remaining `statement_timeout`, preserving stricter inherited settings. Ordinary public reads and unrelated operations keep their settings. Pool waiting, initial setup, transport and rollback can outlast the observer; there is no active cancellation, reconnect, replacement client, or mutation replay. Transaction/setup round trips have overhead; no zero-cost or hard end-to-end deadline is promised. + +Custom Client/Adapter read overrides remain real calls and may use an observation-only fallback. Their arbitrary internal SQL/JavaScript is not physically bounded by this option. PGLite has observer/continuation accounting, not PostgreSQL execution-timeout parity; synchronous WASM can delay timers. A blocked event loop can delay all observer/caller cancellation. + +```ts +const client = new Client({ database, waitReadTimeout: 3000 }) +``` + ### `pullInterval` -**Optional.** Interval in milliseconds between pull operations. Defaults to `5000`. +**Optional.** Interval in milliseconds between worker pull operations, and the cadence and error cooldown for pending-wait reconciliation in every sync mode. Defaults to `5000`. Wait reconciliation also runs without actions and with `syncPattern: false`; it never fetches or executes jobs. + +For wait scheduling only, a positive finite interval is floored and clamped to `1–2,147,483,647`; other accepted values use `5000`. Existing worker option validation and cadence are unchanged. ```ts { @@ -555,7 +571,9 @@ const status = await client.getJobStepStatus(stepId) ### `waitForJob(jobId, options?)` -Wait for a job to change status by subscribing to job-status-changed events. When the job status changes, the job is fetched and returned. This method uses a shared event listener, so multiple concurrent calls are efficient. +Wait for a readable **completed**, **failed**, or **cancelled** job result. Shared notification hints provide a fast path; while waits remain registered, an independent Client loop also checks retained results at `pullInterval`. Lost hints and recovery-produced terminal failures do not require a worker fetch or a fresh notification. + +Initial and periodic checks read lightweight status before terminal detail. Hints request detail directly. Returned detail must itself be terminal: a stale hint or earlier terminal status is not sufficient after time travel. ```ts const job = await client.waitForJob(jobId) @@ -564,10 +582,10 @@ const job = await client.waitForJob(jobId) **Parameters:** - `jobId` - The ID of the job to wait for -- `options.timeout` - Optional timeout in milliseconds. If the job status doesn't change within this time, the promise resolves to `null`. Defaults to no timeout (waits indefinitely). +- `options.timeout` - Optional caller waiting timeout in milliseconds. Expiry resolves this waiter to `null`; omission means no caller timeout. This is separate from the Client's `waitReadTimeout`. - `options.signal` - Optional AbortSignal to cancel waiting. If aborted, the promise resolves to `null`. -**Returns:** Promise resolving to the job when its status changes, or `null` if timeout or aborted +**Returns:** A terminal result containing `id`, `actionName`, `status`, `groupKey`, `description`, `input`, `output`, and `error`. Returns `null` on caller timeout/abort, stop, initial-check failure/expiry, or missing detail after a terminal status/hint. `null` does not mean the job failed. **Example:** @@ -588,9 +606,12 @@ controller.abort() **Notes:** -- If the job is already in a terminal state (completed, failed, or cancelled), the method returns immediately without waiting. -- Multiple concurrent `waitForJob` calls for the same job share a single event listener for efficiency. -- The method automatically cleans up event listeners and timeouts when the promise resolves. +- Already-terminal jobs still require a successful admitted read. Missing/nonterminal status keeps the wait pending. Established waiters survive later read failures and retry after a `pullInterval` cooldown; expired reads start their cooldown only after actual settlement. +- Waiters share a listener and bounded FIFO read scheduling, not cancellation. Cancelling one waiter leaves siblings registered. A waiter arriving after a read starts cannot receive that read's result. +- Each periodic pass considers at most ten IDs in round-robin order. Initial/hint checks share a four-actual-chain limit and one chain per ID. No waits means no periodic wait timer. These are work bounds, not completion or query-rate guarantees. +- Expired results are discarded. Caller cancellation and read-observer expiry do **not** cancel SQL or release actual capacity. Four unresolved chains can block all further checks, including queued initial reads. +- Retained results must remain readable long enough to be observed. Pruned output cannot be reconstructed; there is no stronger SQL snapshot or execution-generation guarantee. +- Stop settles pending waits locally and drains actual reads/transaction cleanup under the existing shared five-second drain budget. `waitReadTimeout` does not extend or reset any lifecycle phase. ### `getActions()` diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 841c470..dda3b40 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -29,6 +29,7 @@ import { STEP_STATUS_FAILED, } from '../../constants.js' import { lifecycleFor, throwLifecycleErrors } from '../../lifecycle.js' +import { type WaitReadBudget, registerWaitReadExecutor } from '../../wait-read.js' import { Adapter, type ArchiveStats, @@ -109,6 +110,12 @@ export abstract class PostgresBaseAdapter< private initialized = false protected ownedClosed = false private listenerObligations: Array<{ done: boolean }> = [] + private readonly waitReadContext = new AsyncLocalStorage<{ + db: DrizzleDatabase + budget: WaitReadBudget + prepare: (remaining: number) => Promise + active: boolean + }>() // ============================================================================ // Constructor @@ -131,6 +138,7 @@ export abstract class PostgresBaseAdapter< this._initDb() this._guardTransactions() + registerWaitReadExecutor(this, (budget, work) => this._executeWaitRead(budget, work)) lifecycleFor(this).onQuiesce(() => this._stopScheduler()) } @@ -140,6 +148,8 @@ export abstract class PostgresBaseAdapter< protected abstract _initDb(): void protected _assertSql(): void { + const waitRead = this.waitReadContext.getStore() + if (waitRead?.active) waitRead.budget.remaining(waitRead.budget.stage) if (this.scheduledPrune.getStore() && this.pruneRetired) { throw new Error('Scheduled prune coordination is retired') } @@ -162,6 +172,46 @@ export abstract class PostgresBaseAdapter< } } + // Wait-only context; public reads and protected overrides remain real calls. + // PGLite/custom fallback gets continuation gates, not execution cancellation. + protected _executeWaitRead(budget: WaitReadBudget, work: () => Promise): Promise { + return this._withWaitRead(this.db, budget, async () => undefined, work) + } + + protected _waitReadsAreBuiltIn(): boolean { + return ( + this.getJobStatus === Adapter.prototype.getJobStatus && + this.getJobById === Adapter.prototype.getJobById && + this._getJobStatus === PostgresBaseAdapter.prototype._getJobStatus && + this._getJobById === PostgresBaseAdapter.prototype._getJobById + ) + } + + protected async _withWaitRead( + db: DrizzleDatabase, + budget: WaitReadBudget, + prepare: (remaining: number) => Promise, + work: () => Promise, + ): Promise { + const context = { db, budget, prepare, active: true } + try { + return await this.waitReadContext.run(context, work) + } finally { + // Never reuse a transaction from an inherited, already-settled async scope. + context.active = false + } + } + + private async _waitLookupDb(stage: string): Promise { + const context = this.waitReadContext.getStore() + if (!context?.active) return this.db + const remaining = context.budget.remaining(`${stage} setup`) + await context.prepare(remaining) + context.budget.remaining(stage) + this._assertSql() + return context.db + } + // ============================================================================ // Lifecycle Methods // ============================================================================ @@ -1578,7 +1628,8 @@ export abstract class PostgresBaseAdapter< END `.as('duration_ms') - const [job] = await this.db + const db = await this._waitLookupDb('detail lookup') + const [job] = await db .select({ id: jobsTable.id, actionName: jobsTable.action_name, @@ -2081,7 +2132,8 @@ export abstract class PostgresBaseAdapter< */ protected async _getJobStatus(jobId: string): Promise { // Try active table first - const [activeJob] = await this.db + const activeDb = await this._waitLookupDb('active status lookup') + const [activeJob] = await activeDb .select({ status: this.tables.jobsActiveTable.status, updatedAt: this.tables.jobsActiveTable.updated_at, @@ -2095,7 +2147,8 @@ export abstract class PostgresBaseAdapter< } // Try archive table - const [archiveJob] = await this.db + const archiveDb = await this._waitLookupDb('archive status lookup') + const [archiveJob] = await archiveDb .select({ status: this.tables.jobsArchiveTable.status, updatedAt: this.tables.jobsArchiveTable.updated_at, diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index 74de41c..f2dee23 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -1,11 +1,13 @@ import { join } from 'node:path' +import { sql } from 'drizzle-orm' import { drizzle } from 'drizzle-orm/postgres-js' import { migrate } from 'drizzle-orm/postgres-js/migrator' import { defineRelations } from 'drizzle-orm/relations' import type { Options as PostgresOptions } from 'postgres' import { lifecycleFor } from '../../lifecycle.js' +import type { WaitReadBudget } from '../../wait-read.js' import { type AdapterOptions, PostgresBaseAdapter } from './base.js' import { PostgresPruneLock } from './prune-lock.js' @@ -32,6 +34,46 @@ export type DB = ReturnType | string> { private pruneLock: PostgresPruneLock | undefined + protected override async _executeWaitRead( + budget: WaitReadBudget, + work: () => Promise, + ): Promise { + // Arbitrary overrides can use this.db themselves. Pinning a transaction around + // those calls can deadlock a max:1 pool and would not bound their own SQL. + if (!this._waitReadsAreBuiltIn()) return super._executeWaitRead(budget, work) + budget.remaining('transaction acquisition') + let callback: Promise | undefined + try { + return await this.db.transaction((tx) => { + callback = (async () => { + budget.remaining('transaction setup') + // Explicitly keep wait reads READ COMMITTED even with a different inherited + // default. Do not supply Drizzle config, which runs before our budget gate. + await tx.execute(sql`SET TRANSACTION ISOLATION LEVEL READ COMMITTED`) + budget.remaining('transaction setup result') + return this._withWaitRead( + tx, + budget, + async (remaining) => { + await tx.execute(sql`SELECT set_config('statement_timeout', + (CASE WHEN setting::bigint > 0 AND setting::bigint < ${remaining} + THEN setting::bigint ELSE ${remaining} END)::text, true) + FROM pg_settings WHERE name = 'statement_timeout'`) + }, + work, + ) + })().finally(() => { + budget.stage = 'transaction cleanup' + }) + return callback + }) + } finally { + // postgres.js can reject begin() on connection close before its callback + // finishes. Neither that race nor observer expiry discharges callback work. + await callback?.catch(() => undefined) + } + } + protected override _acquirePruneLock(): Promise { this.pruneLock ??= new PostgresPruneLock(this.connection, lifecycleFor(this), (error) => this._retirePruning(error), diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 1e34462..7959245 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -26,14 +26,10 @@ import type { PruneArchiveOptions, } from './adapters/adapter.js' import type { JobStatusResult, JobStepStatusResult } from './adapters/schemas.js' -import { - JOB_STATUS_CANCELLED, - JOB_STATUS_COMPLETED, - JOB_STATUS_FAILED, - type JobStatus, -} from './constants.js' +import { JOB_STATUS_CANCELLED, JOB_STATUS_FAILED, type JobStatus } from './constants.js' import { type Lifecycle, lifecycleFor } from './lifecycle.js' import { validateSchema } from './standard-schema.js' +import { WaitManager } from './wait-manager.js' /** * Extracts the inferred type from an action's input/output schema. @@ -162,13 +158,22 @@ export interface BaseOptionsInput { syncPattern?: 'pull' | 'push' | 'hybrid' | false /** - * Interval in milliseconds between pull operations when using `'pull'` or `'hybrid'` sync pattern. - * Lower values mean faster job pickup but more database queries. + * Worker pull interval and pending-wait reconciliation cadence/error cooldown. + * Wait reconciliation runs independently of actions and syncPattern, without fetching jobs. + * For waits only: floor/clamp positive finite values to 1–2,147,483,647; otherwise use 5000. * * @default 5000 */ pullInterval?: number + /** + * Elapsed budget in milliseconds for each admitted wait-result read chain. + * Integer 1–2,147,483,647; no disable value. Not the caller's waiting timeout. + * Outstanding reads retain capacity after expiry until actual cleanup settles. + * @default 5000 + */ + waitReadTimeout?: number + /** * Maximum number of jobs to fetch in a single batch from the database. * Higher values reduce database round-trips but may increase memory usage. @@ -255,6 +260,10 @@ const BaseOptionsSchema = z.object({ 'hybrid', ), pullInterval: z._default(z.number(), 5_000), + waitReadTimeout: z._default( + z.number().check(z.int(), z.minimum(1), z.maximum(2_147_483_647)), + 5_000, + ), batchSize: z._default(z.number(), 10), actionConcurrencyLimit: z._default(z.number(), 100), groupConcurrencyLimit: z._default(z.number(), 10), @@ -354,15 +363,7 @@ export class Client< #lastRecoveryAt: number = 0 #actionManagers = new Map>>() #mockInputSchemas = new Map() - #pendingJobWaits = new Map< - string, - Set<{ - resolve: (result: JobResult | null) => void - timeoutId?: NodeJS.Timeout - signal?: AbortSignal - abortHandler?: () => void - }> - >() + #waits: WaitManager #jobStatusListenerSetup = false #pushListenerSetup = false #jobStatusListener: @@ -390,6 +391,19 @@ export class Client< this.#logger = this.#normalizeLogger(options?.logger) this.#database.setId(this.#id) this.#database.setLogger(this.#logger) + this.#waits = new WaitManager( + this.#database, + this.#lifecycle, + this.#logger, + this.#options.pullInterval, + this.#options.waitReadTimeout, + (id) => this.getJobStatus(id), + (id) => this.getJobById(id), + () => + this.getJobStatus === Client.prototype.getJobStatus && + this.getJobById === Client.prototype.getJobById && + this.start === Client.prototype.start, + ) // Initialize OpenTelemetry TracerProvider if telemetry options are provided // Get tracer from our provider if configured, otherwise use global no-op tracer @@ -922,18 +936,18 @@ export class Client< } /** - * Wait for a job to change status by subscribing to job-status-changed events. - * When the job status changes, the job result is returned. + * Wait for readable completed/failed/cancelled detail, using hints and independent reconciliation. + * Reads share bounded capacity. Lost hints do not require worker fetching; pruned results cannot be reconstructed. * * @param jobId - The ID of the job to wait for * @param options - Optional configuration including timeout - * @returns Promise resolving to the job result when its status changes, or `null` if timeout + * @returns Terminal result, or null on timeout/abort/stop, initial read failure/expiry, or missing detail */ async waitForJob( jobId: string, options?: { /** - * Timeout in milliseconds. If the job status doesn't change within this time, the promise resolves to `null`. + * Caller waiting timeout in milliseconds; expiry resolves to null without cancelling underlying SQL. * Defaults to no timeout (waits indefinitely). */ timeout?: number @@ -951,86 +965,8 @@ export class Client< // Set up the shared event listener if not already set up this.#setupJobStatusListener() - // Register the wait BEFORE checking status to prevent TOCTOU race - // If the job completes between status check and wait registration, - // the NOTIFY would be missed - let timeoutId: NodeJS.Timeout | undefined - let abortHandler: (() => void) | undefined - - return new Promise((resolve) => { - // Check if already aborted before setting up wait - if (options?.signal?.aborted) { - resolve(null) - return - } - - // Set up timeout if provided - if (options?.timeout) { - timeoutId = setTimeout(() => { - this.#removeJobWait(jobId, resolve) - resolve(null) - }, options.timeout) - } - - // Set up abort signal if provided - if (options?.signal) { - abortHandler = () => { - this.#removeJobWait(jobId, resolve) - resolve(null) - } - options.signal.addEventListener('abort', abortHandler) - } - - // Add this wait request to the pending waits BEFORE checking status - if (!this.#pendingJobWaits.has(jobId)) { - this.#pendingJobWaits.set(jobId, new Set()) - } - this.#pendingJobWaits.get(jobId)!.add({ - resolve, - timeoutId, - signal: options?.signal, - abortHandler, - }) - - // Now check if the job is already in a terminal state - // If so, remove the wait and resolve immediately - // Errors settle the wait as null to avoid hangs and leaked wait entries - void this.#lifecycle - .run(async () => { - const existingJobStatus = await this.getJobStatus(jobId) - if (!this.#lifecycle.accepting) return - const terminalStatuses: JobStatus[] = [ - JOB_STATUS_COMPLETED, - JOB_STATUS_FAILED, - JOB_STATUS_CANCELLED, - ] - if (existingJobStatus && terminalStatuses.includes(existingJobStatus.status)) { - const job = await this.getJobById(jobId) - if (!this.#lifecycle.accepting) return - // Keep the wait registered while detail is pending so stop can settle it. - this.#removeJobWait(jobId, resolve) - resolve( - job - ? { - id: job.id, - actionName: job.actionName, - status: job.status, - groupKey: job.groupKey, - description: job.description, - input: job.input, - output: job.output, - error: job.error, - } - : null, - ) - } - }) - .catch((error: unknown) => { - this.#logger.error({ error, jobId }, '[Duron] [waitForJob] Error checking job status') - this.#removeJobWait(jobId, resolve) - resolve(null) - }) - }) + // Listener and waiter registration precede the first admitted read. + return this.#waits.wait(jobId, options) }) } @@ -1205,15 +1141,7 @@ export class Client< this.#pushListener = null this.#pushListenerSetup = false } - for (const waits of this.#pendingJobWaits.values()) { - for (const wait of waits) { - if (wait.timeoutId) clearTimeout(wait.timeoutId) - if (wait.signal && wait.abortHandler) - wait.signal.removeEventListener('abort', wait.abortHandler) - wait.resolve(null) - } - } - this.#pendingJobWaits.clear() + this.#waits.stop() return Promise.all([...this.#actionManagers.values()].map((manager) => manager.stop())).then( () => undefined, ) @@ -1234,92 +1162,13 @@ export class Client< this.#jobStatusListenerSetup = true - this.#jobStatusListener = async (event: { - jobId: string - status: JobStatus | 'retried' - clientId: string - }) => { - if (!this.#lifecycle.accepting) return - return this.#lifecycle - .run(async () => { - const pendingWaits = this.#pendingJobWaits.get(event.jobId) - if (!pendingWaits || pendingWaits.size === 0) { - return - } - - // Fetch the job once for all pending waits - const job = await this.getJobById(event.jobId) - if (!this.#lifecycle.accepting) return - - // Transform to JobResult - const result: JobResult | null = job - ? { - id: job.id, - actionName: job.actionName, - status: job.status, - groupKey: job.groupKey, - description: job.description, - input: job.input, - output: job.output, - error: job.error, - } - : null - - // Resolve all pending waits for this job - const waitsToResolve = Array.from(pendingWaits) - this.#pendingJobWaits.delete(event.jobId) - - for (const wait of waitsToResolve) { - // Clean up timeout and abort signal - if (wait.timeoutId) { - clearTimeout(wait.timeoutId) - } - if (wait.signal && wait.abortHandler) { - wait.signal.removeEventListener('abort', wait.abortHandler) - } - wait.resolve(result) - } - }) - .catch((error: unknown) => { - this.#logger.error({ error, jobId: event.jobId }, '[Duron] Status callback failed') - }) + this.#jobStatusListener = async (event) => { + this.#waits.hint(event.jobId) } this.#database.on('job-status-changed', this.#jobStatusListener) } - /** - * Remove a specific wait request from the pending waits. - * - * @param jobId - The job ID - * @param resolve - The resolve function to remove - */ - #removeJobWait(jobId: string, resolve: (result: JobResult | null) => void) { - const pendingWaits = this.#pendingJobWaits.get(jobId) - if (!pendingWaits) { - return - } - - // Find and remove the specific wait request - for (const wait of pendingWaits) { - if (wait.resolve === resolve) { - if (wait.timeoutId) { - clearTimeout(wait.timeoutId) - } - if (wait.signal && wait.abortHandler) { - wait.signal.removeEventListener('abort', wait.abortHandler) - } - pendingWaits.delete(wait) - break - } - } - - // Clean up empty sets - if (pendingWaits.size === 0) { - this.#pendingJobWaits.delete(jobId) - } - } - /** * Execute a job by finding its action and queuing it with the appropriate ActionManager. * diff --git a/packages/duron/src/wait-manager.ts b/packages/duron/src/wait-manager.ts new file mode 100644 index 0000000..5e9a415 --- /dev/null +++ b/packages/duron/src/wait-manager.ts @@ -0,0 +1,272 @@ +import type { Logger } from 'pino' + +import type { Job, JobStatusResult } from './adapters/adapter.js' +import type { JobResult } from './client.js' +import type { Lifecycle } from './lifecycle.js' +import { WaitReadBudget, WaitReadExpired, WaitReadStopped, executeWaitRead } from './wait-read.js' + +type Waiter = { + initial: boolean + resolve: (result: JobResult | null) => void + timer?: ReturnType + signal?: AbortSignal + abort?: () => void +} +type Cohort = { id: string; waiters: Set; cooldown: number } +type Request = { hint: boolean } +type Observation = { kind: 'status' } | { kind: 'detail'; job: Job | null } + +function terminal(status: string): boolean { + return status === 'completed' || status === 'failed' || status === 'cancelled' +} + +/** Client-owned demand only. Worker fetch/recovery never depends on this scheduler. */ +export class WaitManager { + readonly #cohorts = new Map() + readonly #queue = new Map() + readonly #active = new Set() + #rotation: MapIterator | undefined + #timer: ReturnType | undefined + #pumping = false + readonly #interval: number + + constructor( + readonly adapter: object, + readonly lifecycle: Lifecycle, + readonly logger: Logger, + interval: number, + readonly timeout: number, + readonly readStatus: (id: string) => Promise, + readonly readDetail: (id: string) => Promise, + readonly builtInClientReads: () => boolean, + ) { + this.#interval = + Number.isFinite(interval) && interval > 0 + ? Math.min(2_147_483_647, Math.max(1, Math.floor(interval))) + : 5_000 + } + + wait( + id: string, + options?: { timeout?: number; signal?: AbortSignal }, + ): Promise { + if (!this.lifecycle.accepting || options?.signal?.aborted) return Promise.resolve(null) + let cohort = this.#cohorts.get(id) + if (!cohort) { + cohort = { id, waiters: new Set(), cooldown: 0 } + this.#cohorts.set(id, cohort) + } + const captured = cohort + return new Promise((resolve) => { + const waiter: Waiter = { initial: true, resolve, signal: options?.signal } + captured.waiters.add(waiter) + if (options?.timeout) { + waiter.timer = setTimeout(() => this.#settle(captured, waiter, null), options.timeout) + } + if (options?.signal) { + waiter.abort = () => this.#settle(captured, waiter, null) + options.signal.addEventListener('abort', waiter.abort) + } + this.#request(captured, false) + this.#schedule() + }) + } + + hint(id: string): void { + const cohort = this.#cohorts.get(id) + if (cohort && this.lifecycle.accepting) this.#request(cohort, true) + } + + stop(): void { + for (const cohort of this.#cohorts.values()) { + for (const waiter of cohort.waiters) this.#settle(cohort, waiter, null) + } + this.#idle() + } + + #current(cohort: Cohort): boolean { + return this.#cohorts.get(cohort.id) === cohort && cohort.waiters.size > 0 + } + + #settle(cohort: Cohort, waiter: Waiter, result: JobResult | null): void { + if (!this.#current(cohort) || !cohort.waiters.delete(waiter)) return + if (waiter.timer !== undefined) clearTimeout(waiter.timer) + if (waiter.signal && waiter.abort) waiter.signal.removeEventListener('abort', waiter.abort) + waiter.resolve(result) + if (!cohort.waiters.size) { + this.#cohorts.delete(cohort.id) + this.#queue.delete(cohort) + } + if (!this.#cohorts.size) this.#idle() + } + + #idle(): void { + if (this.#timer !== undefined) clearTimeout(this.#timer) + this.#timer = undefined + this.#queue.clear() + this.#rotation = undefined + // Actual chains are deliberately not removed here. + } + + #schedule(): void { + if (this.#timer !== undefined || !this.#cohorts.size || !this.lifecycle.accepting) return + this.#timer = setTimeout(() => { + this.#timer = undefined + if (!this.lifecycle.accepting) return + const count = Math.min(10, this.#cohorts.size) + for (let index = 0; index < count; index++) { + this.#rotation ??= this.#cohorts.values() + let next = this.#rotation.next() + if (next.done) { + this.#rotation = this.#cohorts.values() + next = this.#rotation.next() + } + if (next.done) break + const cohort = next.value + // Advance rotation even when this ID is busy or cooling down. + if (!this.#active.has(cohort.id) && cohort.cooldown <= performance.now()) { + this.#request(cohort, false) + } + } + this.#schedule() + }, this.#interval) + } + + #request(cohort: Cohort, hint: boolean): void { + if (!this.lifecycle.accepting || !this.#current(cohort)) return + const queued = this.#queue.get(cohort) + if (queued) queued.hint ||= hint + else this.#queue.set(cohort, { hint }) + if (this.#pumping) return + this.#pumping = true + queueMicrotask(() => { + this.#pumping = false + this.#pump() + }) + } + + #pump(): void { + if (!this.lifecycle.accepting) return + for (const [cohort, request] of this.#queue) { + if (this.#active.size >= 4) break + if (this.#active.has(cohort.id) || cohort.cooldown > performance.now()) continue + this.#queue.delete(cohort) + if (!this.#current(cohort)) continue + this.#admit(cohort, request) + } + } + + #admit(cohort: Cohort, request: Request): void { + this.#active.add(cohort.id) + const eligible = [...cohort.waiters] + const initial = eligible.filter((waiter) => waiter.initial) + const statusFirst = initial.length > 0 || !request.hint + const trigger = initial.length ? 'initial' : request.hint ? 'hint' : 'periodic' + const currentMembers = () => eligible.filter((waiter) => cohort.waiters.has(waiter)) + const hasDemand = () => + this.lifecycle.accepting && this.#current(cohort) && currentMembers().length > 0 + const counts = () => ({ + initial: currentMembers().filter((waiter) => initial.includes(waiter)).length, + established: currentMembers().filter((waiter) => !initial.includes(waiter)).length, + }) + const budget = new WaitReadBudget(this.timeout, hasDemand, () => { + this.#log( + { + jobId: cohort.id, + trigger, + stage: budget.stage, + budget: budget.timeout, + elapsed: budget.elapsed, + affected: counts(), + unresolved: !budget.settled, + }, + '[Duron] Wait read expired', + ) + for (const waiter of initial) this.#settle(cohort, waiter, null) + }) + let failed = false + const read = async (): Promise => { + if (statusFirst) { + budget.remaining('status') + const status = await this.readStatus(cohort.id) + budget.remaining('status result') + if (!status || !terminal(status.status)) return { kind: 'status' } + } + budget.remaining('detail') + const job = await this.readDetail(cohort.id) + budget.remaining('detail result') + return { kind: 'detail', job } + } + const work = this.lifecycle.run(() => + this.builtInClientReads() ? executeWaitRead(this.adapter, budget, read) : read(), + ) + // Track/observe the raw chain, not the expiry or caller-wait promise. + void work + .then( + (observation) => { + budget.finish() + if (budget.expired || !hasDemand()) return + // Eligibility scanning/result processing can itself consume elapsed time. + budget.finish() + if (budget.expired) return + for (const waiter of initial) waiter.initial = false + if (observation.kind === 'status') { + if (request.hint) this.#request(cohort, true) + return + } + const job = observation.job + if (job && !terminal(job.status)) return + const result: JobResult | null = job + ? { + id: job.id, + actionName: job.actionName, + status: job.status, + groupKey: job.groupKey, + description: job.description, + input: job.input, + output: job.output, + error: job.error, + } + : null + for (const waiter of eligible) this.#settle(cohort, waiter, result) + }, + (error: unknown) => { + budget.finish() + if (error instanceof WaitReadStopped || error instanceof WaitReadExpired) return + failed = true + this.#log( + { + error, + jobId: cohort.id, + trigger, + stage: budget.stage, + affected: counts(), + late: budget.expired, + }, + '[Duron] Wait read failed', + ) + if (!budget.expired) for (const waiter of initial) this.#settle(cohort, waiter, null) + }, + ) + .finally(() => { + budget.finish() + this.#active.delete(cohort.id) + if ((failed || budget.expired) && this.#current(cohort)) { + cohort.cooldown = performance.now() + this.#interval + } + this.#pump() + }) + .catch((error: unknown) => { + this.#log({ error, jobId: cohort.id }, '[Duron] Wait settlement failed') + }) + } + + #log(fields: object, message: string): void { + // A custom logger must not leave an event callback rejection unobserved. + try { + this.logger.error(fields, message) + } catch { + /* no second logger is available */ + } + } +} diff --git a/packages/duron/src/wait-read.ts b/packages/duron/src/wait-read.ts new file mode 100644 index 0000000..15a2260 --- /dev/null +++ b/packages/duron/src/wait-read.ts @@ -0,0 +1,62 @@ +// Internal wait-only execution seam. Not exported from the package entrypoints. +// Overrides continue to run through their public methods; unsupported adapters +// retain observer/accounting protection, not a physical cancellation guarantee. +export class WaitReadStopped extends Error {} +export class WaitReadExpired extends Error {} + +export class WaitReadBudget { + readonly startedAt = performance.now() + stage = 'admission' + expired = false + settled = false + #timer: ReturnType + + constructor( + readonly timeout: number, + readonly eligible: () => boolean, + readonly onExpiry: () => void, + ) { + this.#timer = setTimeout(() => this.expire(), timeout) + } + + get elapsed(): number { + return performance.now() - this.startedAt + } + + expire(): void { + if (this.expired) return + this.expired = true + this.onExpiry() + } + + remaining(stage: string): number { + this.stage = stage + const remaining = Math.floor(this.timeout - this.elapsed) + if (remaining < 1) this.expire() + if (this.expired) throw new WaitReadExpired('Wait read budget expired') + if (!this.eligible()) throw new WaitReadStopped('Wait read no longer eligible') + return remaining + } + + finish(): void { + this.settled = true + clearTimeout(this.#timer) + // An overdue callback may not have run (notably during synchronous WASM). + if (this.elapsed >= this.timeout) this.expire() + } +} + +type Executor = (budget: WaitReadBudget, work: () => Promise) => Promise +const executors = new WeakMap() + +export function registerWaitReadExecutor(adapter: object, executor: Executor): void { + executors.set(adapter, executor) +} + +export function executeWaitRead( + adapter: object, + budget: WaitReadBudget, + work: () => Promise, +): Promise { + return executors.get(adapter)?.(budget, work) ?? work() +} diff --git a/packages/duron/test/wait-cadence.test.ts b/packages/duron/test/wait-cadence.test.ts new file mode 100644 index 0000000..72dffd6 --- /dev/null +++ b/packages/duron/test/wait-cadence.test.ts @@ -0,0 +1,258 @@ +import { describe, expect, it } from 'bun:test' + +import { defineAction } from '../src/action.js' +import { Client } from '../src/client.js' + +import { pgliteFactory, postgresFactory } from './adapters.js' + +// Observational only: every callback, delay and argument reaches the native +// timer unchanged. Serial tests restore both functions even on assertion failure. +function observeTimers() { + const schedule = globalThis.setTimeout + const clear = globalThis.clearTimeout + const scheduled: Array<{ timer: ReturnType; delay: number | undefined }> = [] + const cleared = new Set[0]>() + globalThis.setTimeout = ((...args: Parameters) => { + const timer = schedule(...args) + scheduled.push({ timer, delay: args[1] }) + return timer + }) as typeof setTimeout + globalThis.clearTimeout = ((...args: Parameters) => { + cleared.add(args[0]) + return clear(...args) + }) as typeof clearTimeout + return { + scheduled, + cleared, + restore() { + globalThis.setTimeout = schedule + globalThis.clearTimeout = clear + }, + } +} + +async function eventually(check: () => boolean): Promise { + const end = performance.now() + 2_000 + while (!check()) { + if (performance.now() >= end) throw new Error('Wait cadence observation exceeded its bound') + await Bun.sleep(2) + } +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Wait cadence with ${factory.name}`, () => { + for (const [pullInterval, expected] of [ + [0, 5_000], + [-3, 5_000], + [0.4, 1], + [2.9, 2], + [2_147_483_648, 2_147_483_647], + ] as const) { + it.serial( + `normalizes wait scheduling ${pullInterval} to ${expected} without rewriting config`, + async () => { + const instance = await factory.create() + const client = new Client({ + database: instance.adapter, + syncPattern: false, + pullInterval, + heartbeatInterval: 123_456, + waitReadTimeout: 789_012, + logger: 'silent', + }) + const abort = new AbortController() + let observation: ReturnType | undefined + let reads = 0 + const status = client.getJobStatus.bind(client) + client.getJobStatus = async (id) => { + reads++ + return status(id) + } + try { + await client.start() + observation = observeTimers() + expect(client.getConfig().pullInterval).toBe(pullInterval) + const wait = client.waitForJob(crypto.randomUUID(), { signal: abort.signal }) + await eventually(() => reads >= 1) + // Startup is complete; no worker or per-caller timeout is installed. + // The first new timer belongs to the new wait demand, not its read budget. + expect(observation.scheduled[0]?.delay).toBe(expected) + const pendingTimer = observation.scheduled + .filter((entry) => entry.delay === expected) + .at(-1)! + abort.abort() + expect(await wait).toBeNull() + expect(observation.cleared.has(pendingTimer.timer)).toBe(true) + } finally { + abort.abort() + observation?.restore() + await client.stop() + await instance.deleteDb() + } + }, + ) + } + + it.serial( + 'activates only for demand, waits one interval, and skips missed ticks without overlapping read batches', + async () => { + const instance = await factory.create() + const interval = 401 + const client = new Client({ + database: instance.adapter, + syncPattern: false, + pullInterval: interval, + heartbeatInterval: 123_456, + waitReadTimeout: 789_012, + logger: 'silent', + }) + const ids = Array.from({ length: 12 }, () => crypto.randomUUID()) + const aborts = ids.map(() => new AbortController()) + const release = Promise.withResolvers() + const releaseLongRead = Promise.withResolvers() + const status = client.getJobStatus.bind(client) + let entered = 0 + let completed = 0 + let active = 0 + let maximum = 0 + let observation: ReturnType | undefined + client.getJobStatus = async (id) => { + const call = ++entered + maximum = Math.max(maximum, ++active) + try { + if (call > ids.length) await release.promise + if (call >= 24) await releaseLongRead.promise + const result = await status(id) + completed++ + return result + } finally { + active-- + } + } + try { + await client.start() + observation = observeTimers() + const ticks = () => observation!.scheduled.filter((entry) => entry.delay === interval) + await Bun.sleep(30) + expect(ticks()).toHaveLength(0) + expect(entered).toBe(0) + const waits = ids.map((id, index) => + client.waitForJob(id, { signal: aborts[index]!.signal }), + ) + await eventually(() => completed === ids.length) + await Bun.sleep(30) + expect(entered).toBe(12) + expect(ticks()).toHaveLength(1) + + // Finite real elapsed stall, not a clock replacement. More than three + // intervals elapse, but only one ten-ID scan may run when JS resumes. + const until = performance.now() + interval * 3.2 + while (performance.now() < until) { + /* finite event-loop stall */ + } + await eventually(() => entered === 16) + await Bun.sleep(20) + expect(entered).toBe(16) + expect(active).toBe(4) + // The next real timer exists while the read batch is still held: the + // scheduler does not await that batch or replay missed timer callbacks. + expect(ticks()).toHaveLength(2) + release.resolve() + await eventually(() => completed === 22) + await Bun.sleep(20) + expect(entered).toBe(22) + expect(maximum).toBe(4) + expect(ticks()).toHaveLength(2) + + const pendingTimer = ticks().at(-1)!.timer + for (const abort of aborts.slice(0, -1)) abort.abort() + expect(observation.cleared.has(pendingTimer)).toBe(false) + aborts.at(-1)!.abort() + expect(await Promise.all(waits)).toEqual(ids.map(() => null)) + expect(observation.cleared.has(pendingTimer)).toBe(true) + await Bun.sleep(interval + 30) + expect(entered).toBe(22) + expect(ticks()).toHaveLength(2) + + // A new cohort reactivates the timer; public stop removes that demand. + const next = client.waitForJob(crypto.randomUUID()) + await eventually(() => completed === 23) + expect(ticks()).toHaveLength(3) + // Hold a periodic read across two more real ticks. Scans keep their + // cadence, but cannot start overlapping reads for this pending ID. + await eventually(() => entered === 24) + await eventually(() => ticks().length >= 6) + expect(entered).toBe(24) + expect(active).toBe(1) + const restartedTimer = ticks().at(-1)!.timer + const stopping = client.stop() + expect(await next).toBeNull() + expect(observation.cleared.has(restartedTimer)).toBe(true) + releaseLongRead.resolve() + await stopping + } finally { + release.resolve() + releaseLongRead.resolve() + for (const abort of aborts) abort.abort() + observation?.restore() + await client.stop() + await instance.deleteDb() + } + }, + 10_000, + ) + + it.serial( + 'keeps the worker delay fractional while normalizing only the wait timer', + async () => { + const instance = await factory.create() + const action = defineAction()({ + name: 'wait-cadence-worker', + handler: async () => {}, + }) + const client = new Client({ + database: instance.adapter, + actions: { action }, + syncPattern: 'pull', + recoverJobsOnStart: false, + pullInterval: 0.4, + heartbeatInterval: 123_456, + waitReadTimeout: 789_012, + logger: 'silent', + }) + const abort = new AbortController() + let observation: ReturnType | undefined + let fetches = 0 + const fetch = client.fetch.bind(client) + client.fetch = async (options) => { + fetches++ + return fetch(options) + } + try { + // Existing worker validation is not broadened by wait normalization. + for (const pullInterval of [NaN, Infinity, -Infinity]) { + expect(() => new Client({ database: instance.adapter, pullInterval })).toThrow() + } + observation = observeTimers() + await client.start() + await eventually(() => fetches >= 2) + expect(observation.scheduled.some((entry) => entry.delay === 0.4)).toBe(true) + expect(observation.scheduled.some((entry) => entry.delay === 1)).toBe(false) + const wait = client.waitForJob(crypto.randomUUID(), { signal: abort.signal }) + await eventually(() => observation!.scheduled.some((entry) => entry.delay === 1)) + expect(client.getConfig().pullInterval).toBe(0.4) + abort.abort() + expect(await wait).toBeNull() + } finally { + abort.abort() + observation?.restore() + await client.stop() + await instance.deleteDb() + } + }, + ) + }) +} diff --git a/packages/duron/test/wait-cancellation.test.ts b/packages/duron/test/wait-cancellation.test.ts new file mode 100644 index 0000000..83abad5 --- /dev/null +++ b/packages/duron/test/wait-cancellation.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'bun:test' + +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Wait cancellation with ${factory.name}`, () => { + for (const stage of ['status', 'detail'] as const) { + for (const boundary of ['timeout', 'abort', 'stop'] as const) { + it(`keeps ${boundary} reachable during ${stage} and omits obsolete next stages`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as Adapter & { + _notify: (event: string, data: unknown) => Promise + } + const client = new Client({ database: adapter, syncPattern: false, logger: 'silent' }) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const abort = new AbortController() + const notify = adapter._notify.bind(adapter) + adapter._notify = async (event, data) => { + if (event !== 'job-status-changed') await notify(event, data) + } + const status = adapter.getJobStatus.bind(adapter) + const detail = adapter.getJobById.bind(adapter) + let detailCalls = 0 + let settlements = 0 + adapter.getJobStatus = async (id) => { + const result = await status(id) + if (stage === 'status') { + entered.resolve() + await release.promise + } + return result + } + adapter.getJobById = async (id) => { + detailCalls++ + const result = await detail(id) + if (stage === 'detail') { + entered.resolve() + await release.promise + } + return result + } + let stopping: Promise | undefined + try { + await client.start() + const id = (await adapter.createJob({ + queue: 'cancellation', + groupKey: 'cancellation', + input: {}, + timeoutMs: 30000, + checksum: 'cancellation', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + await adapter.cancelJob({ jobId: id }) + const waiting = client + .waitForJob(id, { signal: abort.signal, timeout: boundary === 'timeout' ? 80 : 2000 }) + .then((result) => { + settlements++ + return result + }) + await entered.promise + if (boundary === 'abort') abort.abort() + if (boundary === 'stop') stopping = client.stop() + expect(await waiting).toBeNull() + expect(settlements).toBe(1) + release.resolve() + await (stopping ?? client.stop()) + expect(settlements).toBe(1) + expect(detailCalls).toBe(stage === 'detail' ? 1 : 0) + } finally { + abort.abort() + release.resolve() + await stopping + await client.stop() + await instance.deleteDb() + } + }) + } + } + }) +} diff --git a/packages/duron/test/wait-capacity.test.ts b/packages/duron/test/wait-capacity.test.ts new file mode 100644 index 0000000..e595c58 --- /dev/null +++ b/packages/duron/test/wait-capacity.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from 'bun:test' + +import { Client } from '../src/client.js' + +import { pgliteFactory, postgresFactory } from './adapters.js' + +async function eventually(check: () => boolean, timeout = 2_000): Promise { + const end = performance.now() + timeout + while (!check()) { + if (performance.now() >= end) + throw new Error('Wait capacity condition exceeded bounded observation') + await Bun.sleep(2) + } +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Wait capacity with ${factory.name}`, () => { + it('rotates more than ten established IDs without repeatedly selecting the head', async () => { + const instance = await factory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 200, + logger: 'silent', + }) + const ids = Array.from({ length: 23 }, () => crypto.randomUUID()) + const reads: string[] = [] + const status = adapter.getJobStatus.bind(adapter) + adapter.getJobStatus = async (id) => { + reads.push(id) + return status(id) + } + const abort = new AbortController() + try { + await client.start() + const waits = ids.map((id) => client.waitForJob(id, { signal: abort.signal })) + await eventually(() => reads.length >= 46) + expect(reads.slice(0, 23)).toEqual(ids) + expect(reads.slice(23, 46)).toEqual(ids) + abort.abort() + expect(await Promise.all(waits)).toEqual(ids.map(() => null)) + const afterAbort = reads.length + await Bun.sleep(250) + expect(reads).toHaveLength(afterAbort) + } finally { + abort.abort() + await client.stop() + await instance.deleteDb() + } + }) + + it('retains four actual expired chains, excludes queue time, and isolates replacement cohorts', async () => { + const instance = await factory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 1000, + waitReadTimeout: 60, + logger: 'silent', + }) + const ids: string[] = [] + const reads: string[] = [] + const gates = Array.from({ length: 4 }, () => Promise.withResolvers()) + const status = adapter.getJobStatus.bind(adapter) + const reports: unknown[] = [] + client.logger.error = (fields: unknown) => { + reports.push(fields) + } + let active = 0 + let maximum = 0 + let fifthSettled = false + try { + await client.start() + for (let index = 0; index < 5; index++) { + const id = (await adapter.createJob({ + queue: 'capacity', + groupKey: String(index), + input: {}, + timeoutMs: 30000, + checksum: 'capacity', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + await adapter.cancelJob({ jobId: id }) + ids.push(id) + } + // Fault-injected public override: each underlying SQL read completes, then + // its JavaScript reply is held. This is not a native execution-timeout test. + adapter.getJobStatus = async (id) => { + const call = reads.length + reads.push(id) + maximum = Math.max(maximum, ++active) + try { + const result = await status(id) + await gates[call]?.promise + return result + } finally { + active-- + } + } + const first = ids.slice(0, 4).map((id) => client.waitForJob(id, { timeout: 2000 })) + const fifth = client.waitForJob(ids[4]!, { timeout: 2000 }).then((result) => { + fifthSettled = true + return result + }) + await eventually(() => reads.length === 4) + expect(await Promise.all(first)).toEqual([null, null, null, null]) + expect(fifthSettled).toBe(false) + expect(reads).toEqual(ids.slice(0, 4)) + expect(reports).toHaveLength(4) + const replacement = client.waitForJob(ids[0]!, { timeout: 500 }) + await Bun.sleep(20) + expect(reads).toHaveLength(4) + gates[0]!.resolve() + expect(await fifth).toMatchObject({ id: ids[4], status: 'cancelled' }) + expect(await replacement).toMatchObject({ id: ids[0], status: 'cancelled' }) + expect(reads.slice(4)).toEqual([ids[4]!, ids[0]!]) + expect(maximum).toBe(4) + expect(active).toBe(3) + } finally { + for (const gate of gates) gate.resolve() + await client.stop() + await instance.deleteDb() + } + }) + }) +} diff --git a/packages/duron/test/wait-cohorts.test.ts b/packages/duron/test/wait-cohorts.test.ts new file mode 100644 index 0000000..91b54cd --- /dev/null +++ b/packages/duron/test/wait-cohorts.test.ts @@ -0,0 +1,327 @@ +import { describe, expect, it } from 'bun:test' + +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +const jobOptions = { + queue: 'cohort', + groupKey: 'cohort', + input: {}, + timeoutMs: 30000, + checksum: 'cohort', + concurrencyLimit: 1, + concurrencyStepLimit: 1, +} +async function eventually(check: () => boolean, timeout = 2_000): Promise { + const end = performance.now() + timeout + while (!check()) { + if (performance.now() >= end) throw new Error('Cohort condition exceeded bounded observation') + await Bun.sleep(2) + } +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Wait cohorts with ${factory.name}`, () => { + for (const late of ['success', 'error'] as const) { + it(`discards expired established detail and starts cooldown after actual late ${late}`, async () => { + const instance = await factory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 100, + waitReadTimeout: 60, + logger: 'silent', + }) + const status = adapter.getJobStatus.bind(adapter) + const detail = adapter.getJobById.bind(adapter) + const held = Promise.withResolvers() + const release = Promise.withResolvers() + const next = Promise.withResolvers() + const nextRelease = Promise.withResolvers() + const failure = new Error('injected late detail error') + const calls: number[] = [] + const reports: Array<{ fields: unknown; message: unknown }> = [] + client.logger.error = (fields: unknown, message?: unknown) => { + reports.push({ fields, message }) + } + let details = 0 + let settled = false + adapter.getJobStatus = async (id) => { + calls.push(performance.now()) + if (calls.length === 2) { + next.resolve() + await nextRelease.promise + } + return status(id) + } + adapter.getJobById = async (id) => { + const result = await detail(id) + if (++details === 1) { + held.resolve() + await release.promise + if (late === 'error') throw failure + } + return result + } + try { + await client.start() + const id = (await adapter.createJob(jobOptions))! + const first = client.waitForJob(id, { timeout: 2000 }).then((result) => { + settled = true + return result + }) + await eventually(() => calls.length === 1) + await Bun.sleep(10) + await adapter.cancelJob({ jobId: id }) + await held.promise + await eventually(() => + reports.some((report) => report.message === '[Duron] Wait read expired'), + ) + const second = client.waitForJob(id, { timeout: 2000 }) + await Bun.sleep(30) + expect(details).toBe(1) + expect(calls).toHaveLength(1) + expect(settled).toBe(false) + const releasedAt = performance.now() + release.resolve() + await next.promise + expect(calls[1]! - releasedAt).toBeGreaterThanOrEqual(90) + expect(settled).toBe(false) + nextRelease.resolve() + expect(await first).toMatchObject({ id, status: 'cancelled' }) + expect(await second).toMatchObject({ id, status: 'cancelled' }) + expect( + reports.filter((report) => report.message === '[Duron] Wait read expired'), + ).toHaveLength(1) + const failures = reports.filter((report) => report.message === '[Duron] Wait read failed') + expect(failures).toHaveLength(late === 'error' ? 1 : 0) + if (late === 'error') + expect(failures[0]!.fields).toMatchObject({ error: failure, late: true }) + } finally { + release.resolve() + nextRelease.resolve() + await client.stop() + await instance.deleteDb() + } + }) + } + + it('coalesces initial members but excludes late arrivals from a frozen terminal observation', async () => { + const instance = await factory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 500, + logger: 'silent', + }) + const detail = adapter.getJobById.bind(adapter) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const abort = new AbortController() + const lateAbort = new AbortController() + let detailCalls = 0 + let lateSettled = false + adapter.getJobById = async (id) => { + const snapshot = await detail(id) + if (++detailCalls === 1) { + entered.resolve() + await release.promise + } + return snapshot + } + try { + await client.start() + const id = (await adapter.createJob(jobOptions))! + await adapter.fetch({ batch: 1 }) + const step = await adapter.createOrRecoverJobStep({ + jobId: id, + name: 'target', + timeoutMs: 30000, + retriesLimit: 1, + }) + await adapter.completeJobStep({ stepId: step!.id, output: {} }) + await adapter.completeJob({ jobId: id, output: { snapshot: true } }) + const cancelled = client.waitForJob(id, { signal: abort.signal }) + const sibling = client.waitForJob(id, { timeout: 2000 }) + await entered.promise + abort.abort() + expect(await cancelled).toBeNull() + const late = client.waitForJob(id, { signal: lateAbort.signal }).then((result) => { + lateSettled = true + return result + }) + await adapter.timeTravelJob({ jobId: id, stepId: step!.id }) + for (let index = 0; index < 8; index++) + adapter.emit('job-status-changed', { + jobId: id, + status: 'completed', + clientId: adapter.id, + }) + expect(detailCalls).toBe(1) + release.resolve() + expect(await sibling).toMatchObject({ id, status: 'completed', output: { snapshot: true } }) + await Bun.sleep(50) + expect(lateSettled).toBe(false) + // One coalesced direct-detail follow-up after the new initial status check. + expect(detailCalls).toBe(2) + lateAbort.abort() + expect(await late).toBeNull() + } finally { + abort.abort() + lateAbort.abort() + release.resolve() + await client.stop() + await instance.deleteDb() + } + }) + + for (const path of ['initial', 'hint'] as const) { + it(`validates ${path} detail after real same-ID time travel`, async () => { + const instance = await factory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 30, + logger: 'silent', + }) + const detail = adapter.getJobById.bind(adapter) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const abort = new AbortController() + let settled = false + let detailCalls = 0 + adapter.getJobById = async (id) => { + if (++detailCalls === 1) { + entered.resolve() + await release.promise + } + return detail(id) + } + try { + await client.start() + const id = (await adapter.createJob(jobOptions))! + await adapter.fetch({ batch: 1 }) + const step = await adapter.createOrRecoverJobStep({ + jobId: id, + name: 'target', + timeoutMs: 30000, + retriesLimit: 1, + }) + expect(await adapter.completeJobStep({ stepId: step!.id, output: {} })).toBe(true) + let waiting: Promise + if (path === 'initial') { + await adapter.completeJob({ jobId: id, output: { old: true } }) + waiting = client.waitForJob(id, { signal: abort.signal }).then((result) => { + settled = true + return result + }) + } else { + waiting = client.waitForJob(id, { signal: abort.signal }).then((result) => { + settled = true + return result + }) + await Bun.sleep(10) + await adapter.completeJob({ jobId: id, output: { old: true } }) + } + await entered.promise + expect(await adapter.timeTravelJob({ jobId: id, stepId: step!.id })).toBe(true) + release.resolve() + await Bun.sleep(60) + expect(await detail(id)).toMatchObject({ status: 'created' }) + expect(settled).toBe(false) + abort.abort() + expect(await waiting).toBeNull() + } finally { + abort.abort() + release.resolve() + await client.stop() + await instance.deleteDb() + } + }) + } + + it('nulls only initial members on a shared failure and prevents hint/new-member cooldown bypass', async () => { + const instance = await factory.create() + const adapter = instance.adapter as Adapter & { + _notify: (event: string, data: unknown) => Promise + } + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 100, + logger: 'silent', + }) + const status = adapter.getJobStatus.bind(adapter) + const notify = adapter._notify.bind(adapter) + adapter._notify = async (event, data) => { + if (event !== 'job-status-changed') await notify(event, data) + } + const failure = new Error('injected shared status failure') + const released = Promise.withResolvers() + const calls: number[] = [] + const reports: unknown[] = [] + client.logger.error = (fields: unknown) => { + reports.push(fields) + } + let establishedSettled = false + adapter.getJobStatus = async (id) => { + calls.push(performance.now()) + if (calls.length === 2) { + await released.promise + throw failure + } + return status(id) + } + try { + await client.start() + const id = (await adapter.createJob(jobOptions))! + const established = client.waitForJob(id, { timeout: 2000 }).then((result) => { + establishedSettled = true + return result + }) + await eventually(() => calls.length === 1) + await Bun.sleep(10) + const initial = client.waitForJob(id, { timeout: 2000 }) + await eventually(() => calls.length === 2) + released.resolve() + expect(await initial).toBeNull() + expect(establishedSettled).toBe(false) + expect(reports).toEqual([ + { + error: failure, + jobId: id, + trigger: 'initial', + stage: 'status', + affected: { initial: 1, established: 1 }, + late: false, + }, + ]) + const failedAt = performance.now() + const later = client.waitForJob(id, { timeout: 2000 }) + for (let index = 0; index < 5; index++) + adapter.emit('job-status-changed', { + jobId: id, + status: 'cancelled', + clientId: adapter.id, + }) + await adapter.cancelJob({ jobId: id }) + await Bun.sleep(30) + expect(calls).toHaveLength(2) + expect(await established).toMatchObject({ id, status: 'cancelled' }) + expect(await later).toMatchObject({ id, status: 'cancelled' }) + expect(calls[2]! - failedAt).toBeGreaterThanOrEqual(90) + } finally { + released.resolve() + await client.stop() + await instance.deleteDb() + } + }) + }) +} diff --git a/packages/duron/test/wait-context.test.ts b/packages/duron/test/wait-context.test.ts new file mode 100644 index 0000000..4d7c59a --- /dev/null +++ b/packages/duron/test/wait-context.test.ts @@ -0,0 +1,271 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { getPostgresConnection } from './docker.js' +import { PruneRelay } from './prune-relay.js' + +async function eventually(check: () => boolean | Promise): Promise { + const end = performance.now() + 2_000 + while (!(await check())) { + if (performance.now() >= end) + throw new Error('Wait context condition exceeded bounded observation') + await Bun.sleep(2) + } +} + +async function fixture(timeout: number) { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const url = new URL(CONNECTION_URL) + const relay = new PruneRelay() + const adapter = new PostgresAdapter({ + connection: { + host: '127.0.0.1', + port: relay.port, + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + connection: { statement_timeout: 2000 }, + }, + }) + const client = new Client({ + database: adapter, + syncPattern: false, + waitReadTimeout: timeout, + logger: 'silent', + }) + const driver = (adapter as unknown as { db: { $client: postgres.Sql } }).db.$client + const admin = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 2000 } }) + const queries: Array<{ query: string; parameters: unknown[] }> = [] + const reports: Array<{ fields: unknown; message: unknown }> = [] + client.logger.trace = (fields: unknown) => { + queries.push(fields as (typeof queries)[number]) + } + client.logger.error = (fields: unknown, message?: unknown) => { + reports.push({ fields, message }) + } + const close = async () => { + relay.flush() + await client.stop() + await relay.close() + expect(relay.sockets).toBe(0) + expect(relay.errors).toEqual([]) + await eventually( + async () => + Number( + ( + await admin`SELECT count(*) AS count FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid()` + )[0]!['count'], + ) === 0, + ) + await admin.end({ timeout: 5 }) + await deleteDb() + } + try { + await client.start() + const pid = Number((await driver`SELECT pg_backend_pid() AS pid`)[0]!['pid']) + return { adapter, client, driver, admin, relay, pid, queries, reports, close } + } catch (error) { + await close() + throw error + } +} + +const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip +suite('Native wait transaction context', () => { + for (const boundary of ['timeout', 'abort'] as const) { + it(`keeps caller ${boundary} reachable while native COMMIT cleanup is pending`, async () => { + const f = await fixture(2000) + const abort = new AbortController() + let withholding = false + let stopped = false + let stopping: Promise | undefined + try { + const id = (await f.adapter.createJob({ + queue: 'cleanup-cancel', + groupKey: 'cleanup-cancel', + input: {}, + timeoutMs: 30000, + checksum: 'cleanup-cancel', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + await f.adapter.cancelJob({ jobId: id }) + f.queries.length = 0 + f.relay.hold = (tag, connection) => { + if (connection.pid !== f.pid) return false + if (tag === 'C' && f.queries.at(-1)?.query.trim() === 'commit') withholding = true + return withholding + } + const waiting = f.client.waitForJob(id, { + timeout: boundary === 'timeout' ? 100 : 1000, + signal: abort.signal, + }) + await eventually(() => f.relay.held.length > 0) + if (boundary === 'abort') abort.abort() + expect(await waiting).toBeNull() + expect( + f.reports.filter(({ message }) => message === '[Duron] Wait read expired'), + ).toHaveLength(0) + stopping = f.client.stop().then((result) => { + stopped = true + return result + }) + await Bun.sleep(20) + expect(stopped).toBe(false) + f.relay.flush() + expect(await stopping).toBe(true) + } finally { + abort.abort() + f.relay.flush() + await stopping + await f.close() + } + }) + } + + it('rechecks elapsed time at SQL issuance when JavaScript stalls after lookup preparation', async () => { + const f = await fixture(80) + const probe = f.adapter as unknown as { _assertSql: () => void } + const assertSql = probe._assertSql.bind(f.adapter) + let stalled = false + probe._assertSql = () => { + if (!stalled && f.queries.at(-1)?.query.includes('set_config')) { + stalled = true + // Labelled finite synchronous fault after preparation, before issuance. + // No global clock mutation; the observer timer cannot run in this gap. + const end = performance.now() + 100 + while (performance.now() < end) { + /* finite controlled JS stall */ + } + } + assertSql() + } + try { + f.queries.length = 0 + expect(await f.client.waitForJob(crypto.randomUUID(), { timeout: 1000 })).toBeNull() + await f.client.stop() + expect(stalled).toBe(true) + expect(f.queries.some(({ query }) => query.includes('"jobs_active"'))).toBe(false) + } finally { + await f.close() + } + }) + + it('does not start a lookup after a setup reply consumes the observer budget', async () => { + const f = await fixture(80) + let withholding = false + try { + f.queries.length = 0 + f.relay.hold = (tag, connection) => { + if (connection.pid !== f.pid) return false + if (tag === 'D' && f.queries.at(-1)?.query.includes('set_config')) withholding = true + return withholding + } + const waiting = f.client.waitForJob(crypto.randomUUID(), { timeout: 1000 }) + await eventually(() => f.relay.held.length > 0) + expect(await waiting).toBeNull() + f.relay.flush() + await f.client.stop() + expect(f.queries.some(({ query }) => query.includes('"jobs_active"'))).toBe(false) + expect( + f.reports.filter(({ message }) => message === '[Duron] Wait read expired'), + ).toHaveLength(1) + } finally { + await f.close() + } + }) + + it('shares the remaining budget across status/detail and active/archive lookups', async () => { + const f = await fixture(350) + let withholding = false + try { + const id = (await f.adapter.createJob({ + queue: 'context', + groupKey: 'context', + input: {}, + timeoutMs: 30000, + checksum: 'context', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + await f.adapter.fetch({ batch: 1 }) + await f.adapter.completeJob({ jobId: id, output: { saved: true } }) + f.queries.length = 0 + f.relay.hold = (tag, connection) => { + if (connection.pid !== f.pid) return false + const query = f.queries.at(-1)?.query ?? '' + if (tag === 'D' && query.startsWith('select "status"') && query.includes('jobs_archive')) + withholding = true + return withholding + } + const waiting = f.client.waitForJob(id, { timeout: 2000 }) + await eventually(() => f.relay.held.length > 0) + await Bun.sleep(100) + f.relay.flush() + expect(await waiting).toMatchObject({ id, status: 'completed', output: { saved: true } }) + const budgets = f.queries + .filter(({ query }) => query.includes('set_config')) + .map(({ parameters }) => Number(parameters[0])) + expect(budgets).toHaveLength(4) + expect(budgets.every((value) => value > 0 && value <= 350)).toBe(true) + expect(budgets[1]! - budgets[2]!).toBeGreaterThanOrEqual(90) + expect((await f.driver`SHOW statement_timeout`)[0]!['statement_timeout']).toBe('2s') + } finally { + await f.close() + } + }) + + it('keeps successful detail pending through COMMIT acknowledgement and reports cleanup expiry', async () => { + const f = await fixture(80) + let withholding = false + let stopped = false + let stopping: Promise | undefined + try { + const id = (await f.adapter.createJob({ + queue: 'commit', + groupKey: 'commit', + input: {}, + timeoutMs: 30000, + checksum: 'commit', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + await f.adapter.cancelJob({ jobId: id }) + f.queries.length = 0 + f.relay.hold = (tag, connection) => { + if (connection.pid !== f.pid) return false + if (tag === 'C' && f.queries.at(-1)?.query.trim() === 'commit') withholding = true + return withholding + } + const waiting = f.client.waitForJob(id, { timeout: 1000 }) + await eventually(() => f.relay.held.length > 0) + expect(await waiting).toBeNull() + const expiry = f.reports.filter(({ message }) => message === '[Duron] Wait read expired') + expect(expiry).toHaveLength(1) + expect(expiry[0]!.fields).toMatchObject({ stage: 'transaction cleanup', unresolved: true }) + stopping = f.client.stop().then((result) => { + stopped = true + return result + }) + await Bun.sleep(20) + expect(stopped).toBe(false) + f.relay.flush() + expect(await stopping).toBe(true) + expect( + f.reports.filter(({ message }) => message === '[Duron] Wait read failed'), + ).toHaveLength(0) + } finally { + f.relay.flush() + await stopping + await f.close() + } + }) +}) diff --git a/packages/duron/test/wait-lifecycle.test.ts b/packages/duron/test/wait-lifecycle.test.ts new file mode 100644 index 0000000..6ce8346 --- /dev/null +++ b/packages/duron/test/wait-lifecycle.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'bun:test' + +import { Client } from '../src/client.js' + +import { pgliteFactory, postgresFactory } from './adapters.js' + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Wait lifecycle with ${factory.name}`, () => { + for (const waitReadTimeout of [40, 15_000]) { + it(`retains the shared five-second drain with a ${waitReadTimeout}ms read budget`, async () => { + const instance = await factory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + waitReadTimeout, + logger: 'silent', + }) + const status = adapter.getJobStatus.bind(adapter) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const done = Promise.withResolvers() + let details = 0 + adapter.getJobStatus = async (id) => { + const result = await status(id) + entered.resolve() + await release.promise + done.resolve() + return result + } + const detail = adapter.getJobById.bind(adapter) + adapter.getJobById = async (id) => { + details++ + return detail(id) + } + let stopping: Promise | undefined + try { + await client.start() + const waiting = client.waitForJob(crypto.randomUUID()) + await entered.promise + const started = performance.now() + stopping = client.stop().catch((error: unknown) => error) + expect(await waiting).toBeNull() + const error = await stopping + expect(error).toBeInstanceOf(Error) + const messages = + error instanceof AggregateError ? error.errors.map(String).join(' ') : String(error) + expect(messages).toContain('admitted-work drain exceeded five seconds') + expect(performance.now() - started).toBeGreaterThanOrEqual(4_900) + expect(performance.now() - started).toBeLessThan(7_000) + release.resolve() + await done.promise + await Bun.sleep(10) + expect(details).toBe(0) + await expect(client.waitForJob(crypto.randomUUID())).rejects.toThrow('not accepting work') + } finally { + release.resolve() + await stopping + await client.stop().catch(() => undefined) // Incomplete liveness remains an explicit expected obligation. + await instance.deleteDb() + } + }, 20_000) + } + }) +} diff --git a/packages/duron/test/wait-native.test.ts b/packages/duron/test/wait-native.test.ts new file mode 100644 index 0000000..70cde2c --- /dev/null +++ b/packages/duron/test/wait-native.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { getPostgresConnection } from './docker.js' + +async function eventually(check: () => boolean | Promise, timeout = 2_000): Promise { + const end = performance.now() + timeout + while (!(await check())) { + if (performance.now() >= end) + throw new Error('Native wait condition exceeded bounded observation') + await Bun.sleep(5) + } +} + +const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip +suite('Native PostgreSQL wait deadlines', () => { + it('interrupts real finite SQL execution rather than only observing elapsed time (owned seeded view)', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const adapter = new PostgresAdapter({ connection: CONNECTION_URL }) + const client = new Client({ + database: adapter, + syncPattern: false, + waitReadTimeout: 100, + logger: 'silent', + }) + const admin = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 2000 } }) + const errors: unknown[] = [] + client.logger.error = (error: unknown) => { + errors.push(error) + } + try { + await client.start() + const id = (await adapter.createJob({ + queue: 'execution', + groupKey: 'execution', + input: {}, + timeoutMs: 30000, + checksum: 'execution', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + // SQL-only fault fixture in this fresh owned DB. The volatile subquery adds + // finite server execution to the real built-in lookup without overriding it. + await admin`ALTER TABLE duron.jobs_active RENAME TO wait_execution_jobs` + await admin`CREATE VIEW duron.jobs_active AS SELECT jobs.* FROM duron.wait_execution_jobs jobs + CROSS JOIN (SELECT pg_sleep(0.4)) execution_delay` + expect(await client.waitForJob(id, { timeout: 1000 })).toBeNull() + await eventually(() => JSON.stringify(errors).includes('57014')) + expect(JSON.stringify(errors)).toContain('statement timeout') + await client.stop() + const remaining = + await admin`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid()` + expect(remaining[0]!['count']).toBe(0) + } finally { + await client.stop() + await admin.end({ timeout: 5 }) + await deleteDb() + } + }, 30_000) + + for (const seam of [ + 'Client.start', + 'Client.getJobStatus', + 'Adapter.getJobStatus', + 'Adapter._getJobStatus', + ] as const) { + it(`preserves ${seam} overrides without pinning a transaction around their arbitrary SQL`, async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const adapter = new PostgresAdapter({ connection: CONNECTION_URL }) + const client = new Client({ database: adapter, syncPattern: false, logger: 'silent' }) + const queries: string[] = [] + client.logger.trace = (fields: unknown) => { + queries.push((fields as { query: string }).query) + } + let starts = 0 + try { + await client.start() + queries.length = 0 + if (seam === 'Client.start') { + const start = client.start.bind(client) + client.start = async () => { + starts++ + return start() + } + } else if (seam === 'Client.getJobStatus') { + const read = client.getJobStatus.bind(client) + client.getJobStatus = async (id) => { + starts++ + return read(id) + } + } else if (seam === 'Adapter.getJobStatus') { + const read = adapter.getJobStatus.bind(adapter) + adapter.getJobStatus = async (id) => { + starts++ + return read(id) + } + } else { + const probe = adapter as unknown as { _getJobStatus: typeof adapter.getJobStatus } + const read = probe._getJobStatus.bind(adapter) + probe._getJobStatus = async (id) => { + starts++ + return read(id) + } + } + expect(await client.waitForJob(crypto.randomUUID(), { timeout: 40 })).toBeNull() + expect(starts).toBeGreaterThan(0) + expect(queries.filter((query) => query.trim().toLowerCase() === 'begin')).toEqual([]) + } finally { + await client.stop() + await deleteDb() + } + }) + } + + it('bounds a real table-lock read and restores inherited timeout after rollback', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const url = new URL(CONNECTION_URL) + const adapter = new PostgresAdapter({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + connection: { statement_timeout: 2000 }, + }, + }) + const client = new Client({ + database: adapter, + syncPattern: false, + waitReadTimeout: 80, + pullInterval: 20, + logger: 'silent', + }) + const admin = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 2000 } }) + const blocker = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 2000 } }) + const locked = Promise.withResolvers() + const release = Promise.withResolvers() + const errors: unknown[] = [] + client.logger.error = (error: unknown) => { + errors.push(error) + } + let holding: Promise | undefined + try { + await client.start() + holding = blocker.begin(async (tx) => { + await tx`LOCK TABLE duron.jobs_active IN ACCESS EXCLUSIVE MODE` + locked.resolve() + await release.promise + }) + await locked.promise + expect(await client.waitForJob(crypto.randomUUID(), { timeout: 500 })).toBeNull() + // Native supplement: server timeout must actually end the blocked SELECT, + // not merely settle the public observer while retaining a blocked backend. + await eventually(async () => { + const rows = await admin`SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock'` + return rows[0]!['count'] === 0 + }, 500) + expect(errors.some((entry) => JSON.stringify(entry).includes('57014'))).toBe(true) + release.resolve() + await holding + const driver = (adapter as unknown as { db: { $client: postgres.Sql } }).db.$client + expect( + (await driver`SELECT current_setting('statement_timeout') AS timeout`)[0]!['timeout'], + ).toBe('2s') + expect(await client.getJobStatus(crypto.randomUUID())).toBeNull() + } finally { + release.resolve() + await holding?.catch(() => undefined) + await client.stop() + await blocker.end({ timeout: 5 }) + const remaining = await admin`SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid()` + expect(remaining[0]!['count']).toBe(0) + await admin.end({ timeout: 5 }) + await deleteDb() + } + }, 30_000) +}) diff --git a/packages/duron/test/wait-options.test.ts b/packages/duron/test/wait-options.test.ts new file mode 100644 index 0000000..9be234f --- /dev/null +++ b/packages/duron/test/wait-options.test.ts @@ -0,0 +1,23 @@ +import { expect, it } from 'bun:test' + +import { Client } from '../src/client.js' + +import { pgliteFactory } from './adapters.js' + +it('rejects invalid waitReadTimeout values without coercion or a disable value', async () => { + const { adapter } = await pgliteFactory.create() + adapter.setId('wait-options') + try { + expect(new Client({ database: adapter }).getConfig().waitReadTimeout).toBe(5000) + for (const waitReadTimeout of [1, 5000, 2_147_483_647]) { + expect(new Client({ database: adapter, waitReadTimeout }).getConfig().waitReadTimeout).toBe( + waitReadTimeout, + ) + } + for (const waitReadTimeout of [0, -1, 0.5, 2_147_483_648, NaN, Infinity, '5000', null, false]) { + expect(() => new Client({ database: adapter, waitReadTimeout } as never)).toThrow() + } + } finally { + await adapter.stop() + } +}) diff --git a/packages/duron/test/wait-pglite.test.ts b/packages/duron/test/wait-pglite.test.ts new file mode 100644 index 0000000..6590d83 --- /dev/null +++ b/packages/duron/test/wait-pglite.test.ts @@ -0,0 +1,88 @@ +import { expect, it } from 'bun:test' + +import type { PGlite } from '@electric-sql/pglite' + +import { Client } from '../src/client.js' + +import { pgliteFactory } from './adapters.js' + +it('observes a real PGLite engine-queue wait without issuing the archive continuation after expiry', async () => { + const instance = await pgliteFactory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + waitReadTimeout: 40, + logger: 'silent', + }) + const engine = (adapter as unknown as { db: { $client: PGlite } }).db.$client + const query = engine.query.bind(engine) + const queries: string[] = [] + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + let holding: Promise | undefined + try { + await client.start() + holding = engine.transaction(async (tx) => { + await tx.query('SELECT 1') + entered.resolve() + await release.promise + }) + await entered.promise + engine.query = ((...args: Parameters) => { + queries.push(args[0]) + return query(...args) + }) as PGlite['query'] + expect(await client.waitForJob(crypto.randomUUID(), { timeout: 500 })).toBeNull() + expect(queries.filter((text) => text.includes('jobs_active'))).toHaveLength(1) + release.resolve() + await holding + await client.stop() + expect(queries.filter((text) => text.includes('jobs_archive'))).toHaveLength(0) + expect(engine.closed).toBe(true) + } finally { + release.resolve() + await holding?.catch(() => undefined) + await client.stop() + } +}) + +it('discards an overdue PGLite result even when synchronous WASM delays the observer timer', async () => { + const instance = await pgliteFactory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + waitReadTimeout: 30, + logger: 'silent', + }) + const engine = (adapter as unknown as { db: { $client: PGlite } }).db.$client + const detail = adapter.getJobById.bind(adapter) + let returned = false + // Labelled custom public override with real finite SQL execution. This is not + // PostgreSQL cancellation parity or a PGLite production isolation guarantee. + adapter.getJobById = async (id) => { + const result = await detail(id) + await engine.query('SELECT pg_sleep(0.08)') + returned = true + return result + } + try { + await client.start() + const id = (await adapter.createJob({ + queue: 'pglite-wait', + groupKey: 'pglite-wait', + input: {}, + timeoutMs: 30000, + checksum: 'pglite-wait', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + await adapter.cancelJob({ jobId: id }) + expect(await client.waitForJob(id, { timeout: 500 })).toBeNull() + expect(returned).toBe(true) + } finally { + await client.stop() + expect(engine.closed).toBe(true) + } +}) diff --git a/packages/duron/test/wait-pool.test.ts b/packages/duron/test/wait-pool.test.ts new file mode 100644 index 0000000..3f73875 --- /dev/null +++ b/packages/duron/test/wait-pool.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { getPostgresConnection } from './docker.js' + +const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip +suite('Native wait pool and inherited settings', () => { + for (const scenario of ['pool queue', 'stricter inherited timeout'] as const) { + it( + scenario, + async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const url = new URL(CONNECTION_URL) + const adapter = new PostgresAdapter({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + connection: { statement_timeout: 2000 }, + }, + }) + const client = new Client({ + database: adapter, + syncPattern: false, + waitReadTimeout: scenario === 'pool queue' ? 60 : 300, + logger: 'silent', + }) + const driver = (adapter as unknown as { db: { $client: postgres.Sql } }).db.$client + const admin = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 2000 } }) + const locked = Promise.withResolvers() + const release = Promise.withResolvers() + const queries: string[] = [] + const reports: Array<{ fields: unknown; message: unknown }> = [] + client.logger.trace = (fields: unknown) => { + queries.push((fields as { query: string }).query) + } + client.logger.error = (fields: unknown, message?: unknown) => { + reports.push({ fields, message }) + } + let holding: Promise | undefined + try { + await client.start() + if (scenario === 'stricter inherited timeout') await driver`SET statement_timeout = 30` + const holder = scenario === 'pool queue' ? driver : admin + holding = holder.begin(async (tx) => { + if (scenario === 'stricter inherited timeout') + await tx`LOCK TABLE duron.jobs_active IN ACCESS EXCLUSIVE MODE` + else await tx`SELECT 1` + locked.resolve() + await release.promise + }) + await locked.promise + queries.length = 0 + expect(await client.waitForJob(crypto.randomUUID(), { timeout: 1000 })).toBeNull() + if (scenario === 'pool queue') { + expect(queries).toEqual([]) + expect( + reports.filter((report) => report.message === '[Duron] Wait read expired'), + ).toHaveLength(1) + } else { + expect( + reports.filter((report) => report.message === '[Duron] Wait read expired'), + ).toHaveLength(0) + expect( + reports.filter((report) => report.message === '[Duron] Wait read failed'), + ).toHaveLength(1) + expect(JSON.stringify(reports)).toContain('57014') + expect((await driver`SHOW statement_timeout`)[0]!['statement_timeout']).toBe('30ms') + } + release.resolve() + await holding + await client.stop() + if (scenario === 'pool queue') { + // The already-queued BEGIN may execute late. No lookup may follow it. + expect(queries.some((query) => query.includes('"jobs_active"'))).toBe(false) + expect(queries.some((query) => query.trim() === 'rollback')).toBe(true) + } + } finally { + release.resolve() + await holding?.catch(() => undefined) + await client.stop() + const remaining = + await admin`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid()` + expect(remaining[0]!['count']).toBe(0) + await admin.end({ timeout: 5 }) + await deleteDb() + } + }, + 30_000, + ) + } +}) diff --git a/packages/duron/test/wait-reconciliation.test.ts b/packages/duron/test/wait-reconciliation.test.ts new file mode 100644 index 0000000..8c2b27b --- /dev/null +++ b/packages/duron/test/wait-reconciliation.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it, spyOn } from 'bun:test' + +import { type SQL, sql } from 'drizzle-orm' + +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +const jobOptions = { + queue: 'wait-test', + groupKey: 'wait-test', + input: { requested: true }, + timeoutMs: 30_000, + checksum: 'wait-test', + concurrencyLimit: 1, + concurrencyStepLimit: 1, +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Wait reconciliation with ${factory.name}`, () => { + it('discovers real recovery-produced failure without an event or worker fetch (seeded expiry)', async () => { + const instance = await factory.create() + const adapter = instance.adapter as Adapter & { + db: { execute: (query: SQL) => Promise } + } + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 20, + logger: 'silent', + }) + const initial = Promise.withResolvers() + const status = adapter.getJobStatus.bind(adapter) + adapter.getJobStatus = async (id) => { + const result = await status(id) + initial.resolve() + return result + } + try { + await client.start() + const id = (await adapter.createJob(jobOptions))! + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([id]) + const fetch = spyOn(adapter, 'fetch') + const events: unknown[] = [] + adapter.on('job-status-changed', (event) => events.push(event)) + const waiting = client.waitForJob(id, { timeout: 1000 }) + await initial.promise + // Seed only ownership/expiry; actual recovery executes its native archival path. + await adapter.db.execute(sql`UPDATE duron.jobs_active + SET client_id = 'wait-dead-owner', expires_at = now() - interval '1 minute' + WHERE id = ${id}`) + expect(await adapter.recoverJobs({ checksums: ['wait-test'] })).toBe(1) + expect(await waiting).toMatchObject({ + id, + status: 'failed', + error: { message: expect.any(String) }, + }) + expect(events).toEqual([]) + expect(fetch).not.toHaveBeenCalled() + fetch.mockRestore() + } finally { + await client.stop() + await instance.deleteDb() + } + }) + + for (const terminal of ['completed', 'failed', 'cancelled'] as const) { + it(`discovers retained ${terminal} detail after hint loss without actions or worker fetch`, async () => { + const instance = await factory.create() + const adapter = instance.adapter as Adapter & { + _notify: (event: string, payload: unknown) => Promise + } + const client = new Client({ + database: adapter, + syncPattern: terminal === 'completed' ? 'hybrid' : false, + pullInterval: 20, + logger: 'silent', + }) + const initial = Promise.withResolvers() + const status = adapter.getJobStatus.bind(adapter) + adapter.getJobStatus = async (id) => { + const result = await status(id) + initial.resolve() + return result + } + const fetch = spyOn(adapter, 'fetch') + // Injected loss at the notification boundary; mutation and reads use real SQL. + const notify = adapter._notify.bind(adapter) + adapter._notify = async (event, payload) => { + if (event !== 'job-status-changed') await notify(event, payload) + } + try { + await client.start() + const id = (await adapter.createJob(jobOptions))! + // Explicit fixture claim, before observing the actionless Client's behavior. + await adapter.fetch({ batch: 1 }) + fetch.mockClear() + const waiting = client.waitForJob(id, { timeout: 500 }) + await initial.promise + expect( + terminal === 'completed' + ? await adapter.completeJob({ jobId: id, output: { saved: true } }) + : terminal === 'failed' + ? await adapter.failJob({ jobId: id, error: { message: 'retained failure' } }) + : await adapter.cancelJob({ jobId: id }), + ).toBe(true) + expect(await waiting).toEqual({ + id, + actionName: 'wait-test', + groupKey: 'wait-test', + description: null, + status: terminal, + input: { requested: true }, + output: terminal === 'completed' ? { saved: true } : null, + error: terminal === 'failed' ? { message: 'retained failure' } : null, + }) + expect(fetch).not.toHaveBeenCalled() + } finally { + await client.stop() + fetch.mockRestore() + await instance.deleteDb() + } + }) + } + }) +} diff --git a/packages/duron/test/wait-results.test.ts b/packages/duron/test/wait-results.test.ts new file mode 100644 index 0000000..e9f8a75 --- /dev/null +++ b/packages/duron/test/wait-results.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'bun:test' + +import { Client } from '../src/client.js' + +import { pgliteFactory, postgresFactory } from './adapters.js' + +const jobOptions = { + queue: 'wait-results', + groupKey: 'wait-results', + input: {}, + timeoutMs: 30000, + checksum: 'wait-results', + concurrencyLimit: 1, + concurrencyStepLimit: 1, +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Wait result rules with ${factory.name}`, () => { + for (const fault of [ + 'initial status rejection', + 'initial detail rejection', + 'missing detail', + ] as const) { + it(`returns null on ${fault} without leaking registration`, async () => { + const instance = await factory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 20, + logger: 'silent', + }) + const failure = new Error(fault) + let calls = 0 + try { + await client.start() + const id = (await adapter.createJob(jobOptions))! + await adapter.cancelJob({ jobId: id }) + if (fault === 'initial status rejection') + adapter.getJobStatus = async () => { + calls++ + throw failure + } + else + adapter.getJobById = async () => { + calls++ + if (fault === 'initial detail rejection') throw failure + return null + } + expect(await client.waitForJob(id, { timeout: 1000 })).toBeNull() + const settledCalls = calls + await Bun.sleep(50) + expect(calls).toBe(settledCalls) + expect(calls).toBe(1) + } finally { + await client.stop() + await instance.deleteDb() + } + }) + } + + it('retries a failed hint detail through periodic status without another hint', async () => { + const instance = await factory.create() + const adapter = instance.adapter + const client = new Client({ + database: adapter, + syncPattern: false, + pullInterval: 30, + logger: 'silent', + }) + const status = adapter.getJobStatus.bind(adapter) + const detail = adapter.getJobById.bind(adapter) + const initial = Promise.withResolvers() + let details = 0 + adapter.getJobStatus = async (id) => { + const value = await status(id) + initial.resolve() + return value + } + adapter.getJobById = async (id) => { + if (++details === 1) throw new Error('injected hint detail failure') + return detail(id) + } + try { + await client.start() + const id = (await adapter.createJob(jobOptions))! + const waiting = client.waitForJob(id, { timeout: 1000 }) + await initial.promise + await Bun.sleep(5) + expect(await adapter.cancelJob({ jobId: id })).toBe(true) + expect(await waiting).toMatchObject({ id, status: 'cancelled' }) + expect(details).toBe(2) + } finally { + await client.stop() + await instance.deleteDb() + } + }) + }) +} diff --git a/packages/duron/test/wait-transport.test.ts b/packages/duron/test/wait-transport.test.ts new file mode 100644 index 0000000..200bfe5 --- /dev/null +++ b/packages/duron/test/wait-transport.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { getPostgresConnection } from './docker.js' +import { PruneRelay } from './prune-relay.js' + +async function eventually(check: () => boolean | Promise): Promise { + const end = performance.now() + 2_000 + while (!(await check())) { + if (performance.now() >= end) + throw new Error('Wait transport condition exceeded bounded observation') + await Bun.sleep(5) + } +} + +const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip +suite('Owned native wait transport controls', () => { + for (const phase of ['read error response', 'rollback response'] as const) { + it(`retains actual capacity and drain accounting through withheld ${phase}`, async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + // Reuse the existing diagnostic relay; only this new database's owned + // adapter traffic traverses it. No cancellation packet or native cut. + const relay = new PruneRelay() + const url = new URL(CONNECTION_URL) + const adapter = new PostgresAdapter({ + connection: { + host: '127.0.0.1', + port: relay.port, + database: url.pathname.slice(1), + user: url.username, + password: url.password, + max: 1, + connection: { statement_timeout: 2000 }, + }, + }) + const client = new Client({ + database: adapter, + syncPattern: false, + waitReadTimeout: 150, + logger: 'silent', + }) + const driver = (adapter as unknown as { db: { $client: postgres.Sql } }).db.$client + const admin = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 2000 } }) + const blocker = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 2000 } }) + const locked = Promise.withResolvers() + const release = Promise.withResolvers() + const reports: Array<{ fields: unknown; message: unknown }> = [] + client.logger.error = (fields: unknown, message?: unknown) => { + reports.push({ fields, message }) + } + let holding: Promise | undefined + let stopping: Promise | undefined + let fifthSettled = false + let stopped = false + try { + await client.start() + const pid = Number((await driver`SELECT pg_backend_pid() AS pid`)[0]!['pid']) + holding = blocker.begin(async (tx) => { + await tx`LOCK TABLE duron.jobs_active IN ACCESS EXCLUSIVE MODE` + locked.resolve() + await release.promise + }) + await locked.promise + let sawError = false + let withholding = false + relay.hold = (tag, connection) => { + if (connection.pid !== pid) return false + if (tag === 'E') { + sawError = true + if (phase === 'read error response') withholding = true + } + if (sawError && tag === 'C' && phase === 'rollback response') withholding = true + return withholding + } + const first = Array.from({ length: 4 }, () => + client.waitForJob(crypto.randomUUID(), { timeout: 2000 }), + ) + const fifth = client.waitForJob(crypto.randomUUID(), { timeout: 2000 }).then((result) => { + fifthSettled = true + return result + }) + expect(await Promise.all(first)).toEqual([null, null, null, null]) + await eventually(() => relay.held.length > 0) + expect(fifthSettled).toBe(false) + expect( + reports.filter((report) => report.message === '[Duron] Wait read expired'), + ).toHaveLength(4) + expect( + reports.filter((report) => report.message === '[Duron] Wait read failed'), + ).toHaveLength(0) + // First-use extended-query errors need the driver's Sync. Withholding + // ErrorResponse leaves the server active/ClientRead, NOT executing SQL. + // Rollback acknowledgement withholding instead leaves the server idle. + expect(relay.held.some(({ frame }) => frame.toString().includes('57014'))).toBe( + phase === 'read error response', + ) + await eventually(async () => { + const states = await admin`SELECT state,wait_event FROM pg_stat_activity WHERE pid=${pid}` + return phase === 'rollback response' + ? states[0]?.['state'] === 'idle' + : states[0]?.['state'] === 'active' && states[0]?.['wait_event'] === 'ClientRead' + }) + stopping = client.stop().then((result) => { + stopped = true + return result + }) + expect(await fifth).toBeNull() + await Bun.sleep(50) + expect(stopped).toBe(false) + relay.flush() + release.resolve() + await holding + expect(await stopping).toBe(true) + const lateErrors = reports.filter((report) => report.message === '[Duron] Wait read failed') + expect(lateErrors).toHaveLength(1) + expect(lateErrors[0]!.fields).toMatchObject({ late: true }) + expect(JSON.stringify(lateErrors)).toContain('57014') + expect(relay.errors).toEqual([]) + } finally { + relay.flush() + release.resolve() + await holding?.catch(() => undefined) + await stopping?.catch(() => undefined) + await client.stop() + await blocker.end({ timeout: 5 }) + await relay.close() + expect(relay.sockets).toBe(0) + await eventually( + async () => + Number( + ( + await admin`SELECT count(*) AS count FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid()` + )[0]!['count'], + ) === 0, + ) + await admin.end({ timeout: 5 }) + await deleteDb() + } + }, 30_000) + } +}) From 3156e0686b68037a90e91aecd4f699869a5d508d Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 9 Nov 2026 22:14:45 -0300 Subject: [PATCH 009/100] fix: claim jobs in SERIALIZABLE transactions published only after commit Run each built-in PostgreSQL/PGLite claim (`_fetch`) in its own SERIALIZABLE transaction on a transaction-bound context, using the byte-identical claim query. Concurrent claims can no longer both commit admissions from a stale group count: PostgreSQL rejects one with SQLSTATE 40001 at the statement or at COMMIT. Jobs are returned only after COMMIT; statement and COMMIT errors propagate without retry or empty conversion. SQL now() is the claim transaction's BEGIN time (approved). Existing transaction/statement lifecycle gates cover BEGIN, SET TRANSACTION, the claim and pre-COMMIT; the claim callback is tracked through outer driver rejection. Public/custom override dispatch is unchanged. Adds native PostgreSQL claim-admission regressions (stale overlap, Client held handlers, write skew, withheld COMMIT/ROLLBACK, drain/setup gates, BEGIN reference, lock footprint, mixed-legacy limit), seeded selection fixtures on both engines and PGLite shared-path tests; observes the in-flight fetch in two existing cancel fixtures; documents claim admission, limits and the postgres.js close limitation. --- packages/docs/content/docs/adapters.mdx | 2 + packages/docs/content/docs/multi-worker.mdx | 15 + packages/duron/src/adapters/postgres/base.ts | 32 +- packages/duron/test/claim-isolation.test.ts | 800 +++++++++++++++++++ packages/duron/test/claim-pglite.test.ts | 139 ++++ packages/duron/test/claim-selection.test.ts | 145 ++++ packages/duron/test/client.test.ts | 11 +- packages/duron/test/nested-steps.test.ts | 10 +- packages/duron/test/prune-relay.ts | 4 +- 9 files changed, 1145 insertions(+), 13 deletions(-) create mode 100644 packages/duron/test/claim-isolation.test.ts create mode 100644 packages/duron/test/claim-pglite.test.ts create mode 100644 packages/duron/test/claim-selection.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 9a1e70c..7386440 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -280,6 +280,8 @@ export class MyCustomAdapter extends Adapter { See the [Adapter API Reference](/docs/adapters) for all required methods. +`Adapter.fetch()` dispatches to your `_fetch` override, and so does `Client.fetch()` when the Client has actions configured. A custom `_fetch` is responsible for its own cross-worker capacity safety; it only receives the built-in `SERIALIZABLE` claim protection when it delegates to the built-in PostgreSQL/PGLite `_fetch` (see [Multi-Worker Setup](/docs/multi-worker#claim-admission-and-group-capacity)). + ## Best Practices ### Use PGLite for Development diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index af44a2a..1bf2161 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -220,6 +220,21 @@ process.on('SIGINT', async () => { }) ``` +## Claim Admission and Group Capacity + +The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` transaction per fetch. The claim query itself is unchanged: the latest unexpired job for each action name and group key supplies the concurrency limit, candidates are row-locked with `SKIP LOCKED`, and the oldest eligible jobs are claimed first. Claimed jobs are returned, and their handlers can start, only after the transaction commits. + +When concurrent claims from different workers would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. Duron does not retry inside the fetch and does not turn the error into an empty result: a manual `client.fetch()` or `adapter.fetch()` call rejects with the original error, while automatic pull and push fetches log it and fetch again on their next pull or notification. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so occasional conflicts between unrelated groups are possible. Handle the rejection of a `fetch()` you start without awaiting. + +Limits of this protection: + +- Only built-in claims participate. A worker running an older Duron version, a custom `_fetch` override or direct SQL that claims under `READ COMMITTED` can still exceed a limit when it runs concurrently. +- SQL `now()` in a claim is the claim transaction's start time, not the claim statement's. It determines which latest jobs supply limits, which active jobs count, and the claimed jobs' `startedAt` and `expiresAt`. +- The limit governs admission under the existing latest-job and expiry rules. It is not a lease or fence on running work; expiry, recovery and limit changes keep their existing behavior. +- If a claim's commit reply is lost, the outcome is uncertain. Duron does not run or replay that claim; existing liveness and recovery handle a job that was committed. +- Known driver limitation, observed with postgres.js 3.4.9: if the database connection closes while any built-in transaction is open, including a claim, the driver can throw an uncaught exception from its own rollback attempt and keep that pooled connection unusable until the adapter closes. Under Node.js's default handling, an uncaught exception terminates the process. The uncommitted claim is not returned. +- PGLite is a single-engine test backend; it runs claims one at a time and is not evidence of multi-process isolation. + ## Job Recovery Duron uses heartbeat-based liveness detection for crashed-instance recovery: diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index dda3b40..2f12bc6 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1120,13 +1120,34 @@ export abstract class PostgresBaseAdapter< /** * Internal method to fetch jobs from the database respecting concurrency limits per group. * Uses the concurrency limit from the latest job created for each groupKey. - * Uses advisory locks to ensure thread-safe job fetching. + * + * Each claim runs the unchanged row-locking claim query in its own SERIALIZABLE + * transaction, so concurrent claimants cannot both commit admissions from a stale + * group count. Claimed jobs are returned only after COMMIT succeeds. Statement and + * COMMIT errors, including serialization failures (SQLSTATE 40001), propagate + * without retry. SQL `now()` is the transaction's BEGIN time. * * @returns Promise resolving to an array of fetched jobs */ protected async _fetch({ batch }: FetchOptions) { - const result = this._map( - await this.db.execute(sql` + let claim: Promise | undefined + try { + return await this.db.transaction( + (tx) => { + claim = tx.execute(this._claimQuery(batch)).then((rows) => this._map(rows)) + return claim + }, + { isolationLevel: 'serializable' }, + ) + } finally { + // A driver can reject the transaction on connection close (postgres.js does) + // before this callback settles. That does not discharge the claim's own work. + await claim?.catch(() => undefined) + } + } + + private _claimQuery(batch: number): SQL { + return sql` WITH group_concurrency AS ( -- Get the concurrency limit from the latest job for each group SELECT DISTINCT ON (j.group_key, j.action_name) @@ -1221,10 +1242,7 @@ export abstract class PostgresBaseAdapter< j.updated_at as "updatedAt", j.concurrency_limit as "concurrencyLimit", j.concurrency_step_limit as "concurrencyStepLimit" - `), - ) - - return result + ` } /** diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts new file mode 100644 index 0000000..9ad0daf --- /dev/null +++ b/packages/duron/test/claim-isolation.test.ts @@ -0,0 +1,800 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' +import { z } from 'zod' + +import { defineAction } from '../src/action.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' +import { lifecycleFor } from '../src/lifecycle.js' + +import { getPostgresConnection } from './docker.js' +import { PruneRelay } from './prune-relay.js' + +// Native PostgreSQL claim-admission regressions. Public Adapter.fetch/Client.fetch +// outcomes are decisive; owned test-only triggers, advisory-lock barriers and +// native counts are labelled supplements in fresh owned databases only. + +const BARRIER_KEY = 90_901 + +async function eventually(check: () => boolean | Promise, timeout = 2_000): Promise { + const end = performance.now() + timeout + while (!(await check())) { + if (performance.now() >= end) throw new Error('Claim condition exceeded bounded observation') + await Bun.sleep(5) + } +} + +function sqlState(error: unknown): unknown { + const value = error as { code?: unknown; cause?: { code?: unknown } } | null + return value?.code ?? value?.cause?.code +} + +type Settled = { status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown } + +function rejection(settled: Settled): unknown { + expect(settled.status).toBe('rejected') + return (settled as { reason: unknown }).reason +} + +function fulfilment(settled: Settled): T { + expect(settled.status).toBe('fulfilled') + return (settled as { value: T }).value +} + +function driverOf(adapter: PostgresAdapter): postgres.Sql { + return (adapter as unknown as { db: { $client: postgres.Sql } }).db.$client +} + +// Withholds the adapter session's replies from the CommandComplete whose tag +// starts with `command` onward, until relay.flush(). Returns the backend pid. +async function withholdReplyFrom( + relay: PruneRelay, + adapter: PostgresAdapter, + command: 'BEGIN' | 'COMMIT' | 'ROLLBACK', +): Promise { + const pid = Number((await driverOf(adapter)`SELECT pg_backend_pid() AS pid`)[0]!['pid']) + let withholding = false + relay.hold = (tag, connection, frame) => { + if (connection.pid !== pid) return false + if (tag === 'C' && frame.subarray(5).toString().startsWith(command)) withholding = true + return withholding + } + return pid +} + +function observe(promise: Promise): Promise> { + return promise.then( + (value) => ({ status: 'fulfilled', value }), + (reason: unknown) => ({ status: 'rejected', reason }), + ) +} + +async function claimDatabase() { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const url = new URL(CONNECTION_URL) + const options = (applicationName: string, max?: number, relayPort?: number) => ({ + ...(max ? { max } : {}), + host: relayPort ? '127.0.0.1' : url.hostname, + port: relayPort ?? Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + connection: { application_name: applicationName, statement_timeout: 10_000 }, + }) + const admin = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 5_000 } }) + const barrier = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 5_000 } }) + const adapters: PostgresAdapter[] = [] + // relayPort routes this adapter's owned sessions through the diagnostic relay. + const adapter = (name: string, max?: number, relayPort?: number) => { + const instance = new PostgresAdapter({ connection: options(name, max, relayPort) }) + instance.setId(name) + adapters.push(instance) + return instance + } + return { + url: CONNECTION_URL, + admin, + adapter, + async activeCount(): Promise { + const rows = + await admin`SELECT count(*)::int AS count FROM duron.jobs_active WHERE status = 'active'` + return rows[0]!['count'] as number + }, + // Owned test-only barrier: pauses only the named session's claim UPDATE + // after its statement snapshot exists, until the barrier session unlocks. + // It first records all active rows visible to that claim's snapshot in a + // non-transactional owned sequence, so the observation survives rollback. + // This is a snapshot proxy for eligible_groups' count in single-group, + // unexpired fixtures. The claim query already reads these rows, so this + // read adds no rows to the claimant's serializable read set. + async installBeforeUpdateBarrier(applicationName: string): Promise { + await admin.unsafe(` + CREATE SEQUENCE duron.claim_test_seen_active MINVALUE 0; + CREATE FUNCTION duron.claim_test_before_barrier() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF current_setting('application_name') = '${applicationName}' THEN + PERFORM setval('duron.claim_test_seen_active', + (SELECT count(*) FROM duron.jobs_active WHERE status = 'active')); + PERFORM pg_advisory_xact_lock(${BARRIER_KEY}); + END IF; + RETURN NULL; + END $$; + CREATE TRIGGER claim_test_before_barrier BEFORE UPDATE ON duron.jobs_active + FOR EACH STATEMENT EXECUTE FUNCTION duron.claim_test_before_barrier(); + `) + }, + // Owned test-only barrier after the claim UPDATE: provisional RETURNING rows + // exist and row locks are held, but the transaction has not committed. + async installAfterUpdateBarrier(applicationNames: string[]): Promise { + const cases = applicationNames + .map((name, index) => `WHEN '${name}' THEN ${BARRIER_KEY + 1 + index}`) + .join(' ') + await admin.unsafe(` + CREATE FUNCTION duron.claim_test_after_barrier() RETURNS trigger LANGUAGE plpgsql AS $$ + DECLARE barrier_key bigint; + BEGIN + barrier_key := CASE current_setting('application_name') ${cases} END; + IF barrier_key IS NOT NULL THEN + PERFORM pg_advisory_xact_lock(barrier_key); + END IF; + RETURN NULL; + END $$; + CREATE TRIGGER claim_test_after_barrier AFTER UPDATE ON duron.jobs_active + FOR EACH STATEMENT EXECUTE FUNCTION duron.claim_test_after_barrier(); + `) + }, + // Owned test-only fault: a real statement error after the claim UPDATE, + // armed per application_name through an owned control table. + async installStatementFault(): Promise { + await admin.unsafe(` + CREATE TABLE duron.claim_test_faults (application_name text PRIMARY KEY); + CREATE FUNCTION duron.claim_test_fault() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF EXISTS (SELECT 1 FROM duron.claim_test_faults + WHERE application_name = current_setting('application_name')) THEN + PERFORM 1 / 0; + END IF; + RETURN NULL; + END $$; + CREATE TRIGGER claim_test_fault AFTER UPDATE ON duron.jobs_active + FOR EACH STATEMENT EXECUTE FUNCTION duron.claim_test_fault(); + `) + }, + async seenActive(): Promise { + const rows = await admin`SELECT last_value::int AS seen FROM duron.claim_test_seen_active` + return rows[0]!['seen'] as number + }, + async hold(key = BARRIER_KEY): Promise { + await barrier`SELECT pg_advisory_lock(${key})` + }, + async release(key?: number): Promise { + if (key === undefined) await barrier`SELECT pg_advisory_unlock_all()` + else await barrier`SELECT pg_advisory_unlock(${key})` + }, + async waitingAtBarrier(applicationName: string): Promise { + await eventually(async () => { + const rows = await admin` + SELECT count(*)::int AS count FROM pg_locks l + JOIN pg_stat_activity a ON a.pid = l.pid + WHERE l.locktype = 'advisory' AND NOT l.granted + AND a.application_name = ${applicationName}` + return rows[0]!['count'] === 1 + }) + }, + async cleanup(): Promise { + try { + await barrier`SELECT pg_advisory_unlock_all()`.catch(() => undefined) + for (const instance of adapters) await instance.stop().catch(() => undefined) + await barrier.end({ timeout: 5 }) + await eventually(async () => { + const rows = + await admin`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + return rows[0]!['count'] === 0 + }) + } finally { + await admin.end({ timeout: 5 }) + await deleteDb() + } + }, + } +} + +type TracedStatement = { query: string; parameters: unknown[] } + +const ignore = () => undefined +const isClaim = (statement: TracedStatement) => statement.query.includes('group_concurrency') +const isSetTransaction = (statement: TracedStatement) => + /^set transaction/i.test(statement.query.trim()) + +// Records every statement the adapter's driver sends, via its public logger. +function traceStatements(adapter: PostgresAdapter): TracedStatement[] { + const statements: TracedStatement[] = [] + adapter.setLogger({ + trace: (fields: { query?: string; parameters?: unknown[] }) => { + if (fields.query) + statements.push({ query: fields.query, parameters: fields.parameters ?? [] }) + }, + debug: ignore, + info: ignore, + warn: ignore, + error: ignore, + } as never) + return statements +} + +async function createJobs( + adapter: PostgresAdapter, + count: number, + concurrencyLimit: number, +): Promise { + const ids: string[] = [] + for (let index = 0; index < count; index++) { + ids.push( + (await adapter.createJob({ + queue: 'claim-action', + groupKey: 'claim-group', + input: { index }, + timeoutMs: 60_000, + checksum: 'claim-checksum', + concurrencyLimit, + concurrencyStepLimit: 1, + }))!, + ) + } + return ids +} + +// Seeded schedules from the accepted capacity evidence. Base READ COMMITTED +// produced 3/4/2 active claims for these limits; fresh controls stay at capacity. +const schedules = [ + { name: 'limit 2, one already active', jobs: 3, limit: 2, preclaimed: 1, batch: 1 }, + { name: 'limit 2, empty group, batch 2', jobs: 4, limit: 2, preclaimed: 0, batch: 2 }, + { name: 'limit 1, empty group', jobs: 2, limit: 1, preclaimed: 0, batch: 1 }, +] + +const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip +suite('Native PostgreSQL claim admission', () => { + for (const schedule of schedules) { + it(`rejects a stale overlapping Adapter.fetch instead of exceeding group capacity (${schedule.name})`, async () => { + const db = await claimDatabase() + try { + const a = db.adapter('claim-a') + const b = db.adapter('claim-b') + await a.start() + await b.start() + await createJobs(a, schedule.jobs, schedule.limit) + if (schedule.preclaimed) { + expect(await a.fetch({ batch: schedule.preclaimed })).toHaveLength(schedule.preclaimed) + } + await db.installBeforeUpdateBarrier('claim-b') + await db.hold() + const stale = observe(b.fetch({ batch: schedule.batch })) + await db.waitingAtBarrier('claim-b') + expect(await a.fetch({ batch: schedule.batch })).toHaveLength( + schedule.limit - schedule.preclaimed, + ) + // Native snapshot proxy: the paused claim still sees the pre-claimed count. + expect(await db.activeCount()).toBe(schedule.limit) + expect(await db.seenActive()).toBe(schedule.preclaimed) + await db.release() + const result = await stale + expect(await db.activeCount()).toBe(schedule.limit) + expect(sqlState(rejection(result))).toBe('40001') + } finally { + await db.cleanup() + } + }, 30_000) + + it(`returns empty for a fresh Adapter.fetch started after the competing commit (${schedule.name})`, async () => { + const db = await claimDatabase() + try { + const a = db.adapter('claim-a') + const b = db.adapter('claim-b') + await a.start() + await b.start() + await createJobs(a, schedule.jobs, schedule.limit) + if (schedule.preclaimed) await a.fetch({ batch: schedule.preclaimed }) + await a.fetch({ batch: schedule.batch }) + expect(await b.fetch({ batch: schedule.batch })).toEqual([]) + expect(await db.activeCount()).toBe(schedule.limit) + } finally { + await db.cleanup() + } + }, 30_000) + } + + it('withholds the claim until COMMIT while keeping the existing candidate lock footprint', async () => { + const db = await claimDatabase() + try { + const a = db.adapter('claim-a') + const b = db.adapter('claim-b') + await a.start() + await b.start() + const ids = await createJobs(a, 5, 10) + await db.installAfterUpdateBarrier(['claim-a']) + await db.hold(BARRIER_KEY + 1) + let settled = false + const claim = a.fetch({ batch: 1 }).finally(() => { + settled = true + }) + await db.waitingAtBarrier('claim-a') + await Bun.sleep(50) + expect(settled).toBe(false) + const before = await db.admin`SELECT status FROM duron.jobs_active ORDER BY created_at, id` + expect(before.map((row) => row['status'])).toEqual(Array(5).fill('created')) + // Selected and unselected candidates stay locked by the open claim transaction. + for (const id of [ids[0]!, ids[4]!]) { + const probe = await observe( + db.admin`SELECT id FROM duron.jobs_active WHERE id = ${id} FOR UPDATE NOWAIT`, + ) + expect(sqlState(rejection(probe))).toBe('55P03') + } + expect(await b.fetch({ batch: 1 })).toEqual([]) + await db.release(BARRIER_KEY + 1) + expect((await claim).map((job) => job.id)).toEqual([ids[0]!]) + expect(await db.activeCount()).toBe(1) + expect((await b.fetch({ batch: 1 })).map((job) => job.id)).toEqual([ids[1]!]) + } finally { + await db.cleanup() + } + }, 30_000) + + it('rolls back a claim statement error and propagates it instead of returning empty', async () => { + const db = await claimDatabase() + try { + const a = db.adapter('claim-a', 1) + const b = db.adapter('claim-b') + await a.start() + await b.start() + const ids = await createJobs(a, 2, 1) + await db.installStatementFault() + await db.admin`INSERT INTO duron.claim_test_faults VALUES ('claim-a')` + const failed = await observe(a.fetch({ batch: 1 })) + expect(sqlState(rejection(failed))).toBe('22012') + expect(await db.activeCount()).toBe(0) + // Rollback released the provisional row lock for another claimant. + expect((await b.fetch({ batch: 1 })).map((job) => job.id)).toEqual([ids[0]!]) + await db.admin`DELETE FROM duron.claim_test_faults` + expect(await a.fetch({ batch: 1 })).toEqual([]) + const driver = driverOf(a) + expect((await driver`SHOW transaction_isolation`)[0]!['transaction_isolation']).toBe( + 'read committed', + ) + } finally { + await db.cleanup() + } + }, 30_000) + + it('keeps a committed claim unpublished and drained while its COMMIT reply is withheld', async () => { + const db = await claimDatabase() + const relay = new PruneRelay() + const started: string[] = [] + const action = defineAction()({ + name: 'claim-reply', + input: z.object({ index: z.number() }), + output: z.object({ index: z.number() }), + groups: { groupKey: async () => 'claim-group', concurrency: async () => 1 }, + handler: async (ctx) => { + started.push(ctx.jobId) + return { index: ctx.input.index } + }, + }) + const client = new Client({ + id: 'claim-a', + database: db.adapter('claim-a', 1, relay.port), + actions: { claimReply: action }, + syncPattern: false, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + let stopping: Promise | undefined + try { + await client.start() + const id = await client.runAction('claimReply', { index: 0 }) + await withholdReplyFrom(relay, client.database as PostgresAdapter, 'COMMIT') + let settled = false + const fetched = client.fetch({ batchSize: 1 }).finally(() => { + settled = true + }) + // Real server commit is visible before the client receives its reply. + await eventually(async () => (await db.activeCount()) === 1) + await eventually(() => relay.held.length > 0) + let stopped = false + stopping = client.stop().finally(() => { + stopped = true + }) + await Bun.sleep(100) + expect(settled).toBe(false) + expect(stopped).toBe(false) + relay.flush() + // The admitted manual fetch returns its actual claim, but no handler starts after stop. + expect((await fetched).map((job) => job.id)).toEqual([id]) + expect(await stopping).toBe(true) + expect(started).toEqual([]) + expect(await db.activeCount()).toBe(1) + expect(relay.errors).toEqual([]) + } finally { + relay.flush() + await stopping?.catch(() => undefined) + await client.stop().catch(() => undefined) + await relay.close() + await db.cleanup() + } + }, 30_000) + + it('propagates the statement error only after a withheld ROLLBACK reply arrives', async () => { + const db = await claimDatabase() + const relay = new PruneRelay() + const a = db.adapter('claim-a', 1, relay.port) + let stopping: Promise | undefined + try { + await a.start() + const [id] = await createJobs(a, 1, 1) + await db.installStatementFault() + await db.admin`INSERT INTO duron.claim_test_faults VALUES ('claim-a')` + const pid = await withholdReplyFrom(relay, a, 'ROLLBACK') + let settled = false + const failed = observe(a.fetch({ batch: 1 })).finally(() => { + settled = true + }) + await eventually(() => relay.held.length > 0) + // The server has rolled back and released the row; the public call is still pending. + await eventually(async () => { + const [state] = await db.admin`SELECT state FROM pg_stat_activity WHERE pid = ${pid}` + return state?.['state'] === 'idle' + }) + expect( + (await db.admin`SELECT id FROM duron.jobs_active WHERE id = ${id!} FOR UPDATE NOWAIT`) + .length, + ).toBe(1) + expect(await db.activeCount()).toBe(0) + let stopped = false + stopping = a.stop().finally(() => { + stopped = true + }) + await Bun.sleep(100) + expect(settled).toBe(false) + expect(stopped).toBe(false) + relay.flush() + const result = await failed + expect(sqlState(rejection(result))).toBe('22012') + expect(await stopping).toBe(true) + expect(await db.activeCount()).toBe(0) + expect(relay.errors).toEqual([]) + } finally { + relay.flush() + await stopping?.catch(() => undefined) + await a.stop().catch(() => undefined) + await relay.close() + await db.cleanup() + } + }, 30_000) + + it('rolls back an admitted claim that crosses the admitted-work drain boundary', async () => { + const db = await claimDatabase() + try { + const a = db.adapter('claim-a') + const statements = traceStatements(a) + await a.start() + await createJobs(a, 2, 2) + await db.installBeforeUpdateBarrier('claim-a') + await db.hold() + const claim = observe(a.fetch({ batch: 1 })) + await db.waitingAtBarrier('claim-a') + const stopping = observe(a.stop()) + // Hold the admitted claim past the unchanged five-second drain budget. + await eventually(() => !lifecycleFor(a).ordinaryOpen, 7_000) + await db.release() + expect((rejection(await claim) as Error).message).toBe('Lifecycle ordinary work has drained') + expect(statements.filter(isClaim)).toHaveLength(1) + expect(await db.activeCount()).toBe(0) + expect((rejection(await stopping) as Error).message).toContain('admitted-work drain') + } finally { + await db.cleanup() + } + }, 30_000) + + it('issues no setup or claim SQL when its BEGIN reply arrives after the drain boundary', async () => { + const db = await claimDatabase() + const relay = new PruneRelay() + const a = db.adapter('claim-a', 1, relay.port) + try { + const statements = traceStatements(a) + await a.start() + // Control: an ordinary claim sends SET TRANSACTION and the claim statement. + expect(await a.fetch({ batch: 1 })).toEqual([]) + expect(statements.filter(isSetTransaction)).toHaveLength(1) + expect(statements.filter(isClaim)).toHaveLength(1) + await createJobs(a, 1, 1) + await withholdReplyFrom(relay, a, 'BEGIN') + const claim = observe(a.fetch({ batch: 1 })) + await eventually(() => relay.held.length > 0) + const stopping = observe(a.stop()) + // Hold the acquired-but-unacknowledged transaction past the drain budget. + await eventually(() => !lifecycleFor(a).ordinaryOpen, 7_000) + relay.flush() + // The existing statement gate rejects SET TRANSACTION; the driver rolls back. + expect((rejection(await claim) as Error).message).toBe('Lifecycle ordinary work has drained') + expect(statements.filter(isSetTransaction)).toHaveLength(1) + expect(statements.filter(isClaim)).toHaveLength(1) + expect(await db.activeCount()).toBe(0) + const stopped = rejection(await stopping) as Error + expect(stopped.message).toContain('admitted-work drain') + expect(relay.errors).toEqual([]) + } finally { + relay.flush() + await a.stop().catch(() => undefined) + await relay.close() + await db.cleanup() + } + }, 30_000) + + it('uses the explicit claim transaction BEGIN time as the SQL reference', async () => { + const db = await claimDatabase() + const relay = new PruneRelay() + const b = db.adapter('claim-b', 1, relay.port) + try { + await b.start() + const [id] = await createJobs(b, 1, 1) + // Owned test-only trigger recording the claim statement's SQL clocks. + await db.admin.unsafe(` + CREATE TABLE duron.claim_test_clocks (reference timestamptz, statement timestamptz); + CREATE FUNCTION duron.claim_test_clocks() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + INSERT INTO duron.claim_test_clocks VALUES (now(), statement_timestamp()); + RETURN NULL; + END $$; + CREATE TRIGGER claim_test_clocks BEFORE UPDATE ON duron.jobs_active + FOR EACH STATEMENT EXECUTE FUNCTION duron.claim_test_clocks(); + `) + // Delay only the BEGIN acknowledgement, so the claim statement starts later. + await withholdReplyFrom(relay, b, 'BEGIN') + const claim = b.fetch({ batch: 1 }) + await eventually(() => relay.held.length > 0) + await Bun.sleep(200) + relay.flush() + expect((await claim).map((job) => job.id)).toEqual([id!]) + const [clock] = await db.admin` + SELECT (c.statement - c.reference) >= interval '200 milliseconds' AS begin_precedes_claim, + (j.started_at = c.reference) AS started_at_reference, + (j.expires_at - j.started_at) AS timeout + FROM duron.claim_test_clocks c CROSS JOIN duron.jobs_active j WHERE j.id = ${id!}` + expect(clock!['begin_precedes_claim']).toBe(true) + expect(clock!['started_at_reference']).toBe(true) + expect(clock!['timeout']).toBe('00:01:00') + expect(await b.stop()).toBe(true) + expect(relay.errors).toEqual([]) + } finally { + relay.flush() + await b.stop().catch(() => undefined) + await relay.close() + await db.cleanup() + } + }, 30_000) + + it('rejects a distinct-row write skew at COMMIT without publishing its provisional claim', async () => { + const db = await claimDatabase() + const holder = postgres(db.url, { max: 1, connection: { statement_timeout: 5_000 } }) + let holding: Promise | undefined + try { + const a = db.adapter('claim-a') + const b = db.adapter('claim-b', 1) + await a.start() + await b.start() + const [first, second] = await createJobs(a, 2, 1) + await db.installAfterUpdateBarrier(['claim-a', 'claim-b']) + await db.hold(BARRIER_KEY + 1) + await db.hold(BARRIER_KEY + 2) + // Labelled SQL instrumentation: an owned row lock makes A skip the second job. + const locked = Promise.withResolvers() + const unlock = Promise.withResolvers() + holding = holder.begin(async (tx) => { + await tx`SELECT id FROM duron.jobs_active WHERE id = ${second!} FOR UPDATE` + locked.resolve() + await unlock.promise + }) + await locked.promise + const claimA = observe(a.fetch({ batch: 1 })) + await db.waitingAtBarrier('claim-a') + unlock.resolve() + await holding + // B's snapshot cannot see A's uncommitted claim; it skips A's locked row. + const claimB = observe(b.fetch({ batch: 1 })) + await db.waitingAtBarrier('claim-b') + const provisional = + await db.admin`SELECT id, status FROM duron.jobs_active ORDER BY created_at, id` + expect(provisional.map((row) => row['status'])).toEqual(['created', 'created']) + await db.release(BARRIER_KEY + 1) + const resultA = await claimA + expect(fulfilment(resultA).map((job) => job.id)).toEqual([first!]) + await db.release(BARRIER_KEY + 2) + const resultB = await claimB + const final = await db.admin`SELECT id, status FROM duron.jobs_active ORDER BY created_at, id` + expect(final.map((row) => row['status'])).toEqual(['active', 'created']) + // The original driver COMMIT error propagates unwrapped and unconverted. + const commitError = rejection(resultB) as { code?: string; detail?: string } + expect(commitError.code).toBe('40001') + expect(commitError.detail).toContain('during commit attempt') + // The same single pooled B session is reusable at its ordinary isolation. + expect(await b.fetch({ batch: 1 })).toEqual([]) + const driver = driverOf(b) + expect((await driver`SHOW transaction_isolation`)[0]!['transaction_isolation']).toBe( + 'read committed', + ) + } finally { + await holding?.catch(() => undefined) + await holder.end({ timeout: 5 }) + await db.cleanup() + } + }, 30_000) + + // Labelled negative controls: the exact claim SQL captured from the real adapter + // is replayed in owned sessions at each isolation level with the same schedule. + for (const [isolation, expected] of [ + ['read committed', ['active', 'active']], + ['repeatable read', ['active', 'active']], + ['serializable', ['active', 'created']], + ] as const) { + it(`replays the exact claim SQL under ${isolation} for the distinct-row schedule`, async () => { + const db = await claimDatabase() + const sessions = [0, 1, 2].map(() => + postgres(db.url, { max: 1, connection: { statement_timeout: 5_000 } }), + ) + const [holder, sessionA, sessionB] = sessions as [postgres.Sql, postgres.Sql, postgres.Sql] + const pending: Promise[] = [] + try { + const capture = db.adapter('claim-capture') + const statements = traceStatements(capture) + await capture.start() + // Capture the real generated statement from an empty claim, then seed rows. + expect(await capture.fetch({ batch: 1 })).toEqual([]) + const claims = statements.filter(isClaim) + expect(claims).toHaveLength(1) + const [first, second] = await createJobs(capture, 2, 1) + const { query, parameters } = claims[0]! + const lockedSecond = Promise.withResolvers() + const unlock = Promise.withResolvers() + const claimedA = Promise.withResolvers() + const claimedB = Promise.withResolvers() + const commitA = Promise.withResolvers() + const commitB = Promise.withResolvers() + const hold = holder.begin(async (tx) => { + await tx`SELECT id FROM duron.jobs_active WHERE id = ${second!} FOR UPDATE` + lockedSecond.resolve() + await unlock.promise + }) + pending.push(hold) + await lockedSecond.promise + const replay = ( + session: postgres.Sql, + claimed: PromiseWithResolvers, + commit: PromiseWithResolvers, + ) => + observe( + session.begin(`isolation level ${isolation}`, async (tx) => { + claimed.resolve(await tx.unsafe(query, parameters as never[])) + await commit.promise + }), + ) + const replayA = replay(sessionA, claimedA, commitA) + expect(((await claimedA.promise) as Array<{ id: string }>).map((row) => row.id)).toEqual([ + first!, + ]) + unlock.resolve() + await hold + const replayB = replay(sessionB, claimedB, commitB) + expect(((await claimedB.promise) as Array<{ id: string }>).map((row) => row.id)).toEqual([ + second!, + ]) + commitA.resolve() + expect((await replayA).status).toBe('fulfilled') + commitB.resolve() + const resultB = await replayB + const final = await db.admin`SELECT status FROM duron.jobs_active ORDER BY created_at, id` + expect(final.map((row) => row['status'])).toEqual([...expected]) + if (isolation === 'serializable') { + expect(sqlState(rejection(resultB))).toBe('40001') + } else { + expect(resultB.status).toBe('fulfilled') + } + } finally { + await Promise.allSettled(pending) + for (const session of sessions) await session.end({ timeout: 5 }) + await db.cleanup() + } + }, 30_000) + } + + // Labelled limitation control: a stale legacy READ COMMITTED claimant that does + // not participate in SERIALIZABLE claims can still exceed capacity. + it('does not protect against a mixed legacy READ COMMITTED claimant', async () => { + const db = await claimDatabase() + const legacy = postgres(db.url, { + max: 1, + connection: { application_name: 'claim-b', statement_timeout: 5_000 }, + }) + try { + const a = db.adapter('claim-a') + const statements = traceStatements(a) + await a.start() + expect(await a.fetch({ batch: 1 })).toEqual([]) + const { query, parameters } = statements.find(isClaim)! + await createJobs(a, 3, 2) + expect(await a.fetch({ batch: 1 })).toHaveLength(1) + await db.installBeforeUpdateBarrier('claim-b') + await db.hold() + const stale = observe( + legacy.begin('isolation level read committed', (tx) => + tx.unsafe(query, parameters as never[]), + ), + ) + await db.waitingAtBarrier('claim-b') + expect(await a.fetch({ batch: 1 })).toHaveLength(1) + await db.release() + expect((await stale).status).toBe('fulfilled') + expect(await db.activeCount()).toBe(3) + } finally { + await legacy.end({ timeout: 5 }) + await db.cleanup() + } + }, 30_000) + + it('holds at most the group limit of handlers across two Clients with one fetch each', async () => { + const db = await claimDatabase() + const handlers = Promise.withResolvers() + const started: string[] = [] + const action = defineAction()({ + name: 'claim-held', + input: z.object({ index: z.number() }), + output: z.object({ index: z.number() }), + groups: { groupKey: async () => 'claim-group', concurrency: async () => 2 }, + handler: async (ctx) => { + started.push(ctx.jobId) + await handlers.promise + return { index: ctx.input.index } + }, + }) + const client = (name: string) => + new Client({ + id: name, + database: db.adapter(name), + actions: { claimHeld: action }, + syncPattern: false, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + const a = client('claim-a') + const b = client('claim-b') + try { + await a.start() + await b.start() + for (let index = 0; index < 3; index++) await a.runAction('claimHeld', { index }) + expect(await a.fetch({ batchSize: 1 })).toHaveLength(1) + await db.installBeforeUpdateBarrier('claim-b') + await db.hold() + const stale = observe(b.fetch({ batchSize: 1 })) + await db.waitingAtBarrier('claim-b') + expect(await a.fetch({ batchSize: 1 })).toHaveLength(1) + await db.release() + const result = await stale + await eventually(() => started.length >= 2) + await Bun.sleep(50) + expect(started).toHaveLength(2) + expect(await db.activeCount()).toBe(2) + expect(sqlState(rejection(result))).toBe('40001') + handlers.resolve() + await eventually(async () => (await db.activeCount()) === 0) + } finally { + handlers.resolve() + await a.stop().catch(() => undefined) + await b.stop().catch(() => undefined) + await db.cleanup() + } + }, 30_000) +}) diff --git a/packages/duron/test/claim-pglite.test.ts b/packages/duron/test/claim-pglite.test.ts new file mode 100644 index 0000000..c23373e --- /dev/null +++ b/packages/duron/test/claim-pglite.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from 'bun:test' + +import type { PGlite } from '@electric-sql/pglite' +import { z } from 'zod' + +import { defineAction } from '../src/action.js' +import type { FetchOptions } from '../src/adapters/adapter.js' +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' +import { Client } from '../src/client.js' + +// Shared PGLite test-backend path only: one engine serializes its transactions, +// so these cases do not claim PostgreSQL cross-session SSI parity. + +async function createJobs(adapter: PGLiteAdapter, count: number, concurrencyLimit: number) { + const ids: string[] = [] + for (let index = 0; index < count; index++) { + ids.push( + (await adapter.createJob({ + queue: 'claim-action', + groupKey: 'claim-group', + input: { index }, + timeoutMs: 60_000, + checksum: 'claim-checksum', + concurrencyLimit, + concurrencyStepLimit: 1, + }))!, + ) + } + return ids +} + +function engineOf(adapter: PGLiteAdapter): PGlite { + return (adapter as unknown as { db: { $client: PGlite } }).db.$client +} + +describe('PGLite claim transaction', () => { + it('claims inside a SERIALIZABLE transaction without leaking the isolation level', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + adapter.setId('claim-pglite') + try { + await adapter.start() + const engine = engineOf(adapter) + // Owned test-only observation trigger recording the claim's isolation level. + await engine.exec(` + CREATE TABLE duron.claim_test_isolation (level text); + CREATE FUNCTION duron.claim_test_isolation() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + INSERT INTO duron.claim_test_isolation VALUES (current_setting('transaction_isolation')); + RETURN NULL; + END $$; + CREATE TRIGGER claim_test_isolation AFTER UPDATE ON duron.jobs_active + FOR EACH STATEMENT EXECUTE FUNCTION duron.claim_test_isolation(); + `) + const ids = await createJobs(adapter, 3, 2) + const claimed = (await adapter.fetch({ batch: 2 })).map((job) => job.id) + expect(new Set(claimed).size).toBe(2) + expect(claimed.every((id) => ids.includes(id))).toBe(true) + expect(await adapter.fetch({ batch: 2 })).toEqual([]) + const levels = await engine.query<{ level: string }>( + 'SELECT level FROM duron.claim_test_isolation', + ) + expect(levels.rows.map((row) => row.level)).toEqual(['serializable', 'serializable']) + const current = await engine.query<{ transaction_isolation: string }>( + 'SHOW transaction_isolation', + ) + expect(current.rows[0]!.transaction_isolation).toBe('read committed') + } finally { + await adapter.stop() + } + }) + + it('rolls back a claim statement error and reuses the engine for the next claim', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + adapter.setId('claim-pglite') + try { + await adapter.start() + const engine = engineOf(adapter) + await engine.exec(` + CREATE TABLE duron.claim_test_faults (armed boolean); + INSERT INTO duron.claim_test_faults VALUES (true); + CREATE FUNCTION duron.claim_test_fault() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF (SELECT armed FROM duron.claim_test_faults) THEN PERFORM 1 / 0; END IF; + RETURN NULL; + END $$; + CREATE TRIGGER claim_test_fault AFTER UPDATE ON duron.jobs_active + FOR EACH STATEMENT EXECUTE FUNCTION duron.claim_test_fault(); + `) + const [id] = await createJobs(adapter, 1, 1) + const failed = await adapter.fetch({ batch: 1 }).then( + () => null, + (error: { cause?: { code?: string } }) => error, + ) + expect(failed?.cause?.code).toBe('22012') + const statuses = await engine.query<{ status: string }>( + 'SELECT status FROM duron.jobs_active', + ) + expect(statuses.rows.map((row) => row.status)).toEqual(['created']) + await engine.exec('UPDATE duron.claim_test_faults SET armed = false') + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([id!]) + } finally { + await adapter.stop() + } + }) + + it('keeps customized _fetch override dispatch for Adapter.fetch and Client.fetch', async () => { + class CountingAdapter extends PGLiteAdapter { + calls = 0 + protected override async _fetch(options: FetchOptions) { + this.calls++ + return super._fetch(options) + } + } + const adapter = new CountingAdapter({ connection: ':memory:' }) + const action = defineAction()({ + name: 'claim-override', + input: z.object({}), + output: z.object({}), + handler: async () => ({}), + }) + const client = new Client({ + database: adapter, + actions: { claimOverride: action }, + syncPattern: false, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + try { + await client.start() + expect(await adapter.fetch({ batch: 1 })).toEqual([]) + const id = await client.runAction('claimOverride', {}) + expect((await client.fetch({ batchSize: 1 })).map((job) => job.id)).toEqual([id]) + expect(adapter.calls).toBe(2) + } finally { + await client.stop() + } + }) +}) diff --git a/packages/duron/test/claim-selection.test.ts b/packages/duron/test/claim-selection.test.ts new file mode 100644 index 0000000..2ac6e13 --- /dev/null +++ b/packages/duron/test/claim-selection.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from 'bun:test' + +import { type SQL, sql } from 'drizzle-orm' + +import { type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' + +// Seeded SQL fixtures: preserve the existing claim selection rules through the +// public Adapter.fetch. Assertions compare selected ID sets, never RETURNING order. + +type Row = { + id: number + action?: string + group?: string + status?: 'created' | 'active' | 'completed' + expires?: 'past' | 'future' | null + created: number + limit: number +} + +const expiresAt: Record | 'none', SQL> = { + past: sql`now() - interval '1 hour'`, + future: sql`now() + interval '1 hour'`, + none: sql`NULL`, +} + +const id = (value: number) => `00000000-0000-4000-8000-${String(value).padStart(12, '0')}` + +const fixtures: Array<{ name: string; batch: number; rows: Row[]; claimed: number[] }> = [ + { + name: 'latest unexpired row supplies the limit, ignoring a newer expired row', + batch: 10, + rows: [ + { id: 1, created: 1, limit: 1 }, + { id: 2, created: 2, limit: 3, expires: 'future' }, + { id: 3, created: 3, limit: 1, status: 'completed', expires: 'past' }, + ], + claimed: [1, 2], + }, + { + name: 'latest terminal active-storage row still supplies the limit', + batch: 10, + rows: [ + { id: 1, created: 1, limit: 5 }, + { id: 2, created: 2, limit: 5 }, + { id: 3, created: 3, limit: 1, status: 'completed' }, + ], + claimed: [1], + }, + { + name: 'created_at ties for the latest row resolve by descending id', + batch: 10, + rows: [ + { id: 1, created: 1, limit: 5 }, + { id: 2, created: 2, limit: 5 }, + { id: 3, created: 3, limit: 2, status: 'completed' }, + { id: 4, created: 3, limit: 1, status: 'completed' }, + ], + claimed: [1], + }, + { + name: 'capacity scope is actionName plus groupKey', + batch: 10, + rows: [ + { id: 1, action: 'x', group: 'g', created: 1, limit: 1, status: 'active', expires: 'future' }, + { id: 2, action: 'x', group: 'g', created: 2, limit: 1 }, + { id: 3, action: 'y', group: 'g', created: 3, limit: 1 }, + { id: 4, action: 'x', group: 'h', created: 4, limit: 1 }, + ], + claimed: [3, 4], + }, + { + name: 'a batch takes the globally oldest eligible jobs across groups', + batch: 3, + rows: [ + { id: 1, group: 'g1', created: 1, limit: 5 }, + { id: 2, group: 'g2', created: 2, limit: 5 }, + { id: 3, group: 'g1', created: 3, limit: 5 }, + { id: 4, group: 'g2', created: 4, limit: 5 }, + { id: 5, group: 'g1', created: 5, limit: 5 }, + ], + claimed: [1, 2, 3], + }, + { + name: 'null-expiry active jobs count toward capacity and expired active jobs do not', + batch: 10, + rows: [ + { id: 1, created: 1, limit: 2, status: 'active', expires: null }, + { id: 2, created: 2, limit: 2, status: 'active', expires: 'past' }, + { id: 3, created: 3, limit: 2 }, + { id: 4, created: 4, limit: 2 }, + ], + claimed: [3], + }, + { + name: 'an expired created job remains a claim candidate', + batch: 10, + rows: [ + { id: 1, created: 1, limit: 5, expires: 'past' }, + { id: 2, created: 2, limit: 5, expires: 'future' }, + ], + claimed: [1, 2], + }, +] + +function runClaimSelectionTests(factory: AdapterFactory) { + describe(`Claim selection with ${factory.name}`, () => { + for (const fixture of fixtures) { + it(fixture.name, async () => { + const instance = await factory.create() + const adapter = instance.adapter + adapter.setId('claim-selection') + const db = (adapter as unknown as { db: { execute: (query: SQL) => Promise } }).db + try { + await adapter.start() + for (const row of fixture.rows) { + const expires = expiresAt[row.expires ?? 'none'] + await db.execute(sql` + INSERT INTO duron.jobs_active (id, action_name, group_key, status, checksum, + timeout_ms, expires_at, client_id, concurrency_limit, concurrency_step_limit, + created_at) + VALUES (${id(row.id)}, ${row.action ?? 'x'}, ${row.group ?? 'g'}, + ${row.status ?? 'created'}, 'claim-selection', 60000, ${expires}, + ${row.status === 'active' ? 'other-client' : null}, ${row.limit}, 1, + timestamptz '2026-01-01T00:00:00Z' + ${row.created} * interval '1 second') + `) + } + const jobs = await adapter.fetch({ batch: fixture.batch }) + expect(jobs.map((job) => job.id).toSorted()).toEqual(fixture.claimed.map(id)) + } finally { + try { + await adapter.stop() + } finally { + await instance.deleteDb() + } + } + }) + } + }) +} + +runClaimSelectionTests(pgliteFactory) +// oxlint-disable-next-line useLiteralKeys +if (process.env['POSTGRES_TEST'] === 'true') { + runClaimSelectionTests(postgresFactory) +} diff --git a/packages/duron/test/client.test.ts b/packages/duron/test/client.test.ts index a6090af..8decd72 100644 --- a/packages/duron/test/client.test.ts +++ b/packages/duron/test/client.test.ts @@ -434,14 +434,21 @@ function runClientTests(adapterFactory: AdapterFactory) { it('should cancel a job', async () => { const jobId = await client.runAction('slowAction', {}) - // Start processing - client.fetch({ batchSize: 10 }) + // Start processing. A cancel that lands after the SERIALIZABLE claim's + // snapshot can reject the claim with SQLSTATE 40001. + const fetching = client.fetch({ batchSize: 10 }).then( + () => undefined, + (error: { code?: string; cause?: { code?: string } }) => { + expect(error.code ?? error.cause?.code).toBe('40001') + }, + ) // Cancel immediately await client.cancelJob(jobId) // Wait a bit await new Promise((resolve) => setTimeout(resolve, 200)) + await fetching const job = await client.getJobById(jobId) expect(job?.status).toBe(JOB_STATUS_CANCELLED) diff --git a/packages/duron/test/nested-steps.test.ts b/packages/duron/test/nested-steps.test.ts index 5eaac11..639bf7e 100644 --- a/packages/duron/test/nested-steps.test.ts +++ b/packages/duron/test/nested-steps.test.ts @@ -690,8 +690,14 @@ function runNestedStepsTests(adapterFactory: AdapterFactory) { it('should cancel all nested steps when action is cancelled', async () => { const jobId = await client.runAction('deeplyNestedAction', {}) - // Start fetching but cancel quickly - const fetchPromise = client.fetch({ batchSize: 10 }) + // Start fetching but cancel quickly. A cancel that lands after the + // SERIALIZABLE claim's snapshot can reject the claim with SQLSTATE 40001. + const fetchPromise = client.fetch({ batchSize: 10 }).then( + () => undefined, + (error: { code?: string; cause?: { code?: string } }) => { + expect(error.code ?? error.cause?.code).toBe('40001') + }, + ) // Cancel the job after a short delay await new Promise((resolve) => setTimeout(resolve, 10)) diff --git a/packages/duron/test/prune-relay.ts b/packages/duron/test/prune-relay.ts index ae48bca..17f0a7c 100644 --- a/packages/duron/test/prune-relay.ts +++ b/packages/duron/test/prune-relay.ts @@ -16,7 +16,7 @@ export class PruneRelay { readonly connections: RelayConnection[] = [] readonly errors: unknown[] = [] readonly held: Array<{ connection: RelayConnection; frame: Buffer }> = [] - hold: (tag: string, connection: RelayConnection) => boolean = () => false + hold: (tag: string, connection: RelayConnection, frame: Buffer) => boolean = () => false readonly #sockets = new Set>() readonly #connecting = new Set>() #stopped = false @@ -111,7 +111,7 @@ export class PruneRelay { // Record only the PID, never the server's secret cancellation key. if (tag === 'K') connection.pid = frame.readUInt32BE(5) if (tag === 'Z') connection.ready++ - if (this.hold(tag, connection)) this.held.push({ connection, frame }) + if (this.hold(tag, connection, frame)) this.held.push({ connection, frame }) else connection.down.write(frame) } } From 678250181e851dad1778f8370479c35c881ff8fc Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 9 Nov 2026 22:36:12 -0300 Subject: [PATCH 010/100] test: retain owned claim test databases when cleanup preconditions fail claim-isolation drops its owned database only after a fresh zero-session check passes; otherwise it keeps the database and fails with its name and the original error. claim-selection drops only after a successful adapter stop. --- packages/duron/test/claim-isolation.test.ts | 6 +++++- packages/duron/test/claim-selection.test.ts | 8 +++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 9ad0daf..a0354c0 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -185,6 +185,8 @@ async function claimDatabase() { return rows[0]!['count'] === 1 }) }, + // Drop the owned database only after fresh evidence of zero other sessions. + // Otherwise retain it for separately verified cleanup and fail with its name. async cleanup(): Promise { try { await barrier`SELECT pg_advisory_unlock_all()`.catch(() => undefined) @@ -195,10 +197,12 @@ async function claimDatabase() { await admin`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` return rows[0]!['count'] === 0 }) + } catch (error) { + throw new Error(`Retained owned database ${url.pathname.slice(1)}`, { cause: error }) } finally { await admin.end({ timeout: 5 }) - await deleteDb() } + await deleteDb() }, } } diff --git a/packages/duron/test/claim-selection.test.ts b/packages/duron/test/claim-selection.test.ts index 2ac6e13..ddf16d4 100644 --- a/packages/duron/test/claim-selection.test.ts +++ b/packages/duron/test/claim-selection.test.ts @@ -127,11 +127,9 @@ function runClaimSelectionTests(factory: AdapterFactory) { const jobs = await adapter.fetch({ batch: fixture.batch }) expect(jobs.map((job) => job.id).toSorted()).toEqual(fixture.claimed.map(id)) } finally { - try { - await adapter.stop() - } finally { - await instance.deleteDb() - } + // A failed stop retains the database rather than dropping it. + await adapter.stop() + await instance.deleteDb() } }) } From 69de46591f6874e48f5090a58b2656cc9a7f99e1 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 9 Nov 2026 22:57:23 -0300 Subject: [PATCH 011/100] test: release claim test gates before awaiting owned work Hoist the write-skew and replay tests' promise gates out of try, reject a gate when its owning transaction fails first, track replay work, and release every owned gate and advisory barrier in finally before awaiting pending work or ending sessions, so an early failure cannot strand owned transactions. The mixed-legacy test releases its barrier first too. --- packages/duron/test/claim-isolation.test.ts | 56 +++++++++++++++------ 1 file changed, 40 insertions(+), 16 deletions(-) diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index a0354c0..47900d1 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -63,6 +63,13 @@ async function withholdReplyFrom( return pid } +// Rejects a test gate if the owned work that should resolve it fails first, +// so awaiting the gate cannot hang. The gate keeps an observer attached. +function failGateWith(gate: PromiseWithResolvers, work: Promise): void { + gate.promise.catch(() => undefined) + work.catch((error: unknown) => gate.reject(error)) +} + function observe(promise: Promise): Promise> { return promise.then( (value) => ({ status: 'fulfilled', value }), @@ -584,6 +591,9 @@ suite('Native PostgreSQL claim admission', () => { it('rejects a distinct-row write skew at COMMIT without publishing its provisional claim', async () => { const db = await claimDatabase() const holder = postgres(db.url, { max: 1, connection: { statement_timeout: 5_000 } }) + // Test-owned gates live outside try so finally can always release them. + const locked = Promise.withResolvers() + const unlock = Promise.withResolvers() let holding: Promise | undefined try { const a = db.adapter('claim-a') @@ -595,13 +605,12 @@ suite('Native PostgreSQL claim admission', () => { await db.hold(BARRIER_KEY + 1) await db.hold(BARRIER_KEY + 2) // Labelled SQL instrumentation: an owned row lock makes A skip the second job. - const locked = Promise.withResolvers() - const unlock = Promise.withResolvers() holding = holder.begin(async (tx) => { await tx`SELECT id FROM duron.jobs_active WHERE id = ${second!} FOR UPDATE` locked.resolve() await unlock.promise }) + failGateWith(locked, holding) await locked.promise const claimA = observe(a.fetch({ batch: 1 })) await db.waitingAtBarrier('claim-a') @@ -631,6 +640,9 @@ suite('Native PostgreSQL claim admission', () => { 'read committed', ) } finally { + // Release every owned gate before awaiting work or ending sessions. + unlock.resolve() + await db.release().catch(() => undefined) await holding?.catch(() => undefined) await holder.end({ timeout: 5 }) await db.cleanup() @@ -651,6 +663,13 @@ suite('Native PostgreSQL claim admission', () => { ) const [holder, sessionA, sessionB] = sessions as [postgres.Sql, postgres.Sql, postgres.Sql] const pending: Promise[] = [] + // Test-owned gates live outside try so finally can always release them. + const lockedSecond = Promise.withResolvers() + const unlock = Promise.withResolvers() + const claimedA = Promise.withResolvers() + const claimedB = Promise.withResolvers() + const commitA = Promise.withResolvers() + const commitB = Promise.withResolvers() try { const capture = db.adapter('claim-capture') const statements = traceStatements(capture) @@ -661,30 +680,27 @@ suite('Native PostgreSQL claim admission', () => { expect(claims).toHaveLength(1) const [first, second] = await createJobs(capture, 2, 1) const { query, parameters } = claims[0]! - const lockedSecond = Promise.withResolvers() - const unlock = Promise.withResolvers() - const claimedA = Promise.withResolvers() - const claimedB = Promise.withResolvers() - const commitA = Promise.withResolvers() - const commitB = Promise.withResolvers() const hold = holder.begin(async (tx) => { await tx`SELECT id FROM duron.jobs_active WHERE id = ${second!} FOR UPDATE` lockedSecond.resolve() await unlock.promise }) pending.push(hold) + failGateWith(lockedSecond, hold) await lockedSecond.promise const replay = ( session: postgres.Sql, claimed: PromiseWithResolvers, commit: PromiseWithResolvers, - ) => - observe( - session.begin(`isolation level ${isolation}`, async (tx) => { - claimed.resolve(await tx.unsafe(query, parameters as never[])) - await commit.promise - }), - ) + ) => { + const work = session.begin(`isolation level ${isolation}`, async (tx) => { + claimed.resolve(await tx.unsafe(query, parameters as never[])) + await commit.promise + }) + pending.push(work) + failGateWith(claimed, work) + return observe(work) + } const replayA = replay(sessionA, claimedA, commitA) expect(((await claimedA.promise) as Array<{ id: string }>).map((row) => row.id)).toEqual([ first!, @@ -707,6 +723,10 @@ suite('Native PostgreSQL claim admission', () => { expect(resultB.status).toBe('fulfilled') } } finally { + // Release every owned gate before awaiting replay work or ending sessions. + unlock.resolve() + commitA.resolve() + commitB.resolve() await Promise.allSettled(pending) for (const session of sessions) await session.end({ timeout: 5 }) await db.cleanup() @@ -722,6 +742,7 @@ suite('Native PostgreSQL claim admission', () => { max: 1, connection: { application_name: 'claim-b', statement_timeout: 5_000 }, }) + let stale: Promise> | undefined try { const a = db.adapter('claim-a') const statements = traceStatements(a) @@ -732,7 +753,7 @@ suite('Native PostgreSQL claim admission', () => { expect(await a.fetch({ batch: 1 })).toHaveLength(1) await db.installBeforeUpdateBarrier('claim-b') await db.hold() - const stale = observe( + stale = observe( legacy.begin('isolation level read committed', (tx) => tx.unsafe(query, parameters as never[]), ), @@ -743,6 +764,9 @@ suite('Native PostgreSQL claim admission', () => { expect((await stale).status).toBe('fulfilled') expect(await db.activeCount()).toBe(3) } finally { + // Release the barrier before awaiting the legacy claim or ending its session. + await db.release().catch(() => undefined) + await stale await legacy.end({ timeout: 5 }) await db.cleanup() } From 0512dab5a8a23db8713754b4fbd414da1c05f8c7 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 16 Nov 2026 00:33:06 -0300 Subject: [PATCH 012/100] fix: lock the job row in cancel/complete/fail and step creation Cancellation raced step creation: a creator could fail with FK 23503, a step could be archived active under a cancelled job, or a committed step could be lost. Competing cancel/complete/fail could hit 23505 or 40P01. Cancel, complete and fail now take the job row FOR UPDATE in their existing first statement, with unchanged guards. The step creator's job_check takes FOR KEY SHARE OF j in its single statement. Under READ COMMITTED a committed cancellation archives every earlier step as cancelled, and later creators get the existing null result. Competing terminators serialize; the loser returns false. Claims skip a job held by a cancellation. A waiting call rechecks its guard on the latest row version. A stale creator or a stale complete/fail racing a recovery requeue therefore loses, and the requeued job can run again (approved consequence). Status writers, claims, recovery and time travel are unchanged. Adds native PostgreSQL schedule tests (POSTGRES_TEST) and sequential both-engine tests, plus docs on guarantees and limits (READ COMMITTED, participating writers, frozen now(), lock waits, recovery residual). --- packages/docs/content/docs/adapters.mdx | 2 + packages/docs/content/docs/jobs-and-steps.mdx | 2 + packages/docs/content/docs/multi-worker.mdx | 23 + packages/duron/src/adapters/postgres/base.ts | 20 +- .../duron/test/cancel-storage-shared.test.ts | 149 +++ packages/duron/test/cancel-storage.test.ts | 1006 +++++++++++++++++ 6 files changed, 1199 insertions(+), 3 deletions(-) create mode 100644 packages/duron/test/cancel-storage-shared.test.ts create mode 100644 packages/duron/test/cancel-storage.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 7386440..683de2b 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -282,6 +282,8 @@ See the [Adapter API Reference](/docs/adapters) for all required methods. `Adapter.fetch()` dispatches to your `_fetch` override, and so does `Client.fetch()` when the Client has actions configured. A custom `_fetch` is responsible for its own cross-worker capacity safety; it only receives the built-in `SERIALIZABLE` claim protection when it delegates to the built-in PostgreSQL/PGLite `_fetch` (see [Multi-Worker Setup](/docs/multi-worker#claim-admission-and-group-capacity)). +Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). + ## Best Practices ### Use PGLite for Development diff --git a/packages/docs/content/docs/jobs-and-steps.mdx b/packages/docs/content/docs/jobs-and-steps.mdx index dc89a36..322b5bd 100644 --- a/packages/docs/content/docs/jobs-and-steps.mdx +++ b/packages/docs/content/docs/jobs-and-steps.mdx @@ -79,6 +79,8 @@ You can cancel a job: await client.cancelJob(jobId) ``` +A cancelled job is archived with every step marked `cancelled`. For how cancellation interacts with concurrent step writes, completion, claims and recovery on PostgreSQL, and its limits, see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps). + ### Retrying Jobs You can retry a failed job: diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 1bf2161..ac81b7a 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -235,6 +235,29 @@ Limits of this protection: - Known driver limitation, observed with postgres.js 3.4.9: if the database connection closes while any built-in transaction is open, including a claim, the driver can throw an uncaught exception from its own rollback attempt and keep that pooled connection unusable until the adapter closes. Under Node.js's default handling, an uncaught exception terminates the process. The uncommitted claim is not returned. - PGLite is a single-engine test backend; it runs claims one at a time and is not evidence of multi-process isolation. +## Cancellation and Stored Steps + +Cancelling a job in the database archives the job as `cancelled` and archives every one of its steps as `cancelled`, including steps that had already completed or failed. On PostgreSQL, a cancellation that commits keeps every step committed before it took the job, and no step for that job can be created while it runs. A step creation that arrives while the cancellation holds the job waits for it and then returns `null` (the existing "job is not active" result) instead of failing with a foreign-key error. A step creation that took the job first makes the cancellation wait, and its step is archived as `cancelled`. A step status write that reaches its step first succeeds and is then overwritten to `cancelled`; one that arrives later waits and returns `false`. + +The same row lock orders `cancelJob`, `completeJob` and `failJob` on one job: the first to lock it wins and the others return `false`. Recovery skips a job that one of them holds. A claim also skips a `created` job that a cancellation holds, and a claim whose snapshot predates a committed cancellation of its candidate is rejected with `40001` as described above. + +A call that waited rechecks its existing conditions against the latest version of the job. This changes two outcomes when recovery requeues a job whose owner looks dead: + +- A late step creation from the previous execution returns `null`. +- A late `completeJob` or `failJob` from the previous execution returns `false`, and the requeued job stays requeued and can run again. + +If the late call locks the job first, it wins and recovery skips the job. These are rechecks of the existing conditions, not ownership or execution fencing: after time travel or a new claim, a stale handler can still create steps and update reset steps with their old IDs. + +Limits: + +- The guarantees hold when the effective transaction isolation is `READ COMMITTED` (the PostgreSQL default) and only for the built-in writers. Duron does not set the isolation level. Under a different `default_transaction_isolation`, these locks can raise serialization errors earlier, and behavior has not been analyzed. Workers on an older Duron version, custom adapter overrides and direct SQL do not participate. +- They describe the stored result as of the cancellation's commit, until a later time travel, prune or reset changes the job. False time travel restores the job and its steps as they were archived, and each step method keeps its existing guard, so `cancelJobStep` still accepts an active step under a restored `cancelled` job. +- A call that waited checks expiry against its transaction's start time, not the time it acquired the lock. Archived `finishedAt` and `updatedAt` are the application time taken before any wait. +- Lock waits have no deadline. A cancellation can wait for in-flight step creations, other terminators, recovery and claims (including claims holding candidate rows they did not select). `completeJob` and `failJob` can wait for step creations, cancellation and recovery. A step creation can wait for terminators and recovery. Step creations can keep overtaking a waiting cancellation, completion or failure, so a busy job can delay them. `client.stop()` observes such waits within its shutdown budgets but does not cut them short; an unfinished wait is reported as an incomplete drain. +- Known recovery residual (not fixed): a recovery pass works from a snapshot taken before it locks the job. A step committed in between can survive a requeue that should have deleted it, and, if its creation began before the job expired, can be lost when an expired job is archived. +- This is storage behavior only. `client.cancelJob()` aborts a job that this Client is running in memory; otherwise it cancels in the database. A database cancellation does not stop a handler that is already running elsewhere, and a job this Client has claimed but not yet started (still being fetched or queued) also takes the database path: its handler can still start and then fail when step creation returns `null`. Either handler continues until a step write returns "not active". Local handling of claimed-but-not-started jobs is separate follow-up work. +- PGLite runs one statement at a time; it shows the same sequential results, not concurrent locking behavior. + ## Job Recovery Duron uses heartbeat-based liveness detection for crashed-instance recovery: diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 2f12bc6..8c372d5 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -566,7 +566,7 @@ export abstract class PostgresBaseAdapter< return this.db.transaction(async (tx) => { const finishedAt = new Date() - // 1. Check job exists and meets conditions before archiving + // 1. Lock the job row first (see _cancelJob), with the unchanged guard const [job] = await tx .select() .from(this.tables.jobsActiveTable) @@ -578,6 +578,7 @@ export abstract class PostgresBaseAdapter< gt(this.tables.jobsActiveTable.expires_at, sql`now()`), ), ) + .for('update') if (!job) { return false @@ -625,7 +626,7 @@ export abstract class PostgresBaseAdapter< return this.db.transaction(async (tx) => { const finishedAt = new Date() - // 1. Check job exists before archiving + // 1. Lock the job row first (see _cancelJob), with the unchanged guard const [job] = await tx .select() .from(this.tables.jobsActiveTable) @@ -636,6 +637,7 @@ export abstract class PostgresBaseAdapter< eq(this.tables.jobsActiveTable.client_id, this.id), ), ) + .for('update') if (!job) { return false @@ -677,13 +679,23 @@ export abstract class PostgresBaseAdapter< /** * Internal method to cancel a job. * + * Cancel, complete and fail lock the job row in a standalone first statement + * with their unchanged guards; step creation takes FOR KEY SHARE on the same + * row. Under READ COMMITTED the later statements then see every step committed + * before the lock. A creator that reaches the row after the lock waits; once the + * cancellation commits it gets `null` instead of a foreign key error (until a + * later restoration, such as time travel, re-inserts the job). A creator already + * holding the row makes the cancellation wait and its step is archived. A call + * that waited rechecks its guard on the latest row version using its frozen + * transaction `now()`. + * * @returns Promise resolving to `true` if cancelled, `false` otherwise */ protected async _cancelJob({ jobId }: CancelJobOptions) { return this.db.transaction(async (tx) => { const finishedAt = new Date() - // 1. Check job exists before updating steps + // 1. Lock the job row first, with the unchanged guard const [job] = await tx .select() .from(this.tables.jobsActiveTable) @@ -696,6 +708,7 @@ export abstract class PostgresBaseAdapter< ), ), ) + .for('update') if (!job) { return false @@ -1397,6 +1410,7 @@ export abstract class PostgresBaseAdapter< WHERE j.id = ${jobId} AND j.status = ${JOB_STATUS_ACTIVE} AND (j.expires_at IS NULL OR j.expires_at > now()) + FOR KEY SHARE OF j ), step_existed AS ( SELECT EXISTS( diff --git a/packages/duron/test/cancel-storage-shared.test.ts b/packages/duron/test/cancel-storage-shared.test.ts new file mode 100644 index 0000000..2640dc7 --- /dev/null +++ b/packages/duron/test/cancel-storage-shared.test.ts @@ -0,0 +1,149 @@ +import { describe, expect, it } from 'bun:test' + +import { type SQL, sql } from 'drizzle-orm' + +import { type Adapter, type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' + +// Sequential cancellation-storage behaviour on both SQL engines (issue 12a). +// No concurrency is claimed here; PGLite runs one statement at a time. +// Public Adapter results and step lists are decisive. The one SQL seed is +// labelled at its use. + +async function createClaimedJob(adapter: Adapter): Promise { + const jobId = (await adapter.createJob({ + queue: 'cancel-shared', + groupKey: crypto.randomUUID(), + input: {}, + timeoutMs: 60_000, + checksum: 'cancel-shared', + concurrencyLimit: 10, + concurrencyStepLimit: 10, + }))! + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + return jobId +} + +async function createStep(adapter: Adapter, jobId: string, name: string) { + return adapter.createOrRecoverJobStep({ jobId, name, timeoutMs: 60_000, retriesLimit: 0 }) +} + +async function stepStatuses(adapter: Adapter, jobId: string): Promise> { + const { steps } = await adapter.getJobSteps({ jobId }) + return Object.fromEntries(steps.map((step) => [step.id, step.status])) +} + +function runCancelStorageTests(factory: AdapterFactory) { + describe(`Cancellation storage with ${factory.name}`, () => { + async function withAdapter(test: (adapter: Adapter) => Promise): Promise { + const instance = await factory.create() + instance.adapter.setId('cancel-shared') + try { + await instance.adapter.start() + await test(instance.adapter) + } finally { + // A failed stop retains the database rather than dropping it. + await instance.adapter.stop() + await instance.deleteDb() + } + } + + it('archives every step cancelled and rejects later writes with the existing results', async () => { + await withAdapter(async (adapter) => { + const jobId = await createClaimedJob(adapter) + const s1 = (await createStep(adapter, jobId, 's1'))! + const s2 = (await createStep(adapter, jobId, 's2'))! + expect(await adapter.completeJobStep({ stepId: s1.id, output: 1 })).toBe(true) + + expect(await adapter.cancelJob({ jobId })).toBe(true) + + expect((await adapter.getJobById(jobId))?.status).toBe('cancelled') + expect(await stepStatuses(adapter, jobId)).toEqual({ + [s1.id]: 'cancelled', + [s2.id]: 'cancelled', + }) + expect(await createStep(adapter, jobId, 's3')).toBeNull() + expect(await adapter.completeJobStep({ stepId: s2.id, output: 1 })).toBe(false) + expect(await adapter.failJobStep({ stepId: s2.id, error: { message: 'x' } })).toBe(false) + expect( + await adapter.delayJobStep({ stepId: s2.id, delayMs: 10, error: { message: 'x' } }), + ).toBe(false) + expect(await adapter.cancelJobStep({ stepId: s2.id })).toBe(false) + expect(await adapter.cancelJob({ jobId })).toBe(false) + expect(await adapter.completeJob({ jobId, output: 1 })).toBe(false) + expect(await adapter.failJob({ jobId, error: { message: 'x' } })).toBe(false) + }) + }) + + it('keeps terminator guards: complete needs this owner, cancel accepts created jobs', async () => { + await withAdapter(async (adapter) => { + const created = (await adapter.createJob({ + queue: 'cancel-shared', + groupKey: crypto.randomUUID(), + input: {}, + timeoutMs: 60_000, + checksum: 'cancel-shared', + concurrencyLimit: 10, + concurrencyStepLimit: 10, + }))! + expect(await adapter.completeJob({ jobId: created, output: 1 })).toBe(false) + expect(await adapter.failJob({ jobId: created, error: {} })).toBe(false) + expect(await adapter.cancelJob({ jobId: created })).toBe(true) + expect(await adapter.deleteJob({ jobId: created })).toBe(false) + + const claimed = await createClaimedJob(adapter) + adapter.setId('another-owner') + expect(await adapter.completeJob({ jobId: claimed, output: 1 })).toBe(false) + expect(await adapter.failJob({ jobId: claimed, error: {} })).toBe(false) + adapter.setId('cancel-shared') + expect(await adapter.completeJob({ jobId: claimed, output: 1 })).toBe(true) + }) + }) + + it('TT: after successful time travel and a new claim, stale writes keep their unfenced results', async () => { + await withAdapter(async (adapter) => { + const jobId = await createClaimedJob(adapter) + const s1 = (await createStep(adapter, jobId, 's1'))! + expect(await adapter.completeJobStep({ stepId: s1.id, output: 1 })).toBe(true) + const s2 = (await createStep(adapter, jobId, 's2'))! + expect(await adapter.completeJobStep({ stepId: s2.id, output: 2 })).toBe(true) + expect(await adapter.completeJob({ jobId, output: 'done' })).toBe(true) + + expect(await adapter.timeTravelJob({ jobId, stepId: s2.id })).toBe(true) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + + // A stale handler of the earlier execution uses its old job and step IDs. + expect(await createStep(adapter, jobId, 'stale-new')).not.toBeNull() + expect(await adapter.completeJobStep({ stepId: s2.id, output: 'stale' })).toBe(true) + expect(await adapter.completeJobStep({ stepId: s1.id, output: 'stale' })).toBe(false) + }) + }) + + it('TT-false: a false time travel restoring a cancelled job keeps cancelJobStep for a legacy active step', async () => { + await withAdapter(async (adapter) => { + const jobId = await createClaimedJob(adapter) + const s1 = (await createStep(adapter, jobId, 's1'))! + expect(await adapter.cancelJob({ jobId })).toBe(true) + // Seeded SQL (labelled): legacy archive data with an active step under a + // cancelled job, as written by pre-12a code or a bypassing writer. + const db = (adapter as unknown as { db: { execute: (query: SQL) => Promise } }).db + await db.execute( + sql`UPDATE duron.job_steps_archive SET status = 'active' WHERE id = ${s1.id}`, + ) + + expect(await adapter.timeTravelJob({ jobId, stepId: crypto.randomUUID() })).toBe(false) + + expect((await adapter.getJobById(jobId))?.status).toBe('cancelled') + expect(await stepStatuses(adapter, jobId)).toEqual({ [s1.id]: 'active' }) + expect(await createStep(adapter, jobId, 's2')).toBeNull() + expect(await adapter.completeJobStep({ stepId: s1.id, output: 1 })).toBe(false) + expect(await adapter.cancelJobStep({ stepId: s1.id })).toBe(true) + }) + }) + }) +} + +runCancelStorageTests(pgliteFactory) +// oxlint-disable-next-line useLiteralKeys +if (process.env['POSTGRES_TEST'] === 'true') { + runCancelStorageTests(postgresFactory) +} diff --git a/packages/duron/test/cancel-storage.test.ts b/packages/duron/test/cancel-storage.test.ts new file mode 100644 index 0000000..3fdba53 --- /dev/null +++ b/packages/duron/test/cancel-storage.test.ts @@ -0,0 +1,1006 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +// Native PostgreSQL cancellation/storage regressions (issue 12a). Public Adapter +// results are decisive. Supplements, each in a fresh owned database only: +// a one-shot test-only statement barrier inside one adapter transaction, +// SELECT-only native observation of lock waits and committed rows by ID, +// owned step-row locks that hold real recovery statements, and owned +// application_name-filtered advisory-lock triggers. + +const BARRIER_KEY = 91_201 +const OBSERVE_MS = 2_000 +const TEST_MS = 30_000 + +type Settled = { status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown } + +function observe(promise: Promise): Promise> { + return promise.then( + (value) => ({ status: 'fulfilled', value }), + (reason: unknown) => ({ status: 'rejected', reason }), + ) +} + +function sqlState(error: unknown): unknown { + let cause = error as { code?: unknown; cause?: unknown } | null | undefined + for (let depth = 0; cause && depth < 5; depth++) { + if (typeof cause.code === 'string') return cause.code + cause = cause.cause as typeof cause + } + return undefined +} + +function fulfilment(settled: Settled): T { + if (settled.status === 'rejected') { + throw new Error(`Expected fulfilment, got SQLSTATE ${String(sqlState(settled.reason))}`, { + cause: settled.reason, + }) + } + return settled.value +} + +function rejection(settled: Settled): unknown { + expect(settled.status).toBe('rejected') + return (settled as { reason: unknown }).reason +} + +async function eventually(check: () => boolean | Promise): Promise { + const end = performance.now() + OBSERVE_MS + while (!(await check())) { + if (performance.now() >= end) throw new Error('Condition exceeded bounded observation') + await Bun.sleep(5) + } +} + +type Gate = { reached: Promise; release: () => void; fail: (error: Error) => void } +type StatementStarter = 'select' | 'insert' | 'update' | 'delete' | 'execute' +type StatementPause = { beforeStatement: number; starter: StatementStarter } + +// Statement roles inside the built-in terminators; statement 1 is the job-row lock. +const CANCEL_AFTER_LOCK: StatementPause = { beforeStatement: 2, starter: 'update' } +const CANCEL_AFTER_STEP_UPDATE: StatementPause = { beforeStatement: 3, starter: 'insert' } +const CANCEL_AFTER_STEP_ARCHIVE: StatementPause = { beforeStatement: 5, starter: 'delete' } +const TERMINATE_AFTER_LOCK: StatementPause = { beforeStatement: 2, starter: 'insert' } + +// Test-only barrier: pauses the adapter's next transaction before the given +// statement (checked by its builder kind), or before COMMIT. fail() rejects +// inside the callback, so the transaction really rolls back. `reached` rejects +// if the transaction ends without reaching the barrier. Callers release in finally. +function gateNextTransaction(adapter: PostgresAdapter, pause: StatementPause | 'commit'): Gate { + const db = (adapter as unknown as { db: { transaction: (...args: any[]) => Promise } }) + .db + const guarded = db.transaction + const reached = Promise.withResolvers() + const open = Promise.withResolvers() + open.promise.catch(() => undefined) + reached.promise.catch(() => undefined) + const hold = async () => { + reached.resolve() + await open.promise + } + db.transaction = (work: (tx: unknown) => Promise, config: unknown) => { + db.transaction = guarded + const transaction = guarded.call( + db, + async (tx: object) => { + if (pause === 'commit') { + const result = await work(tx) + await hold() + return result + } + return work(pauseBeforeStatement(tx, pause, hold, (error) => reached.reject(error))) + }, + config, + ) + const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) + transaction.then(endedEarly, endedEarly) + return transaction + } + return { + reached: reached.promise, + release: () => { + db.transaction = guarded + open.resolve() + }, + fail: (error) => { + db.transaction = guarded + open.reject(error) + }, + } +} + +const STATEMENT_STARTERS = new Set(['select', 'insert', 'update', 'delete', 'execute']) + +function pauseBeforeStatement( + tx: object, + pause: StatementPause, + hold: () => Promise, + mismatch: (error: Error) => void, +): object { + let count = 0 + const chain = (builder: object, index: number, starter: string): object => + new Proxy(builder, { + get(object, property) { + if (property === 'then') { + return (onFulfilled: never, onRejected: never) => + (async () => { + if (index === pause.beforeStatement) { + if (starter === pause.starter) await hold() + else mismatch(new Error(`Statement ${index} is ${starter}, not ${pause.starter}`)) + } + return await (object as PromiseLike) + })().then(onFulfilled, onRejected) + } + const value = Reflect.get(object, property, object) + if (typeof value !== 'function') return value + return (...args: unknown[]) => { + const next = value.apply(object, args) + return next && typeof next === 'object' ? chain(next, index, starter) : next + } + }, + }) + return new Proxy(tx, { + get(object, property) { + const value = Reflect.get(object, property, object) + if (typeof property === 'string' && STATEMENT_STARTERS.has(property)) { + return (...args: unknown[]) => chain(value.apply(object, args), ++count, property) + } + return typeof value === 'function' ? value.bind(object) : value + }, + }) +} + +type StepRow = { id: string; status: string } + +async function cancelDatabase() { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const url = new URL(CONNECTION_URL) + const name = url.pathname.slice(1) + const session = (applicationName: string, max = 1) => + postgres(CONNECTION_URL, { + max, + connection: { application_name: applicationName, statement_timeout: 5_000 }, + }) + const admin = session('cs-admin') + const barrier = session('cs-barrier') + const locker = session('cs-locker') + const adapters: PostgresAdapter[] = [] + const inFlight: Promise[] = [] + let lockHolder: { release: () => void; done: Promise } | null = null + + const adapter = async (id: string) => { + const instance = new PostgresAdapter({ + connection: { + host: url.hostname, + port: Number(url.port), + database: name, + user: url.username, + password: url.password, + connection: { application_name: id, statement_timeout: 10_000 }, + }, + }) + instance.setId(id) + adapters.push(instance) + await instance.start() + return instance + } + + return { + admin, + adapter, + // Observes a call without rejecting and tracks it so cleanup awaits it after + // every gate has been released. + observe(promise: Promise): Promise> { + const settled = observe(promise) + inFlight.push(settled) + return settled + }, + // SELECT-only: the named sessions' current lock waits and their blockers. + async lockWaitBlockers(applicationName: string): Promise { + const rows = await admin` + SELECT a.wait_event_type, ARRAY( + SELECT b.application_name FROM pg_stat_activity b + WHERE b.pid = ANY(pg_blocking_pids(a.pid)) + ) AS blockers + FROM pg_stat_activity a + WHERE a.datname = current_database() AND a.application_name = ${applicationName} + AND a.wait_event_type = 'Lock'` + return rows.length > 0 ? (rows.flatMap((row) => row['blockers']) as string[]) : null + }, + // Resolves to the first of: the pending call settled, or its session waits on a lock. + async settledOrWaiting( + pending: Promise>, + applicationName: string, + ): Promise<{ outcome: 'settled' } | { outcome: 'waiting'; blockers: string[] }> { + let settled = false + void pending.then(() => (settled = true)) + let blockers: string[] | null = null + await eventually(async () => { + if (settled) return true + blockers = await this.lockWaitBlockers(applicationName) + return blockers !== null + }) + return settled ? { outcome: 'settled' } : { outcome: 'waiting', blockers: blockers! } + }, + async waitingAtAdvisory(applicationName: string): Promise { + await eventually(async () => { + const rows = await admin` + SELECT 1 FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid + WHERE l.locktype = 'advisory' AND NOT l.granted AND a.application_name = ${applicationName}` + return rows.length > 0 + }) + }, + async job(jobId: string) { + const active = + await admin`SELECT status, client_id, started_at FROM duron.jobs_active WHERE id = ${jobId}` + const archive = await admin` + SELECT status, client_id, started_at, finished_at, expires_at, error + FROM duron.jobs_archive WHERE id = ${jobId}` + return { active: active[0] ?? null, archive: archive[0] ?? null } + }, + async steps(jobId: string): Promise<{ active: StepRow[]; archive: StepRow[] }> { + const active = await admin` + SELECT id, status FROM duron.job_steps_active WHERE job_id = ${jobId} ORDER BY id` + const archive = await admin` + SELECT id, status FROM duron.job_steps_archive WHERE job_id = ${jobId} ORDER BY id` + return { active: [...active], archive: [...archive] } + }, + // Owned row lock on one step, held in an owned session until released. + async lockStepRow(stepId: string): Promise { + const locked = Promise.withResolvers() + const open = Promise.withResolvers() + const done = locker + .begin(async (sql) => { + await sql`SELECT id FROM duron.job_steps_active WHERE id = ${stepId} FOR UPDATE` + locked.resolve() + await open.promise + }) + .catch((error: unknown) => locked.reject(error)) + lockHolder = { release: () => open.resolve(), done } + await locked.promise + }, + async releaseStepRow(): Promise { + const holder = lockHolder + lockHolder = null + if (!holder) return + holder.release() + await holder.done + }, + // Owned test-only trigger: the named session's step INSERT waits on the barrier. + async installStepInsertBarrier(applicationName: string, stepName: string): Promise { + await admin.unsafe(` + CREATE FUNCTION duron.cs_step_insert_barrier() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF current_setting('application_name') = '${applicationName}' AND NEW.name = '${stepName}' THEN + PERFORM pg_advisory_xact_lock(${BARRIER_KEY}); + END IF; + RETURN NEW; + END $$; + CREATE TRIGGER cs_step_insert_barrier BEFORE INSERT ON duron.job_steps_active + FOR EACH ROW EXECUTE FUNCTION duron.cs_step_insert_barrier(); + `) + }, + // Owned test-only trigger: the named session's claim UPDATE waits on the + // barrier after its statement snapshot exists, before candidate locks. + async installClaimBarrier(applicationName: string): Promise { + await admin.unsafe(` + CREATE FUNCTION duron.cs_claim_barrier() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF current_setting('application_name') = '${applicationName}' THEN + PERFORM pg_advisory_xact_lock(${BARRIER_KEY}); + END IF; + RETURN NULL; + END $$; + CREATE TRIGGER cs_claim_barrier BEFORE UPDATE ON duron.jobs_active + FOR EACH STATEMENT EXECUTE FUNCTION duron.cs_claim_barrier(); + `) + }, + async hold(): Promise { + await barrier`SELECT pg_advisory_lock(${BARRIER_KEY})` + }, + async release(): Promise { + await barrier`SELECT pg_advisory_unlock_all()` + }, + // Drop only after fresh evidence of zero other sessions; otherwise retain and fail. + async cleanup(): Promise { + try { + lockHolder?.release() + await lockHolder?.done + await barrier`SELECT pg_advisory_unlock_all()`.catch(() => undefined) + const drained = await Promise.race([ + Promise.all(inFlight).then(() => true), + Bun.sleep(5_000).then(() => false), + ]) + if (!drained) throw new Error('Observed calls did not settle after release') + for (const instance of adapters) await instance.stop().catch(() => undefined) + await barrier.end({ timeout: 5 }) + await locker.end({ timeout: 5 }) + await eventually(async () => { + const rows = await admin` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid()` + return rows[0]!['count'] === 0 + }) + } catch (error) { + throw new Error(`Retained owned database ${name}`, { cause: error }) + } finally { + await admin.end({ timeout: 5 }) + } + await deleteDb() + }, + } +} + +type CancelDatabase = Awaited> + +let jobCounter = 0 + +async function createJob(adapter: PostgresAdapter, timeoutMs = 60_000): Promise { + const index = ++jobCounter + return (await adapter.createJob({ + queue: 'cancel-action', + groupKey: `cancel-group-${index}`, + input: { index }, + timeoutMs, + checksum: 'cancel-checksum', + concurrencyLimit: 100, + concurrencyStepLimit: 10, + }))! +} + +// Worker W claims a job and creates step s1 (left active unless completed). +async function claimedJobWithStep(w: PostgresAdapter, timeoutMs = 60_000, completeStep = false) { + const jobId = await createJob(w, timeoutMs) + const claimed = await w.fetch({ batch: 1 }) + expect(claimed.map((job) => job.id)).toEqual([jobId]) + const s1 = (await createStep(w, jobId, 's1'))! + expect(s1).not.toBeNull() + if (completeStep) expect(await w.completeJobStep({ stepId: s1.id, output: { s1: 1 } })).toBe(true) + return { jobId, s1: s1.id } +} + +function createStep(adapter: PostgresAdapter, jobId: string, name: string) { + return adapter.createOrRecoverJobStep({ jobId, name, timeoutMs: 60_000, retriesLimit: 0 }) +} + +// Keeps the primary test failure when cleanup also fails (and retains the database). +async function withDatabase(test: (db: CancelDatabase) => Promise): Promise { + const db = await cancelDatabase() + let failed = false + let failure: unknown + try { + await test(db) + } catch (error) { + failed = true + failure = error + } + try { + await db.cleanup() + } catch (cleanupError) { + if (!failed) throw cleanupError + // AggregateError keeps both the primary failure and the cleanup failure. + // oxlint-disable-next-line preserve-caught-error + throw new AggregateError([failure, cleanupError], 'Test failed and cleanup failed') + } + if (failed) throw failure +} + +// Recovery's requeue/expired archival lock the job row and then block on an +// owned step-row lock, so they hold the job while the stale call arrives. +async function recoveryHoldingJob(db: CancelDatabase, r: PostgresAdapter, s1: string) { + await db.lockStepRow(s1) + const recovery = db.observe(r.recoverJobs({ checksums: ['other-checksum'] })) + expect(await db.settledOrWaiting(recovery, 'r')).toEqual({ + outcome: 'waiting', + blockers: ['cs-locker'], + }) + // Wrapped so the async helper does not adopt (await) the held recovery. + return { recovery } +} + +const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip +suite('Native PostgreSQL cancellation storage', () => { + describe('step creation racing a cancellation (A/B/C)', () => { + const cases = [ + { name: 'A: paused before COMMIT (after DELETE)', pause: 'commit' as const }, + { name: 'B: paused after the step status UPDATE', pause: CANCEL_AFTER_STEP_UPDATE }, + { name: 'C: paused after the step archive copy', pause: CANCEL_AFTER_STEP_ARCHIVE }, + ] + for (const scenario of cases) { + it( + `rejects the racing creation with null and archives only committed steps (${scenario.name})`, + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const { jobId, s1 } = await claimedJobWithStep(w, 60_000, true) + const gate = gateNextTransaction(c, scenario.pause) + try { + const cancel = db.observe(c.cancelJob({ jobId })) + await gate.reached + const creation = db.observe(createStep(w, jobId, 's2')) + const observed = await db.settledOrWaiting(creation, 'w') + gate.release() + const created = fulfilment(await creation) + expect(fulfilment(await cancel)).toBe(true) + // Storage by row ID first: any step the creator reports must be archived cancelled. + const steps = await db.steps(jobId) + expect(steps.active).toEqual([]) + if (created) + expect(steps.archive).toContainEqual({ id: created.id, status: 'cancelled' }) + expect(steps.archive).toEqual([{ id: s1, status: 'cancelled' }]) + expect(created).toBeNull() + expect((await db.job(jobId)).archive?.['status']).toBe('cancelled') + // Native supplement: the creator waited on the cancelling transaction. + expect(observed).toEqual({ outcome: 'waiting', blockers: ['c'] }) + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + } + }) + + it( + 'G: makes a cancellation wait for a creator already holding the job, then archives its step cancelled', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const { jobId, s1 } = await claimedJobWithStep(w) + await db.installStepInsertBarrier('w', 'gated') + await db.hold() + let creation: Promise> | undefined + let cancel: Promise> | undefined + try { + creation = db.observe(createStep(w, jobId, 'gated')) + await db.waitingAtAdvisory('w') + cancel = db.observe(c.cancelJob({ jobId })) + const observed = await db.settledOrWaiting(cancel, 'c') + await db.release() + const step = fulfilment(await creation) as { id: string } | null + expect(step).not.toBeNull() + expect(fulfilment(await cancel)).toBe(true) + expect(observed).toEqual({ outcome: 'waiting', blockers: ['w'] }) + const steps = await db.steps(jobId) + expect(steps.active).toEqual([]) + expect(steps.archive).toHaveLength(2) + expect(steps.archive).toContainEqual({ id: s1, status: 'cancelled' }) + expect(steps.archive).toContainEqual({ id: step!.id, status: 'cancelled' }) + } finally { + await db.release() + await creation + await cancel + } + }) + }, + TEST_MS, + ) + + describe('status writes racing a cancellation (H, preserved)', () => { + it( + 'H1: a step completion before the step UPDATE succeeds and is then archived cancelled', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const { jobId, s1 } = await claimedJobWithStep(w) + const gate = gateNextTransaction(c, CANCEL_AFTER_LOCK) + try { + const cancel = db.observe(c.cancelJob({ jobId })) + await gate.reached + expect(fulfilment(await db.observe(w.completeJobStep({ stepId: s1, output: 1 })))).toBe( + true, + ) + gate.release() + expect(fulfilment(await cancel)).toBe(true) + expect(await db.steps(jobId)).toEqual({ + active: [], + archive: [{ id: s1, status: 'cancelled' }], + }) + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + it( + 'H2: a step completion after the step UPDATE waits and returns false', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const { jobId, s1 } = await claimedJobWithStep(w) + const gate = gateNextTransaction(c, CANCEL_AFTER_STEP_UPDATE) + try { + const cancel = db.observe(c.cancelJob({ jobId })) + await gate.reached + const completion = db.observe(w.completeJobStep({ stepId: s1, output: 1 })) + expect((await db.settledOrWaiting(completion, 'w')).outcome).toBe('waiting') + gate.release() + expect(fulfilment(await completion)).toBe(false) + expect(fulfilment(await cancel)).toBe(true) + expect(await db.steps(jobId)).toEqual({ + active: [], + archive: [{ id: s1, status: 'cancelled' }], + }) + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + }) + + it( + 'RB: a rolled-back cancellation releases a waiting creator and status write without archiving', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const { jobId, s1 } = await claimedJobWithStep(w) + const gate = gateNextTransaction(c, CANCEL_AFTER_STEP_UPDATE) + try { + const cancel = db.observe(c.cancelJob({ jobId })) + await gate.reached + const creation = db.observe(createStep(w, jobId, 's2')) + expect(await db.settledOrWaiting(creation, 'w')).toEqual({ + outcome: 'waiting', + blockers: ['c'], + }) + const completion = db.observe(w.completeJobStep({ stepId: s1, output: 1 })) + gate.fail(new Error('forced cancellation rollback')) + expect((rejection(await cancel) as Error).message).toBe('forced cancellation rollback') + const step = fulfilment(await creation) as { id: string } | null + expect(step).not.toBeNull() + expect(fulfilment(await completion)).toBe(true) + const job = await db.job(jobId) + expect(job.archive).toBeNull() + expect(job.active?.['status']).toBe('active') + expect((await db.steps(jobId)).archive).toEqual([]) + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + describe('competing terminators (I/I2)', () => { + const terminators = [ + { + name: 'completeJob', + run: (w: PostgresAdapter, jobId: string) => w.completeJob({ jobId, output: { ok: 1 } }), + }, + { + name: 'failJob', + run: (w: PostgresAdapter, jobId: string) => w.failJob({ jobId, error: { message: 'x' } }), + }, + ] + for (const terminator of terminators) { + for (const [label, pause] of [ + ['after its job lock', CANCEL_AFTER_LOCK], + ['after its step UPDATE', CANCEL_AFTER_STEP_UPDATE], + ] as const) { + it( + `I: a cancellation holding the job makes ${terminator.name} wait and return false (cancellation paused ${label})`, + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const { jobId, s1 } = await claimedJobWithStep(w) + const gate = gateNextTransaction(c, pause) + try { + const cancel = db.observe(c.cancelJob({ jobId })) + await gate.reached + const loser = db.observe(terminator.run(w, jobId)) + await db.settledOrWaiting(loser, 'w') + gate.release() + expect(fulfilment(await cancel)).toBe(true) + expect(fulfilment(await loser)).toBe(false) + expect((await db.job(jobId)).archive?.['status']).toBe('cancelled') + expect(await db.steps(jobId)).toEqual({ + active: [], + archive: [{ id: s1, status: 'cancelled' }], + }) + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + } + } + + it( + 'I: a completion holding the job makes the cancellation wait and return false', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const { jobId, s1 } = await claimedJobWithStep(w, 60_000, true) + const gate = gateNextTransaction(w, TERMINATE_AFTER_LOCK) + try { + const completion = db.observe(w.completeJob({ jobId, output: { ok: 1 } })) + await gate.reached + const cancel = db.observe(c.cancelJob({ jobId })) + await db.settledOrWaiting(cancel, 'c') + gate.release() + expect(fulfilment(await completion)).toBe(true) + expect(fulfilment(await cancel)).toBe(false) + expect((await db.job(jobId)).archive?.['status']).toBe('completed') + expect(await db.steps(jobId)).toEqual({ + active: [], + archive: [{ id: s1, status: 'completed' }], + }) + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + it( + 'I2: a second cancellation waits and returns false', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const c2 = await db.adapter('c2') + const { jobId } = await claimedJobWithStep(w) + const gate = gateNextTransaction(c, CANCEL_AFTER_LOCK) + try { + const first = db.observe(c.cancelJob({ jobId })) + await gate.reached + const second = db.observe(c2.cancelJob({ jobId })) + await db.settledOrWaiting(second, 'c2') + gate.release() + expect(fulfilment(await first)).toBe(true) + expect(fulfilment(await second)).toBe(false) + expect((await db.job(jobId)).archive?.['status']).toBe('cancelled') + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + it( + 'I2: deleting a created job held by a cancellation waits and returns false', + async () => { + await withDatabase(async (db) => { + const c = await db.adapter('c') + const d = await db.adapter('d') + const jobId = await createJob(c) + const gate = gateNextTransaction(c, CANCEL_AFTER_LOCK) + try { + const cancel = db.observe(c.cancelJob({ jobId })) + await gate.reached + const deletion = db.observe(d.deleteJob({ jobId })) + await db.settledOrWaiting(deletion, 'd') + gate.release() + expect(fulfilment(await cancel)).toBe(true) + expect(fulfilment(await deletion)).toBe(false) + expect((await db.job(jobId)).archive?.['status']).toBe('cancelled') + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + }) + + describe('SERIALIZABLE claims (J)', () => { + it( + 'J1: a claim skips a created job held by a cancellation', + async () => { + await withDatabase(async (db) => { + const c = await db.adapter('c') + const f = await db.adapter('f') + const jobId = await createJob(c) + const gate = gateNextTransaction(c, CANCEL_AFTER_LOCK) + try { + const cancel = db.observe(c.cancelJob({ jobId })) + await gate.reached + expect(fulfilment(await db.observe(f.fetch({ batch: 1 })))).toEqual([]) + gate.release() + expect(fulfilment(await cancel)).toBe(true) + const job = await db.job(jobId) + expect(job.active).toBeNull() + expect(job.archive?.['status']).toBe('cancelled') + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + it( + 'J2: a cancellation waits for an uncommitted claim and archives the latest claimed row', + async () => { + await withDatabase(async (db) => { + const c = await db.adapter('c') + const f = await db.adapter('f') + const jobId = await createJob(c) + const gate = gateNextTransaction(f, 'commit') + try { + const claim = db.observe(f.fetch({ batch: 1 })) + await gate.reached + const cancel = db.observe(c.cancelJob({ jobId })) + await db.settledOrWaiting(cancel, 'c') + gate.release() + expect(fulfilment(await claim).map((job) => job.id)).toEqual([jobId]) + expect(fulfilment(await cancel)).toBe(true) + const job = await db.job(jobId) + expect(job.archive?.['status']).toBe('cancelled') + expect(job.archive?.['client_id']).toBe('f') + expect(job.archive?.['started_at']).not.toBeNull() + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + it( + 'J3: a claim whose snapshot predates a committed cancellation rejects with 40001 and publishes nothing', + async () => { + await withDatabase(async (db) => { + const c = await db.adapter('c') + const f = await db.adapter('f') + const jobId = await createJob(c) + await db.installClaimBarrier('f') + await db.hold() + let claim: Promise> | undefined + try { + claim = db.observe(f.fetch({ batch: 1 })) + await db.waitingAtAdvisory('f') + expect(fulfilment(await db.observe(c.cancelJob({ jobId })))).toBe(true) + await db.release() + expect(sqlState(rejection(await claim))).toBe('40001') + const job = await db.job(jobId) + expect(job.active).toBeNull() + expect(job.archive?.['status']).toBe('cancelled') + } finally { + await db.release() + await claim + } + }) + }, + TEST_MS, + ) + }) + + it( + 'L: a bounded natural sample of creators, status writes and terminators keeps storage consistent', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + for (let iteration = 0; iteration < 10; iteration++) { + const { jobId, s1 } = await claimedJobWithStep(w) + const creators = Array.from({ length: 6 }, (_, index) => + db.observe(createStep(w, jobId, `l-${index}`)), + ) + const writes = [ + db.observe(w.completeJobStep({ stepId: s1, output: 1 })), + db.observe(w.completeJob({ jobId, output: { iteration } })), + ] + const cancel = db.observe(c.cancelJob({ jobId })) + const created = (await Promise.all(creators)).map(fulfilment) + const [, completion] = (await Promise.all(writes)).map(fulfilment) + const cancelled = fulfilment(await cancel) + expect([completion, cancelled].filter(Boolean)).toHaveLength(1) + const job = await db.job(jobId) + expect(job.active).toBeNull() + expect(job.archive?.['status']).toBe(cancelled ? 'cancelled' : 'completed') + const steps = await db.steps(jobId) + expect(steps.active).toEqual([]) + const archived = new Set(steps.archive.map((step) => step.id)) + for (const step of created) if (step) expect(archived.has(step.id)).toBe(true) + if (cancelled) { + expect(steps.archive.every((step) => step.status === 'cancelled')).toBe(true) + } + } + }) + }, + TEST_MS, + ) + + describe('latest-locked-row rechecks against recovery (R1/R2/R3/R3b)', () => { + it( + 'R1: a stale creator waiting on an unexpired requeue returns null', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w) + try { + const { recovery } = await recoveryHoldingJob(db, r, s1) + const creation = db.observe(createStep(w, jobId, 's2')) + expect(await db.settledOrWaiting(creation, 'w')).toEqual({ + outcome: 'waiting', + blockers: ['r'], + }) + await db.releaseStepRow() + expect(fulfilment(await recovery)).toBe(1) + const created = fulfilment(await creation) + expect((await db.job(jobId)).active?.['status']).toBe('created') + expect(await db.steps(jobId)).toEqual({ active: [], archive: [] }) + expect(created).toBeNull() + } finally { + await db.releaseStepRow() + } + }) + }, + TEST_MS, + ) + + for (const terminator of ['completeJob', 'failJob'] as const) { + it( + `R3: a stale ${terminator} waiting on an unexpired requeue returns false and the job can run again`, + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w) + try { + const { recovery } = await recoveryHoldingJob(db, r, s1) + const stale = db.observe( + terminator === 'completeJob' + ? w.completeJob({ jobId, output: 1 }) + : w.failJob({ jobId, error: { message: 'late' } }), + ) + expect((await db.settledOrWaiting(stale, 'w')).outcome).toBe('waiting') + await db.releaseStepRow() + expect(fulfilment(await recovery)).toBe(1) + expect(fulfilment(await stale)).toBe(false) + const job = await db.job(jobId) + expect(job.archive).toBeNull() + expect(job.active?.['status']).toBe('created') + expect((await r.fetch({ batch: 1 })).map((claimed) => claimed.id)).toEqual([jobId]) + } finally { + await db.releaseStepRow() + } + }) + }, + TEST_MS, + ) + } + + it( + 'R3: a completion that locks first wins and recovery skips the job', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId } = await claimedJobWithStep(w) + const gate = gateNextTransaction(w, TERMINATE_AFTER_LOCK) + try { + const completion = db.observe(w.completeJob({ jobId, output: 1 })) + await gate.reached + expect( + fulfilment(await db.observe(r.recoverJobs({ checksums: ['other-checksum'] }))), + ).toBe(0) + gate.release() + expect(fulfilment(await completion)).toBe(true) + expect((await db.job(jobId)).archive?.['status']).toBe('completed') + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + it( + 'R3b: a stale failJob waiting on expired archival returns false', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w, 500) + await Bun.sleep(600) + try { + const { recovery } = await recoveryHoldingJob(db, r, s1) + const stale = db.observe(w.failJob({ jobId, error: { message: 'late' } })) + expect((await db.settledOrWaiting(stale, 'w')).outcome).toBe('waiting') + await db.releaseStepRow() + expect(fulfilment(await recovery)).toBe(1) + expect(fulfilment(await stale)).toBe(false) + const job = await db.job(jobId) + expect(job.archive?.['status']).toBe('failed') + expect(job.archive?.['error']).toEqual({ + message: 'Job expired after exceeding timeout', + }) + } finally { + await db.releaseStepRow() + } + }) + }, + TEST_MS, + ) + + it( + 'R3b: a failJob that locks an expired job first wins and expired archival skips it', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId } = await claimedJobWithStep(w, 500) + await Bun.sleep(600) + const gate = gateNextTransaction(w, TERMINATE_AFTER_LOCK) + try { + const failure = db.observe(w.failJob({ jobId, error: { message: 'first' } })) + await gate.reached + expect( + fulfilment(await db.observe(r.recoverJobs({ checksums: ['other-checksum'] }))), + ).toBe(0) + gate.release() + expect(fulfilment(await failure)).toBe(true) + const job = await db.job(jobId) + expect(job.archive?.['status']).toBe('failed') + expect(job.archive?.['error']).toEqual({ message: 'first' }) + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + it( + 'R2: a completion that waits past expiry rechecks against its frozen BEGIN-time now()', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const c = await db.adapter('c') + const { jobId } = await claimedJobWithStep(w, 1_000) + const gate = gateNextTransaction(c, CANCEL_AFTER_LOCK) + try { + const cancel = db.observe(c.cancelJob({ jobId })) + await gate.reached + const completion = db.observe(w.completeJob({ jobId, output: 1 })) + expect(await db.settledOrWaiting(completion, 'w')).toEqual({ + outcome: 'waiting', + blockers: ['c'], + }) + await Bun.sleep(1_100) + gate.fail(new Error('forced cancellation rollback')) + rejection(await cancel) + // Characterization: the recheck uses the pre-wait reference, and the + // archived finish time is the pre-wait JavaScript timestamp. + expect(fulfilment(await completion)).toBe(true) + const job = await db.job(jobId) + expect(job.archive?.['status']).toBe('completed') + expect((job.archive!['finished_at'] as Date).getTime()).toBeLessThan( + (job.archive!['expires_at'] as Date).getTime(), + ) + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + }) +}) From 640f094d4afc5906bc6935c81c9b8f2128635511 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 16 Nov 2026 02:41:31 -0300 Subject: [PATCH 013/100] test: report session identities when prune transport count differs Keep the single post-loss pg_stat_activity observation, its predicate and expected count of 2. Select backend_type, application_name, backend_start and state, and attach phase, cut pid and rows to the failure message so a natural extra or missing session is self-attributing. No waits or polling. Diagnostic improvement only; the intermittent third-session finding stays open. --- packages/duron/test/prune-transport.test.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/duron/test/prune-transport.test.ts b/packages/duron/test/prune-transport.test.ts index 2cc71c2..864eedb 100644 --- a/packages/duron/test/prune-transport.test.ts +++ b/packages/duron/test/prune-transport.test.ts @@ -155,11 +155,12 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(reserves).toBe(1) expect(returns).toBe(0) expect(relay.sockets).toBe(0) - expect( - await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() - `, - ).toHaveLength(2) + // Same single observation; identity columns make an unexpected count self-attributing. + const sessions = await observer` + SELECT pid, backend_type, application_name, backend_start, state + FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + ` + expect(sessions, JSON.stringify({ phase, cutPid: pid, sessions })).toHaveLength(2) expect(await adapter.stop()).toBe(true) expect(returns).toBe(0) expect( From 9dc267f942775ee280b195a230ae1fdc03523fff Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 28 Nov 2026 18:39:46 -0300 Subject: [PATCH 014/100] test(postgres): bound and report native wait fixture cleanup Pending-safe independent finalization for the two real-PostgreSQL wait fixtures: either exact 57014 site for body readiness, first-nonzero identities, <=2s bounded zero, separate whole-target fresh zero before normal drop, primary preservation, 60s outer watchdog. Test-only; no driver or production change. --- .../duron/test/wait-native-fixture.test.ts | 1463 +++++++++++++++++ packages/duron/test/wait-native-fixture.ts | 915 +++++++++++ packages/duron/test/wait-native.test.ts | 227 ++- 3 files changed, 2559 insertions(+), 46 deletions(-) create mode 100644 packages/duron/test/wait-native-fixture.test.ts create mode 100644 packages/duron/test/wait-native-fixture.ts diff --git a/packages/duron/test/wait-native-fixture.test.ts b/packages/duron/test/wait-native-fixture.test.ts new file mode 100644 index 0000000..eb79377 --- /dev/null +++ b/packages/duron/test/wait-native-fixture.test.ts @@ -0,0 +1,1463 @@ +// Deterministic tests for the wait-native fixture helpers. Not gated on POSTGRES_TEST: they use a +// virtual clock and fake operations only. They never provision, connect to or query PostgreSQL. +// Reference controls labelled "source-derived" re-encode the behaviour of the accepted +// 5c29001:packages/duron/test/wait-native.test.ts (file SHA-256 3920b4ef…) to show the defects. + +import { describe, expect, it } from 'bun:test' + +import { + type Clock, + FixtureBody, + FixtureBodyAborted, + FixtureBodyTimeout, + type FinalizeInput, + FIXTURE_CAPS, + FixtureCleanupError, + FixtureObservationTimeout, + observe, + awaitLockGate, + finalizeNativeFixture, + throwFixtureOutcome, + isStatementTimeoutLog, + lockReadyWithStatementTimeout, + statementTimeoutObserved, +} from './wait-native-fixture.js' + +// --------------------------------------------------------------------------------------------- +// Virtual scheduler: timers fire one at a time in due-time order (then creation order), with the +// whole microtask queue drained between firings. Pending work with no timer left is a deadlock. +// --------------------------------------------------------------------------------------------- + +const drain = () => new Promise((resolve) => setImmediate(resolve)) +const never = () => new Promise(() => undefined) + +function virtualScheduler() { + let now = 0 + let sequence = 0 + const timers: { due: number; sequence: number; fire: () => void; cancelled: boolean }[] = [] + const clock: Clock = { + now: () => now, + timer(ms) { + let fire!: () => void + const promise = new Promise((resolve) => { + fire = resolve + }) + const entry = { due: now + Math.max(0, ms), sequence: sequence++, fire, cancelled: false } + timers.push(entry) + return { + promise, + cancel: () => { + entry.cancelled = true + }, + } + }, + } + // Resolves (or rejects) with `value` once virtual time reaches now + ms. + const after = (ms: number, value: () => T): Promise => + clock.timer(ms).promise.then(() => value()) + async function run(work: Promise): Promise { + let outcome: { ok: true; value: T } | { ok: false; error: unknown } | undefined + work.then( + (value) => (outcome = { ok: true, value }), + (error: unknown) => (outcome = { ok: false, error }), + ) + for (;;) { + await drain() + if (outcome) break + const live = timers + .filter((t) => !t.cancelled) + .toSorted((a, b) => a.due - b.due || a.sequence - b.sequence) + const next = live[0] + if (!next) throw new Error('virtual deadlock: work pending with no timers') + timers.splice(timers.indexOf(next), 1) + now = Math.max(now, next.due) + next.fire() + } + if (!outcome.ok) throw outcome.error + return outcome.value + } + return { + clock, + after, + never, + run, + // Synchronous clock jump without firing timers (models a delayed timer reaction). + jump: (ms: number) => { + now += ms + }, + liveTimers: () => timers.filter((t) => !t.cancelled).length, + } +} + +const statementTimeout = () => + Object.assign(new Error('Failed query: select "status" from "duron"."jobs_active"'), { + cause: Object.assign(new Error('canceling statement due to statement timeout'), { + code: '57014', + }), + }) +const adapterLog = (error: unknown = statementTimeout()) => [ + error, + 'Error in Adapter.getJobStatus()', +] +const waitFailedLog = (error: unknown = statementTimeout()) => [ + { error, jobId: 'job', trigger: 'initial', stage: 'status', affected: {}, late: false }, + '[Duron] Wait read failed', +] + +// Source-derived reference: accepted slow-SQL readiness `JSON.stringify(errors).includes('57014')`. +const acceptedReadiness = (errors: unknown[]) => JSON.stringify(errors).includes('57014') + +describe('57014 evidence (S1)', () => { + it('accepts the raw adapter wrapper Error and the wait-manager failure error', () => { + expect(isStatementTimeoutLog(adapterLog())).toBe(true) + expect(isStatementTimeoutLog(waitFailedLog())).toBe(true) + }) + + it('rejects text, job IDs, text-only Errors and non-Error code objects', () => { + const rejected: unknown[][] = [ + [{ jobId: '57014-abcd', note: '57014' }, '[Duron] Wait read failed'], + ['57014', 'Error in Adapter.getJobStatus()'], + [new Error('canceling 57014 statement'), 'Error in Adapter.getJobStatus()'], + [{ code: '57014' }, 'Error in Adapter.getJobStatus()'], + waitFailedLog({ code: '57014' }), + waitFailedLog({ message: 'statement timeout 57014' }), + [statementTimeout(), 'Error in Adapter.getJobById()'], + [statementTimeout()], + [...adapterLog(), 'extra'], + [ + Object.assign(new Error('x'), { cause: Object.assign(new Error('y'), { code: '40001' }) }), + 'Error in Adapter.getJobStatus()', + ], + ] + for (const args of rejected) expect(isStatementTimeoutLog(args)).toBe(false) + }) + + it('tolerates cyclic, deep and throwing evidence without accepting it', () => { + const cyclic = new Error('a') as Error & { cause?: unknown } + cyclic.cause = cyclic + const deep = [1, 2, 3, 4, 5, 6].reduce( + (inner) => Object.assign(new Error('wrap'), { cause: inner }), + Object.assign(new Error('root'), { code: '57014' }), + ) + const trap = new Error('trap') + Object.defineProperty(trap, 'cause', { + get() { + throw new Error('getter') + }, + }) + const fieldsTrap = {} + Object.defineProperty(fieldsTrap, 'error', { + get() { + throw new Error('getter') + }, + }) + expect(isStatementTimeoutLog(adapterLog(cyclic))).toBe(false) + expect(isStatementTimeoutLog(adapterLog(deep))).toBe(false) + expect(isStatementTimeoutLog(adapterLog(trap))).toBe(false) + expect(isStatementTimeoutLog([fieldsTrap, '[Duron] Wait read failed'])).toBe(false) + }) + + it('table-lock readiness needs native Lock 0 AND real evidence from either site', () => { + expect(lockReadyWithStatementTimeout(0, [])).toBe(false) + expect(lockReadyWithStatementTimeout(1, [adapterLog()])).toBe(false) + expect(lockReadyWithStatementTimeout('0', [adapterLog()])).toBe(false) + expect(lockReadyWithStatementTimeout(0, [adapterLog()])).toBe(true) + expect(lockReadyWithStatementTimeout(0, [waitFailedLog()])).toBe(true) + }) + + it('slow-SQL readiness ignores a job ID that merely contains 57014 (old text check accepted it)', () => { + const uuidLog = [{ jobId: 'a57014b2-0000-4000-8000-000000000000' }, '[Duron] Wait read expired'] + expect(acceptedReadiness([uuidLog[0]])).toBe(true) + expect(statementTimeoutObserved([uuidLog])).toBe(false) + expect(statementTimeoutObserved([uuidLog, waitFailedLog()])).toBe(true) + }) +}) + +describe('virtual scheduler (test utility)', () => { + it('fires timers in due-time order regardless of registration order, honouring cancellation', async () => { + const vs = virtualScheduler() + const order: string[] = [] + const late = vs.clock.timer(22_000) + void late.promise.then(() => order.push('22s')) + const early = vs.after(20_000, () => order.push('20s')) + const cancelled = vs.clock.timer(10_000) + void cancelled.promise.then(() => order.push('cancelled')) + cancelled.cancel() + await vs.run(early) + expect(order).toEqual(['20s']) + expect(vs.clock.now()).toBe(20_000) + await vs.run(late.promise) + expect(order).toEqual(['20s', '22s']) + }) + + it('reports a deadlock instead of hanging', async () => { + const vs = virtualScheduler() + expect(await vs.run(vs.never()).catch((error: Error) => error.message)).toBe( + 'virtual deadlock: work pending with no timers', + ) + }) +}) + +describe('bounded body steps (S0)', () => { + it('returns values and rethrows the original error identity, including undefined', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 20_000) + expect(await vs.run(body.step('value', () => vs.after(5, () => 7)))).toBe(7) + const failure = new Error('original') + expect( + await vs.run(body.step('reject', () => Promise.reject(failure))).catch((e: unknown) => e), + ).toBe(failure) + let thrown: unknown = 'not thrown' + await vs.run( + body + .step('undefined', () => Promise.reject(undefined)) + .catch((e: unknown) => { + thrown = e + }), + ) + expect(thrown).toBeUndefined() + expect(body.aborted).toBe(false) + }) + + it('a pending step expires at the body deadline, aborts the body and later steps never start', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 20_000) + let laterStarted = 0 + const error = await vs.run( + (async () => { + await body.step('holding', () => vs.never()) + await body.step('inherited timeout', () => { + laterStarted++ + return 1 + }) + })().catch((e: unknown) => e), + ) + expect(error).toBeInstanceOf(FixtureBodyTimeout) + expect((error as FixtureBodyTimeout).step).toBe('holding') + expect(vs.clock.now()).toBe(20_000) + expect(laterStarted).toBe(0) + expect(body.aborted).toBe(true) + expect(body.record().pending).toEqual(['holding']) + const refused = await body + .step('after abort', () => { + laterStarted++ + return 1 + }) + .catch((e: unknown) => e) + expect(refused).toBeInstanceOf(FixtureBodyAborted) + expect(laterStarted).toBe(0) + }) + + it('an eventually-style loop stops issuing queries once its pending query expires the body', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 20_000) + let queries = 0 + // Model of the unchanged cooperative eventually(check, 500): the check issues one native + // query per iteration through body.step. A pending query cannot be bounded by the 500ms + // parameter (cooperative), only by the body deadline. + const loop = async () => { + const end = vs.clock.now() + 500 + while (!(await body.step('lock-wait query', () => (queries++, vs.never())))) { + if (vs.clock.now() >= end) throw new Error('exceeded') + await vs.after(5, () => undefined) + } + } + const error = await vs.run(loop().catch((e: unknown) => e)) + expect(error).toBeInstanceOf(FixtureBodyTimeout) + expect(queries).toBe(1) + expect(vs.clock.now()).toBe(20_000) + }) + + it('checks the deadline at settlement: a result consumed after the bound fails', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 2_000) + const error = await vs.run( + body + .step('late zero', async () => { + vs.jump(2_100) // clock passes the bound before the bound timer reaction runs + return 0 + }) + .catch((e: unknown) => e), + ) + expect(error).toBeInstanceOf(FixtureBodyTimeout) + expect(body.record().pending).toEqual([]) + expect(body.record().late).toEqual([ + expect.objectContaining({ step: 'late zero', status: 'ok', kind: 'settled-after-bound' }), + ]) + }) + + it('records a late settlement of a pending step after the body expired', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 1_000) + const slow = vs.after(3_000, () => 'eventually') + await vs.run(body.step('client.start', () => slow).catch(() => undefined)) + await vs.run(slow) + await vs.run(vs.after(0, () => undefined)) + expect(body.record().late).toEqual([ + expect.objectContaining({ step: 'client.start', status: 'ok', at: 3_000 }), + ]) + }) + + it('a step started after the deadline already passed never calls its start function', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 100) + vs.jump(150) + let started = 0 + const error = await body.step('getJobStatus', () => (started++, 1)).catch((e: unknown) => e) + expect(error).toBeInstanceOf(FixtureBodyTimeout) + expect(started).toBe(0) + }) +}) + +describe('bounded lock gate (S2)', () => { + it('resolves once the lock is acquired before the bound', async () => { + const vs = virtualScheduler() + const locked = vs.after(30, () => undefined) + await vs.run(awaitLockGate({ clock: vs.clock, locked, holding: vs.never(), boundMs: 5_000 })) + expect(vs.clock.now()).toBe(30) + }) + + it('fails with the real cause when holding rejects before the lock', async () => { + const vs = virtualScheduler() + const begin = new Error('BEGIN failed') + const holding = vs.after(10, () => Promise.reject(begin)) + const error = (await vs + .run(awaitLockGate({ clock: vs.clock, locked: vs.never(), holding, boundMs: 5_000 })) + .catch((e: unknown) => e)) as Error + expect(error.message).toContain('settled before acquiring the table lock') + expect(error.cause).toBe(begin) + }) + + it('fails when holding resolves before the lock (unexpected settlement)', async () => { + const vs = virtualScheduler() + const holding = vs.after(10, () => 'committed') + const error = (await vs + .run(awaitLockGate({ clock: vs.clock, locked: vs.never(), holding, boundMs: 5_000 })) + .catch((e: unknown) => e)) as Error + expect(error.message).toContain('settled before acquiring the table lock') + }) + + it('is bounded: neither lock nor holding settles -> fails at exactly the bound', async () => { + const vs = virtualScheduler() + const error = (await vs + .run( + awaitLockGate({ clock: vs.clock, locked: vs.never(), holding: vs.never(), boundMs: 5_000 }), + ) + .catch((e: unknown) => e)) as Error + expect(error.message).toContain('5000ms') + expect(vs.clock.now()).toBe(5_000) + }) + + it('observes a holding rejection that arrives after the gate passed (no unhandled rejection)', async () => { + const vs = virtualScheduler() + const holding = vs.after(50, () => Promise.reject(new Error('late COMMIT failure'))) + await vs.run( + awaitLockGate({ clock: vs.clock, locked: Promise.resolve(), holding, boundMs: 5_000 }), + ) + // No handler is attached here: only the gate's own observation prevents an unhandled + // rejection, which Bun would report as a test error. + await vs.run(vs.after(100, () => undefined)) + }) +}) + +// --------------------------------------------------------------------------------------------- +// Finalizer (S3) +// --------------------------------------------------------------------------------------------- + +type Scheduler = ReturnType +const zeroRow = (): { count: number; sampled_at: string; sessions: unknown[] } => ({ + count: 0, + sampled_at: 't', + sessions: [], +}) +const nonzeroRow = (pid = 42) => ({ count: 1, sampled_at: 't', sessions: [{ pid, state: 'idle' }] }) + +function harness(vs: Scheduler, overrides: Partial = {}) { + const calls: string[] = [] + const reports: string[] = [] + const observer = { + fresh: async () => (calls.push('fresh'), zeroRow()), + catalogHas: async () => (calls.push('catalog'), true), + close: async () => { + calls.push('observer.close') + }, + } + const input: FinalizeInput = { + clock: vs.clock, + deadline: 54_000, + database: 'owned_db', + primary: undefined, + release: () => { + calls.push('release') + }, + holding: Promise.resolve(), + stop: async () => { + calls.push('stop') + }, + endBlocker: async () => { + calls.push('blocker') + }, + sample: async () => (calls.push('sample'), zeroRow()), + endAdmin: async () => { + calls.push('admin') + }, + openObserver: () => (calls.push('observer.open'), observer), + drop: async () => { + calls.push('drop') + }, + report: (line) => { + calls.push('report') + reports.push(line) + }, + ...overrides, + } + return { input, calls, reports, observer } +} + +const failureSteps = (outcome: Awaited>) => + outcome.failures.map((f) => f.step) + +describe('finalizer ordering, success and primary preservation (S3)', () => { + it('clean case: original order, strict fresh zero before drop, observer closed, silent', async () => { + const vs = virtualScheduler() + const h = harness(vs) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(h.calls).toEqual([ + 'release', + 'stop', + 'blocker', + 'sample', + 'admin', + 'observer.open', + 'fresh', + 'drop', + 'observer.close', + ]) + expect(outcome.boundary).toBe('original') + expect(outcome.dropState).toBe('confirmed') + expect(outcome.dropped).toBe(true) + expect(h.reports).toEqual([]) + expect(() => throwFixtureOutcome(outcome)).not.toThrow() + }) + + it('releases the JS gate before awaiting holding', async () => { + const vs = virtualScheduler() + let release!: () => void + const holding = new Promise((resolve) => { + release = resolve + }) + const h = harness(vs, { holding, release: () => release() }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures).toEqual([]) + expect(vs.clock.now()).toBe(0) + }) + + it('a 20s successful stop is supported (the diagnostic 6s ceiling is not a contract)', async () => { + const vs = virtualScheduler() + const h = harness(vs, { stop: () => vs.after(20_000, () => true) }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures).toEqual([]) + expect(outcome.dropState).toBe('confirmed') + expect(vs.clock.now()).toBe(20_000) + }) + + it('rethrows a sole primary with identical identity, including undefined and falsy values', async () => { + for (const value of [new Error('primary'), undefined, 0, '']) { + const vs = virtualScheduler() + const h = harness(vs, { primary: { value } }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + let thrown: unknown = 'nothing' + try { + throwFixtureOutcome(outcome) + } catch (error) { + thrown = error + } + expect(Object.is(thrown, value)).toBe(true) + expect(h.calls).not.toContain('drop') + expect(outcome.dropState).toBe('not-started:primary failure') + // DB identity and drop state are reported separately, never written onto the primary. + expect(h.reports.at(-1)).toContain('owned_db') + } + }) + + it('primary plus cleanup failures: AggregateError with the primary first and labelled steps', async () => { + const vs = virtualScheduler() + const primary = new Error('body failure') + const stopError = new Error('stop failed') + const h = harness(vs, { + primary: { value: primary }, + stop: async () => { + throw stopError + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + let thrown: unknown + try { + throwFixtureOutcome(outcome) + } catch (error) { + thrown = error + } + expect(thrown).toBeInstanceOf(AggregateError) + const errors = (thrown as AggregateError).errors + expect(errors[0]).toBe(primary) + expect(errors[1]).toBeInstanceOf(FixtureCleanupError) + expect((errors[1] as FixtureCleanupError).step).toBe('client.stop') + expect((errors[1] as FixtureCleanupError).cause).toBe(stopError) + expect((errors[1] as FixtureCleanupError).database).toBe('owned_db') + expect((thrown as AggregateError).message).toContain('owned_db') + expect(primary.message).toBe('body failure') + }) + + it('a sole cleanup failure is thrown labelled, with the original cause', async () => { + const vs = virtualScheduler() + const adminError = new Error('admin end failed') + const h = harness(vs, { + endAdmin: async () => { + throw adminError + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + let thrown: unknown + try { + throwFixtureOutcome(outcome) + } catch (error) { + thrown = error + } + expect(thrown).toBeInstanceOf(FixtureCleanupError) + expect((thrown as FixtureCleanupError).cause).toBe(adminError) + expect(h.calls).not.toContain('drop') + }) +}) + +describe('finalizer under rejection (S3)', () => { + for (const step of ['stop', 'endBlocker', 'sample', 'endAdmin'] as const) { + it(`${step} rejects: later independent steps still run and nothing is dropped`, async () => { + const vs = virtualScheduler() + const h = harness(vs) + const original = h.input[step]! + h.input[step] = (async () => { + await original() + throw new Error(`${step} failed`) + }) as never + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(h.calls).toEqual(expect.arrayContaining(['stop', 'blocker', 'sample', 'admin'])) + expect(h.calls).not.toContain('drop') + expect(outcome.failures).toHaveLength(1) + expect(outcome.dropped).toBe(false) + }) + } + + it('a holding rejection is a failure (not swallowed): cause kept, no drop', async () => { + const vs = virtualScheduler() + const holdingError = new Error('holder transaction failed') + const holding = Promise.reject(holdingError) + holding.catch(() => undefined) + const h = harness(vs, { holding }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['holding']) + expect(outcome.failures[0]!.error).toBe(holdingError) + expect(outcome.boundary).not.toBe('original') + expect(h.calls).not.toContain('drop') + expect(h.calls).toEqual(expect.arrayContaining(['stop', 'blocker', 'sample', 'admin'])) + }) + + it('a holding rejection identical to the primary is kept once (primary not erased)', async () => { + const vs = virtualScheduler() + const holdingError = new Error('holder transaction failed') + const holding = Promise.reject(holdingError) + holding.catch(() => undefined) + const h = harness(vs, { holding, primary: { value: holdingError } }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures[0]).toMatchObject({ step: 'holding', duplicateOfPrimary: true }) + let thrown: unknown + try { + throwFixtureOutcome(outcome) + } catch (error) { + thrown = error + } + expect(thrown).toBe(holdingError) + }) + + it('a holding rejection already carried as the lock-gate primary cause is not repeated', async () => { + const vs = virtualScheduler() + const holdingError = new Error('BEGIN failed') + const holding = Promise.reject(holdingError) + holding.catch(() => undefined) + const gateError = new Error('Blocker transaction settled before acquiring the table lock', { + cause: holdingError, + }) + const h = harness(vs, { holding, primary: { value: gateError } }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures).toEqual([ + expect.objectContaining({ step: 'holding', error: holdingError, duplicateOfPrimary: true }), + ]) + let thrown: unknown + try { + throwFixtureOutcome(outcome) + } catch (error) { + thrown = error + } + expect(thrown).toBe(gateError) + expect(h.calls).not.toContain('drop') + }) + + it('internal faults (release, openObserver, invalid snapshot) never skip later obligations', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + release: () => { + throw new Error('release threw') + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(h.calls).toEqual(expect.arrayContaining(['stop', 'blocker', 'sample', 'admin'])) + expect(failureSteps(outcome)).toContain('release') + expect(h.calls).not.toContain('drop') + + const vs2 = virtualScheduler() + const h2 = harness(vs2, { + openObserver: () => { + throw new Error('observer construction failed') + }, + }) + const outcome2 = await vs2.run(finalizeNativeFixture(h2.input)) + expect(failureSteps(outcome2)).toEqual(['observer.open']) + expect(h2.calls).toContain('admin') + expect(h2.calls).not.toContain('drop') + + const vs3 = virtualScheduler() + const h3 = harness(vs3, { sample: async () => ({ count: '0' }) }) + const outcome3 = await vs3.run(finalizeNativeFixture(h3.input)) + expect(failureSteps(outcome3)).toEqual(['first sample']) + expect(h3.calls).toContain('admin') + expect(h3.calls).not.toContain('drop') + }) +}) + +describe('finalizer under pending work (S3)', () => { + const pendingCases: [keyof FinalizeInput, string, number][] = [ + ['holding', 'holding', 3_000], + ['stop', 'client.stop', 22_000], + ['endBlocker', 'blocker.end', 6_000], + ['sample', 'first sample', 2_500], + ['endAdmin', 'admin.end', 6_000], + ] + for (const [key, step, cap] of pendingCases) { + it(`${step} never settles: bounded at ${cap}ms, later obligations still start, no drop`, async () => { + const vs = virtualScheduler() + const h = harness(vs) + if (key === 'holding') h.input.holding = vs.never() + else + (h.input as unknown as Record)[key] = () => { + h.calls.push(`${step} (pending)`) + return vs.never() + } + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual([step]) + expect(outcome.steps.find((s) => s.step === step)).toMatchObject({ + status: 'expired', + boundMs: cap, + }) + // Every independent obligation was started exactly once (normally or as the pending one). + for (const [normal, pending] of [ + ['stop', 'client.stop (pending)'], + ['blocker', 'blocker.end (pending)'], + ['sample', 'first sample (pending)'], + ['admin', 'admin.end (pending)'], + ]) { + expect(h.calls.filter((c) => c === normal || c === pending)).toHaveLength(1) + } + expect(h.calls[0]).toBe('release') + expect(h.calls).not.toContain('drop') + if (['holding', 'client.stop', 'blocker.end'].includes(step)) { + expect(outcome.boundary).not.toBe('original') + } + }) + } + + it('stop beyond its 22s observation fails and retains; its late success is recorded', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + stop: () => vs.after(23_000, () => true), + endBlocker: () => vs.after(2_000, () => undefined), + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['client.stop']) + expect(outcome.late).toEqual([ + expect.objectContaining({ step: 'client.stop', status: 'ok', at: 23_000 }), + ]) + expect(outcome.dropState).toBe('not-started:cleanup failure') + }) + + it('an exhausted deadline still starts every close, with zero-length observation', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + deadline: 1_000, + stop: () => (h.calls.push('stop'), vs.never()), + endBlocker: () => (h.calls.push('blocker'), vs.never()), + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(h.calls).toEqual(expect.arrayContaining(['stop', 'blocker', 'sample', 'admin'])) + expect(failureSteps(outcome)).toEqual(['client.stop', 'blocker.end']) + expect(h.calls).not.toContain('drop') + }) + + it('checks the deadline at settlement: a sample consumed after its bound fails', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + sample: async () => { + vs.jump(2_600) // passes the 2.5s bound before the bound timer reaction runs + return zeroRow() + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['first sample']) + expect(outcome.steps.find((s) => s.step === 'first sample')!.status).toBe('expired') + expect(outcome.late).toEqual([ + expect.objectContaining({ step: 'first sample', status: 'ok', kind: 'settled-after-bound' }), + ]) + expect(h.calls).not.toContain('drop') + }) +}) + +describe('bounded zero and reporting (S3)', () => { + it('transient nonzero reaching zero inside 2s: report BEFORE drop, then strict fresh zero and drop', async () => { + const vs = virtualScheduler() + const rows = [nonzeroRow(7), nonzeroRow(7), zeroRow()] + const h = harness(vs, { sample: async () => (h.calls.push('sample'), rows.shift()!) }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures).toEqual([]) + expect(outcome.first!.count).toBe(1) + expect(outcome.zeroReached).toBe(true) + expect(h.calls.indexOf('report')).toBeGreaterThan(h.calls.indexOf('admin')) + expect(h.calls.indexOf('report')).toBeLessThan(h.calls.indexOf('drop')) + const report = JSON.parse(h.reports[0]!.replace(/^\[wait-native-fixture\] /, '')) + expect(report).toMatchObject({ + event: 'first-nonzero', + database: 'owned_db', + zeroReached: true, + }) + expect(report.first.sessions).toEqual([{ pid: 7, state: 'idle' }]) + expect(JSON.stringify(report)).not.toContain('benign') + }) + + it('persistent nonzero: bounded-zero failure within 2s with first/last identities; no drop', async () => { + const vs = virtualScheduler() + const h = harness(vs, { sample: async () => (h.calls.push('sample'), nonzeroRow(9)) }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['bounded zero']) + expect(vs.clock.now()).toBeLessThanOrEqual(2_000) + expect(outcome.followups.length).toBeGreaterThan(1) + expect(h.calls).toContain('admin') + expect(h.calls).not.toContain('drop') + expect(h.reports[0]).toContain('"event":"first-nonzero"') + expect(h.reports.at(-1)).toContain('"event":"fixture-cleanup"') + }) + + it('a follow-up that advances past the 2s window and returns zero does NOT pass', async () => { + const vs = virtualScheduler() + let calls = 0 + const h = harness(vs, { + sample: async () => { + calls++ + if (calls === 1) return nonzeroRow() + vs.jump(2_100) + return zeroRow() + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + // v2: the late observation is its own failure; the summary does not claim sessions persisted. + expect(failureSteps(outcome)).toEqual(['bounded zero sample', 'bounded zero']) + expect(outcome.zeroReached).toBe(false) + expect(h.calls).not.toContain('drop') + }) + + it('a pending follow-up query is bounded by the remaining 2s window', async () => { + const vs = virtualScheduler() + let calls = 0 + const h = harness(vs, { + sample: () => (++calls === 1 ? Promise.resolve(nonzeroRow()) : vs.never()), + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['bounded zero sample', 'bounded zero']) + expect(vs.clock.now()).toBe(2_000) + expect(h.calls).toContain('admin') + }) + + it('a failed first-nonzero report is a fixture failure and prevents the drop', async () => { + const vs = virtualScheduler() + const rows = [nonzeroRow(), zeroRow()] + const h = harness(vs, { + sample: async () => rows.shift()!, + report: () => { + throw new Error('stderr closed') + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['report first-nonzero', 'report final']) + expect(h.calls).not.toContain('drop') + expect(h.calls).toContain('admin') + }) + + it('hostile session values are serialized safely and do not bypass cleanup', async () => { + const vs = virtualScheduler() + const hostile: Record = { big: 10n } + hostile['self'] = hostile + Object.defineProperty(hostile, 'trap', { + enumerable: true, + get() { + throw new Error('getter') + }, + }) + const rows = [{ count: 1, sampled_at: 't', sessions: [hostile] }, zeroRow()] + const h = harness(vs, { sample: async () => rows.shift()! }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures).toEqual([]) + expect(h.reports[0]).toContain('[circular]') + expect(h.calls).toContain('drop') + }) +}) + +describe('strict fresh zero and honest drop states (S3)', () => { + it('observer sees the target nonzero for the whole window: no drop, observer still closed', async () => { + const vs = virtualScheduler() + const h = harness(vs) + h.observer.fresh = async () => (h.calls.push('fresh'), nonzeroRow()) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['fresh zero']) + expect(outcome.dropState).toBe('not-started:fresh zero not observed') + expect(h.calls).not.toContain('drop') + expect(h.calls.at(-2)).toBe('observer.close') + }) + + it('target departs within the fresh window: drop proceeds', async () => { + const vs = virtualScheduler() + const h = harness(vs) + const rows = [nonzeroRow(), zeroRow()] + h.observer.fresh = async () => rows.shift()! + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures).toEqual([]) + expect(outcome.fresh).toHaveLength(2) + expect(outcome.dropState).toBe('confirmed') + }) + + it('pending fresh query: bounded, observer closed, no drop', async () => { + const vs = virtualScheduler() + const h = harness(vs) + h.observer.fresh = () => vs.never() + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['fresh zero sample', 'fresh zero']) + expect(h.calls).toContain('observer.close') + expect(h.calls).not.toContain('drop') + }) + + it('a generic drop error is unknown (never "retained"), with catalog presence recorded', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + drop: async () => { + throw new Error('Command failed: docker exec dropdb: connection lost') + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.dropState).toBe('unknown:error; catalog present at 0ms') + expect(outcome.dropped).toBe(false) + expect(failureSteps(outcome)).toEqual(['deleteDb']) + }) + + it('positive refusal text is "refused"; catalog absence is observed, not our confirmed drop', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + drop: async () => { + throw new Error('dropdb: error: database "owned_db" is being accessed by other users') + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.dropState).toBe('refused; catalog present at 0ms') + + const vs2 = virtualScheduler() + const h2 = harness(vs2, { + drop: async () => { + throw new Error('Command failed: unexpected EOF') + }, + }) + h2.observer.catalogHas = async () => false + const outcome2 = await vs2.run(finalizeNativeFixture(h2.input)) + expect(outcome2.dropState).toBe('unknown:error; catalog absent at 0ms') + expect(outcome2.dropped).toBe(false) + }) + + it('a drop timeout is unknown:timeout; its late fulfillment before the report is reflected', async () => { + const vs = virtualScheduler() + const h = harness(vs, { drop: () => vs.after(9_000, () => undefined) }) + h.observer.close = () => vs.after(2_000, () => undefined) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.dropState).toBe( + 'unknown:timeout; catalog present at 8000ms; our drop confirmed late at 9000ms', + ) + expect(outcome.late).toEqual([ + expect.objectContaining({ step: 'deleteDb', status: 'ok', kind: 'late', at: 9_000 }), + ]) + expect(failureSteps(outcome)).toEqual(['deleteDb']) + }) + + it('confirmed drop followed by observer-close failure keeps the dropped state', async () => { + const vs = virtualScheduler() + const h = harness(vs) + h.observer.close = async () => { + throw new Error('observer end failed') + } + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.dropState).toBe('confirmed') + expect(outcome.dropped).toBe(true) + expect(failureSteps(outcome)).toEqual(['observer.close']) + expect(h.reports.at(-1)).toContain('"dropState":"confirmed"') + }) + + it('insufficient budget: no fresh-zero observer, or no drop start, and the DB is retained', async () => { + const vs = virtualScheduler() + const h = harness(vs, { deadline: 7_999 }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.dropState).toBe('not-started:insufficient budget') + expect(h.calls).not.toContain('observer.open') + + const vs2 = virtualScheduler() + const h2 = harness(vs2, { deadline: 13_999 }) + const outcome2 = await vs2.run(finalizeNativeFixture(h2.input)) + expect(outcome2.dropState).toBe('not-started:insufficient budget') + expect(h2.calls).toContain('fresh') + expect(h2.calls).not.toContain('drop') + expect(h2.calls).toContain('observer.close') + + const vs3 = virtualScheduler() + const h3 = harness(vs3, { deadline: 14_000 }) + expect((await vs3.run(finalizeNativeFixture(h3.input))).dropState).toBe('confirmed') + }) +}) + +// Source: 5c29001:packages/duron/test/wait-native.test.ts lines 182-192. Re-encodes the accepted +// finalizer order and semantics over the same fakes. +const acceptedFinally = async (o: FinalizeInput) => { + o.release?.() + await o.holding?.catch(() => undefined) + await o.stop() + await o.endBlocker?.() + const remaining = (await o.sample()) as { count: number } + if (remaining.count !== 0) + throw new Error(`expect(received).toBe(0): received ${remaining.count}`) + await o.endAdmin() + await o.drop() +} + +describe('source-derived reference: the accepted sequential finally', () => { + it('masks the body primary and skips admin close and drop when the count throws', async () => { + const vs = virtualScheduler() + const h = harness(vs, { sample: async () => nonzeroRow() }) + const primary = new Error('body failure') + const thrown = await vs + .run( + (async () => { + try { + throw primary + } finally { + await acceptedFinally(h.input) + } + })(), + ) + .catch((e: unknown) => e) + expect(thrown).not.toBe(primary) + expect(h.calls).not.toContain('admin') + + const vs2 = virtualScheduler() + const h2 = harness(vs2, { sample: async () => nonzeroRow() }) + const outcome = await vs2.run( + finalizeNativeFixture({ ...h2.input, primary: { value: primary } }), + ) + expect(outcome.primary!.value).toBe(primary) + expect(h2.calls).toContain('admin') + }) + + it('stalls behind a pending holding or stop; the repaired finalizer bounds and continues', async () => { + const vs = virtualScheduler() + const h = harness(vs, { stop: () => vs.never() }) + expect(await vs.run(acceptedFinally(h.input)).catch((e: Error) => e.message)).toBe( + 'virtual deadlock: work pending with no timers', + ) + expect(h.calls).not.toContain('admin') + + const vs2 = virtualScheduler() + const h2 = harness(vs2, { stop: () => vs2.never() }) + await vs2.run(finalizeNativeFixture(h2.input)) + expect(h2.calls).toContain('admin') + }) + + it('swallowed a holding rejection; the repaired finalizer reports it', async () => { + const vs = virtualScheduler() + const holding = Promise.reject(new Error('holder failed')) + holding.catch(() => undefined) + const h = harness(vs, { holding }) + await vs.run(acceptedFinally(h.input)) + expect(h.calls).toContain('drop') // accepted code dropped despite the holder failure + + const vs2 = virtualScheduler() + const h2 = harness(vs2, { holding }) + const outcome = await vs2.run(finalizeNativeFixture(h2.input)) + expect(failureSteps(outcome)).toEqual(['holding']) + expect(h2.calls).not.toContain('drop') + }) +}) + +// --------------------------------------------------------------------------------------------- +// v2 corrections (SOURCE-REVIEW1): each case below failed or was uncovered against v1. +// --------------------------------------------------------------------------------------------- + +const thrownBy = (outcome: Awaited>) => { + try { + throwFixtureOutcome(outcome) + } catch (error) { + return error + } + return 'nothing thrown' +} + +describe('v2: independent failures are never coalesced by equal primitives or absent causes', () => { + for (const [label, primary, holdingFailure] of [ + ['unrelated Error without cause + holding rejects undefined', new Error('body'), undefined], + ['primary 0 + holding rejects 0', 0, 0], + ['primary undefined + holding rejects undefined', undefined, undefined], + ] as const) { + it(label, async () => { + const vs = virtualScheduler() + const holding = Promise.reject(holdingFailure) + holding.catch(() => undefined) + const h = harness(vs, { holding, primary: { value: primary } }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures[0]).toMatchObject({ step: 'holding' }) + expect(outcome.failures[0]!.duplicateOfPrimary).toBeUndefined() + const thrown = thrownBy(outcome) as AggregateError + expect(thrown).toBeInstanceOf(AggregateError) + expect(Object.is(thrown.errors[0], primary)).toBe(true) + expect((thrown.errors[1] as FixtureCleanupError).cause).toBe(holdingFailure) + expect('cause' in (thrown.errors[1] as object)).toBe(true) + }) + } + + it('the identical holding Error object, or the lock-gate cause object, is still de-duplicated', async () => { + const vs = virtualScheduler() + const holdingError = new Error('BEGIN failed') + const holding = Promise.reject(holdingError) + holding.catch(() => undefined) + const h = harness(vs, { holding, primary: { value: holdingError } }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(thrownBy(outcome)).toBe(holdingError) + }) +}) + +describe('v2: unavailable, late or invalid follow-up evidence is not reported as persistent sessions', () => { + it('a rejecting bounded-zero follow-up keeps its original error and wording says unavailable', async () => { + const vs = virtualScheduler() + const queryError = new Error('admin connection lost') + let calls = 0 + const h = harness(vs, { + sample: async () => { + if (++calls === 1) return nonzeroRow() + throw queryError + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['bounded zero sample', 'bounded zero']) + expect(outcome.failures[0]!.error).toBe(queryError) + const summary = outcome.failures[1]!.error as Error + expect(summary.message).toContain('unavailable') + expect(summary.message).not.toContain('still had sessions') + expect(h.calls).not.toContain('drop') + }) + + it('a follow-up settling after the window keeps its late error as the timeout cause', async () => { + const vs = virtualScheduler() + const late = new Error('late failure') + let calls = 0 + const h = harness(vs, { + sample: async () => { + if (++calls === 1) return nonzeroRow() + vs.jump(2_100) + throw late + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + const timeout = outcome.failures[0]!.error as FixtureObservationTimeout + expect(outcome.failures[0]!.step).toBe('bounded zero sample') + expect(timeout).toBeInstanceOf(FixtureObservationTimeout) + expect(timeout.settledAfterBound).toBe(true) + expect(timeout.cause).toBe(late) + }) + + it('a pending fresh-zero query is unavailable evidence, not "fresh zero not observed" sessions', async () => { + const vs = virtualScheduler() + const h = harness(vs) + h.observer.fresh = () => vs.never() + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['fresh zero sample', 'fresh zero']) + expect((outcome.failures[1]!.error as Error).message).toContain('unavailable') + expect(outcome.drop.attempt).toBe('not-started') + }) + + it('malformed fresh evidence is a failed precondition (not "pending")', async () => { + const vs = virtualScheduler() + const h = harness(vs) + h.observer.fresh = async () => ({ count: 1, sampled_at: 't', sessions: [] }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.drop).toMatchObject({ attempt: 'not-started' }) + expect(outcome.drop.reason).not.toContain('pending') + expect(failureSteps(outcome)).toEqual(['fresh zero sample', 'fresh zero']) + expect(h.calls).not.toContain('drop') + }) + + it('a snapshot whose count disagrees with its identities is invalid evidence', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + sample: async () => ({ count: 2, sampled_at: 't', sessions: [{ pid: 1 }] }), + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['first sample']) + expect(h.calls).not.toContain('drop') + }) +}) + +describe('v2: drop and catalog evidence keeps time, cause and later confirmation', () => { + it('a drop that times out but fulfills before the final report is reflected, failure kept', async () => { + const vs = virtualScheduler() + const h = harness(vs, { drop: () => vs.after(9_000, () => undefined) }) + h.observer.close = () => vs.after(2_000, () => undefined) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['deleteDb']) + expect(outcome.drop).toMatchObject({ + attempt: 'unknown', + reason: 'timeout', + catalog: { present: true, at: 8_000 }, + lateConfirmedAt: 9_000, + }) + expect(outcome.dropped).toBe(true) + expect(outcome.dropState).toContain('catalog present at 8000ms') + expect(outcome.dropState).toContain('confirmed late at 9000ms') + expect(h.reports.at(-1)).toContain('confirmed late at 9000ms') + }) + + it('catalog absence is an observation, not proof that our refused drop deleted the DB', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + drop: async () => { + throw new Error('dropdb: database "owned_db" is being accessed by other users') + }, + }) + h.observer.catalogHas = async () => false + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.drop).toMatchObject({ attempt: 'refused', catalog: { present: false } }) + expect(outcome.dropped).toBe(false) + expect(outcome.dropState).toContain('catalog absent at') + }) + + for (const [label, catalogHas, expected] of [ + ['rejects', () => Promise.reject(new Error('observer lost')), 'unavailable'], + ['returns a non-boolean', async () => 'yes', 'unavailable'], + ] as const) { + it(`a catalog probe that ${label} is recorded as unavailable with its cause`, async () => { + const vs = virtualScheduler() + const h = harness(vs, { + drop: async () => { + throw new Error('Command failed: unexpected EOF') + }, + }) + h.observer.catalogHas = catalogHas as never + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.drop.catalog?.present).toBe(expected) + expect(failureSteps(outcome)).toEqual(['deleteDb', 'catalog probe']) + expect(outcome.dropState).toContain('catalog unavailable at') + }) + } + + it('without budget for the probe the catalog is recorded as not probed', async () => { + const vs = virtualScheduler() + const h = harness(vs, { deadline: 14_000, drop: () => vs.after(8_100, () => undefined) }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.drop.catalog?.present).toBe('not probed') + }) + + it('a drop that settles ok after its bound but before consumption is confirmed-after-bound', async () => { + const vs = virtualScheduler() + const h = harness(vs, { + drop: async () => { + vs.jump(8_100) + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.drop.attempt).toBe('confirmed-after-bound') + expect(outcome.dropped).toBe(true) + expect(failureSteps(outcome)).toEqual(['deleteDb']) + }) + + it('a drop that expires and later rejects stays unknown and keeps the late error', async () => { + const vs = virtualScheduler() + const late = new Error('late drop failure') + const h = harness(vs, { drop: () => vs.after(9_000, () => Promise.reject(late)) }) + h.observer.close = () => vs.after(2_000, () => undefined) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.drop).toMatchObject({ attempt: 'unknown', reason: 'timeout' }) + expect(outcome.dropped).toBe(false) + expect(outcome.late).toEqual([ + expect.objectContaining({ step: 'deleteDb', status: 'error', error: late }), + ]) + }) +}) + +describe('v2: observation edges', () => { + it('exact-bound tie: an operation timer created before the bound timer is in time', async () => { + const vs = virtualScheduler() + const op = vs.after(100, () => 'value') + const outcome = await vs.run(observe(vs.clock, () => op, 100)) + expect(outcome).toMatchObject({ status: 'ok', value: 'value', at: 100 }) + }) + + it('exact-bound tie: an operation timer created after the bound timer fails the observation (safe direction) and is recorded late', async () => { + const vs = virtualScheduler() + const lates: unknown[] = [] + // start() defers creating its timer to a microtask, i.e. after observe created the bound timer. + const outcome = await vs.run( + observe(vs.clock, () => Promise.resolve().then(() => vs.after(100, () => 'value')), 100, { + onLate: (late, kind) => lates.push({ ...late, kind }), + }), + ) + expect(outcome).toMatchObject({ status: 'expired', settled: undefined }) + await vs.run(vs.after(1, () => undefined)) + expect(lates).toEqual([expect.objectContaining({ status: 'ok', at: 100, kind: 'late' })]) + }) + + it('a synchronous throw from start is an error observation, also inside a body step', async () => { + const vs = virtualScheduler() + const failure = new Error('sync') + expect( + await vs.run( + observe( + vs.clock, + () => { + throw failure + }, + 100, + ), + ), + ).toMatchObject({ status: 'error', error: failure }) + const body = new FixtureBody(vs.clock, 1_000) + expect( + await vs.run( + body + .step('sync', () => { + throw failure + }) + .catch((e: unknown) => e), + ), + ).toBe(failure) + }) + + it('a body step that fails after its bound keeps the late error as the timeout cause', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 1_000) + const late = new Error('late body failure') + const error = (await vs.run( + body + .step('late', async () => { + vs.jump(1_100) + throw late + }) + .catch((e: unknown) => e), + )) as FixtureBodyTimeout + expect(error).toBeInstanceOf(FixtureBodyTimeout) + expect(error.cause).toBe(late) + }) + + it('no stale pending entry when the late settlement races the step continuation', async () => { + // Invariant check: the operation is resolved N microtask hops after the BOUND timer fires. In + // every ordering the result is either in time, or late with no pending entry left behind. + // With the current microtask ordering the stale-entry window is not reachable from here, so + // this does not discriminate the add-after-observe mutant (mutants-v2.log, W); observe's + // synchronous onPending keeps the ordering by construction. + for (let hops = 0; hops <= 40; hops++) { + const vs = virtualScheduler() + let resolveOp!: (value: string) => void + const op = new Promise((resolve) => { + resolveOp = resolve + }) + const clock: Clock = { + now: vs.clock.now, + timer(ms) { + const timer = vs.clock.timer(ms) + void timer.promise.then(async () => { + for (let i = 0; i < hops; i++) await Promise.resolve() + resolveOp('v') + }) + return timer + }, + } + const body = new FixtureBody(clock, 100) + const result = await vs.run(body.step('raced', () => op).catch((e: unknown) => e)) + await vs.run(vs.after(1, () => undefined)) + const record = body.record() + expect(record.pending).toEqual([]) + if (result !== 'v') expect(record.late).toHaveLength(1) + } + }) + + it('the lock-gate timer is cancelled even when locked rejects', async () => { + const vs = virtualScheduler() + const error = await vs + .run( + awaitLockGate({ + clock: vs.clock, + locked: Promise.reject(new Error('locked rejected')), + holding: vs.never(), + boundMs: 5_000, + }), + ) + .catch((e: unknown) => e) + expect((error as Error).message).toBe('locked rejected') + expect(vs.liveTimers()).toBe(0) + }) + + it('shared default caps are frozen', () => { + expect(Object.isFrozen(FIXTURE_CAPS)).toBe(true) + }) +}) + +describe('v2: budgets when the finalizer starts late (bodies or provisioning used time)', () => { + it('a stop starting at 17.5s still gets its full 22s observation; a 20s stop passes', async () => { + const vs = virtualScheduler() + vs.jump(17_500) + const h = harness(vs, { stop: () => vs.after(20_000, () => true) }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures).toEqual([]) + expect(outcome.steps.find((s) => s.step === 'client.stop')!.boundMs).toBe(22_000) + }) + + it('a stop starting at 19.9s is clipped to 19.6s by the reserves: a 20s stop fails and retains', async () => { + const vs = virtualScheduler() + vs.jump(19_900) + const h = harness(vs, { stop: () => vs.after(20_000, () => true) }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.steps.find((s) => s.step === 'client.stop')!.boundMs).toBe(19_600) + expect(failureSteps(outcome)).toEqual(['client.stop']) + expect(outcome.dropped).toBe(false) + }) + + it('the bounded-zero window is clipped by the admin reserve near the deadline', async () => { + const vs = virtualScheduler() + vs.jump(46_500) + const h = harness(vs, { sample: async () => nonzeroRow() }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['bounded zero']) + expect(vs.clock.now()).toBeLessThanOrEqual(48_000) + }) + + it('the final report includes the body record (aborted step, pending and late)', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 1_000) + const primary = await vs.run(body.step('holding', () => vs.never()).catch((e: unknown) => e)) + const h = harness(vs, { primary: { value: primary }, body }) + await vs.run(finalizeNativeFixture(h.input)) + const report = JSON.parse(h.reports.at(-1)!.replace(/^\[wait-native-fixture\] /, '')) + expect(report.body).toMatchObject({ abortedBy: 'holding', pending: ['holding'] }) + }) +}) + +// --------------------------------------------------------------------------------------------- +// v3 corrections (SOURCE-REVIEW2) +// --------------------------------------------------------------------------------------------- + +const finalReport = (reports: string[]) => + JSON.parse(reports.at(-1)!.replace(/^\[wait-native-fixture\] /, '')) as Record + +describe('v3: emitted reports carry late errors, bounded causes and truthful wording', () => { + for (const [label, lateError, expected] of [ + ['an Error', new Error('late drop failure'), 'Error: late drop failure'], + ['undefined', undefined, 'undefined'], + ['0', 0, '0'], + ] as const) { + it(`a late rejection (${label}) is described in the emitted final report`, async () => { + const vs = virtualScheduler() + const h = harness(vs, { drop: () => vs.after(9_000, () => Promise.reject(lateError)) }) + h.observer.close = () => vs.after(2_000, () => undefined) + await vs.run(finalizeNativeFixture(h.input)) + const report = finalReport(h.reports) + expect(report['late']).toEqual([ + { step: 'deleteDb', status: 'error', kind: 'late', at: 9_000, error: expected }, + ]) + // The expiry itself stays a separate failure recorded at the bound. + expect(report['failures'][0]).toMatchObject({ step: 'deleteDb', at: 8_000 }) + }) + } + + it('a late body rejection of undefined is described in the report body record', async () => { + const vs = virtualScheduler() + const body = new FixtureBody(vs.clock, 1_000) + const primary = await vs.run( + body + .step('client.start', () => vs.after(1_500, () => Promise.reject(undefined))) + .catch((e: unknown) => e), + ) + await vs.run(vs.after(1_000, () => undefined)) + const h = harness(vs, { primary: { value: primary }, body }) + await vs.run(finalizeNativeFixture(h.input)) + expect(finalReport(h.reports)['body'].late).toEqual([ + { step: 'client.start', status: 'error', kind: 'late', at: 1_500, error: 'undefined' }, + ]) + }) + + it('cyclic and deep cause chains are described with markers, without changing the errors', async () => { + const a = new Error('a') as Error & { cause?: unknown } + const b = new Error('b', { cause: a }) + a.cause = b + const deep = [1, 2, 3, 4, 5, 6].reduce( + (inner, i) => new Error(`level ${i}`, { cause: inner }), + new Error('root'), + ) + for (const [error, marker] of [ + [a, '[cause cycle]'], + [deep, '[cause depth limit]'], + ] as const) { + const vs = virtualScheduler() + const h = harness(vs, { + stop: async () => { + throw error + }, + }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.failures[0]!.error).toBe(error) + expect(finalReport(h.reports)['failures'][0].error).toContain(marker) + } + expect(a.cause).toBe(b) + }) + + it('an empty bounded-zero window says no query was started (not a separate failed query)', async () => { + const vs = virtualScheduler() + vs.jump(48_100) + const h = harness(vs, { sample: async () => (h.calls.push('sample'), nonzeroRow()) }) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(failureSteps(outcome)).toEqual(['bounded zero']) + expect(h.calls.filter((c) => c === 'sample')).toHaveLength(1) + const message = (outcome.failures[0]!.error as Error).message + expect(message).toContain('no observation window remained') + expect(message).not.toContain('recorded separately') + }) + + it('report timestamps are relative to a nonzero origin', async () => { + const vs = virtualScheduler() + vs.jump(1_000) + const h = harness(vs, { + origin: 1_000, + deadline: 55_000, + drop: () => vs.after(9_000, () => undefined), + }) + h.observer.close = () => vs.after(2_000, () => undefined) + const outcome = await vs.run(finalizeNativeFixture(h.input)) + expect(outcome.dropState).toBe( + 'unknown:timeout; catalog present at 8000ms; our drop confirmed late at 9000ms', + ) + expect(finalReport(h.reports)['failures'][0]).toMatchObject({ step: 'deleteDb', at: 8_000 }) + }) +}) diff --git a/packages/duron/test/wait-native-fixture.ts b/packages/duron/test/wait-native-fixture.ts new file mode 100644 index 0000000..b489848 --- /dev/null +++ b/packages/duron/test/wait-native-fixture.ts @@ -0,0 +1,915 @@ +// Test-local helpers for the two native wait-deadline fixtures in wait-native.test.ts (the slow-SQL +// and table-lock cases). Pure: every clock, SQL, close, drop and report effect is injected by the +// caller, so wait-native-fixture.test.ts can drive them deterministically without PostgreSQL. + +// --------------------------------------------------------------------------------------------- +// Statement-timeout (SQLSTATE 57014) evidence from the two real logger sites: +// adapter.ts Adapter.getJobStatus: logger.error(error, 'Error in Adapter.getJobStatus()') +// wait-manager.ts chain rejection: logger.error({ error, ... }, '[Duron] Wait read failed') +// Both must carry an actual Error whose cause chain has code '57014'. Text never counts. +// --------------------------------------------------------------------------------------------- + +const STATUS_WRAPPER_MESSAGE = 'Error in Adapter.getJobStatus()' +const WAIT_FAILED_MESSAGE = '[Duron] Wait read failed' + +function hasStatementTimeoutCause(root: unknown): boolean { + try { + const seen = new Set() + let current: unknown = root + for (let depth = 0; depth < 5; depth++) { + if (!(current instanceof Error) || seen.has(current)) return false + seen.add(current) + if ((current as { code?: unknown }).code === '57014') return true + current = current.cause + } + return false + } catch { + return false + } +} + +export function isStatementTimeoutLog(args: readonly unknown[]): boolean { + try { + if (args.length !== 2) return false + const [first, message] = args + if (message === STATUS_WRAPPER_MESSAGE) return hasStatementTimeoutCause(first) + if (message !== WAIT_FAILED_MESSAGE) return false + if (typeof first !== 'object' || first === null || Array.isArray(first)) return false + return hasStatementTimeoutCause((first as { error?: unknown }).error) + } catch { + return false + } +} + +export function statementTimeoutObserved(calls: readonly (readonly unknown[])[]): boolean { + return calls.some((args) => isStatementTimeoutLog(args)) +} + +/** Table-lock body readiness: the unchanged native Lock-count-zero AND real 57014 evidence. */ +export function lockReadyWithStatementTimeout( + lockCount: unknown, + calls: readonly (readonly unknown[])[], +): boolean { + return lockCount === 0 && statementTimeoutObserved(calls) +} + +// --------------------------------------------------------------------------------------------- +// Clock and bounded observation. A bound limits OBSERVATION only: expiry is never settlement, the +// real promise stays observed, and its settlement is reported through ONE late path. The bound is +// checked against the settlement time when the result is consumed, so a result consumed after +// the bound is a failed observation even if it is now known ("settled-after-bound"). +// Exact-bound ties are ordering-dependent: a settlement at the bound counts as in time when it is +// consumed before the bound timer's reaction; otherwise the observation fails (safe direction) +// and the settlement is recorded as late. +// --------------------------------------------------------------------------------------------- + +export interface Timer { + promise: Promise + cancel(): void +} + +export interface Clock { + now(): number + timer(ms: number): Timer +} + +export const realClock: Clock = { + now: () => performance.now(), + timer(ms) { + let handle: ReturnType | undefined + const promise = new Promise((resolve) => { + handle = setTimeout(resolve, ms) + }) + return { promise, cancel: () => clearTimeout(handle) } + }, +} + +export type Settled = + | { status: 'ok'; value: T; at: number } + | { status: 'error'; error: unknown; at: number } + +export type Observation = + | Settled + | { status: 'expired'; boundAt: number; at: number; settled: Settled | undefined } + +export interface ObserveHooks { + /** Called synchronously when the observation expires with the operation still pending. */ + onPending?: () => void + /** The single late path: settled-after-bound (known at expiry) or a later settlement. */ + onLate?: (settled: Settled, kind: 'settled-after-bound' | 'late') => void +} + +export async function observe( + clock: Clock, + start: () => T | Promise, + boundAt: number, + hooks: ObserveHooks = {}, +): Promise> { + let settled: Settled | undefined + let pendingAtExpiry = false + let actual: Promise> + try { + actual = Promise.resolve(start()).then( + (value): Settled => (settled = { status: 'ok', value, at: clock.now() }), + (error: unknown): Settled => (settled = { status: 'error', error, at: clock.now() }), + ) + } catch (error) { + settled = { status: 'error', error, at: clock.now() } + actual = Promise.resolve(settled) + } + void actual.then((late) => { + if (pendingAtExpiry) hooks.onLate?.(late, 'late') + }) + const timer = clock.timer(Math.max(0, boundAt - clock.now())) + try { + const winner = await Promise.race([actual, timer.promise.then(() => undefined)]) + const result = winner ?? settled + if (result && result.at <= boundAt) return result + } finally { + timer.cancel() + } + if (settled) { + hooks.onLate?.(settled, 'settled-after-bound') + } else { + pendingAtExpiry = true + hooks.onPending?.() + } + return { status: 'expired', boundAt, at: clock.now(), settled } +} + +/** The actual error of an after-bound settlement, kept as a timeout's cause (even undefined). */ +function lateCause(settled: Settled | undefined): { cause: unknown } | undefined { + return settled?.status === 'error' ? { cause: settled.error } : undefined +} + +// --------------------------------------------------------------------------------------------- +// Bounded body steps. Every awaited fixture operation that issues I/O goes through step(). Once +// a step expires (or the deadline has passed), the body is aborted: later step() calls throw +// WITHOUT calling their start function, so no further fixture SQL is issued and the body unwinds. +// (Pure awaits without I/O, such as the slow-SQL logger poll, are not steps.) +// --------------------------------------------------------------------------------------------- + +export class FixtureBodyTimeout extends Error { + constructor( + readonly step: string, + readonly boundAt: number, + readonly settledAfterBound = false, + options?: { cause: unknown }, + ) { + super( + `Fixture body step "${step}" not settled within its body deadline${ + settledAfterBound ? ' (settled after the bound)' : '' + }`, + options, + ) + this.name = 'FixtureBodyTimeout' + } +} + +export class FixtureBodyAborted extends Error { + constructor( + readonly step: string, + readonly abortedBy: string, + ) { + super(`Fixture body step "${step}" not started: body aborted by "${abortedBy}"`) + this.name = 'FixtureBodyAborted' + } +} + +export interface LateRecord { + step: string + status: 'ok' | 'error' + kind: 'settled-after-bound' | 'late' + at: number + error?: unknown +} + +const lateRecord = ( + step: string, + late: Settled, + kind: LateRecord['kind'], +): LateRecord => ({ + step, + status: late.status, + kind, + at: late.at, + ...(late.status === 'error' ? { error: late.error } : {}), +}) + +export class FixtureBody { + #abortedBy: string | undefined + readonly #pending = new Set() + readonly #late: LateRecord[] = [] + + constructor( + readonly clock: Clock, + readonly deadline: number, + ) {} + + get aborted(): boolean { + return this.#abortedBy !== undefined + } + + record(): { abortedBy: string | undefined; pending: string[]; late: LateRecord[] } { + return { abortedBy: this.#abortedBy, pending: [...this.#pending], late: [...this.#late] } + } + + async step(name: string, start: () => T | Promise): Promise { + if (this.#abortedBy !== undefined) throw new FixtureBodyAborted(name, this.#abortedBy) + if (this.clock.now() >= this.deadline) { + this.#abortedBy = name + throw new FixtureBodyTimeout(name, this.deadline) + } + const observation = await observe(this.clock, start, this.deadline, { + onPending: () => this.#pending.add(name), + onLate: (late, kind) => { + this.#pending.delete(name) + this.#late.push(lateRecord(name, late, kind)) + }, + }) + if (observation.status === 'ok') return observation.value + if (observation.status === 'error') throw observation.error + this.#abortedBy = name + throw new FixtureBodyTimeout( + name, + this.deadline, + observation.settled !== undefined, + lateCause(observation.settled), + ) + } +} + +// --------------------------------------------------------------------------------------------- +// Lock gate: holding is observed immediately (no unhandled rejection), with no rejecting branch +// of its own; the timer is always cancelled. statement_timeout bounds only server LOCK execution, +// not acquisition or JS; hence the explicit observation bound. +// --------------------------------------------------------------------------------------------- + +export async function awaitLockGate(options: { + clock: Clock + locked: Promise + holding: Promise + boundMs: number +}): Promise { + const settled = options.holding.then( + () => ({ ok: true as const }), + (error: unknown) => ({ ok: false as const, error }), + ) + const timer = options.clock.timer(options.boundMs) + let gate: 'locked' | 'timeout' | { settled: { ok: true } | { ok: false; error: unknown } } + try { + gate = await Promise.race([ + options.locked.then(() => 'locked' as const), + settled.then((outcome) => ({ settled: outcome })), + timer.promise.then(() => 'timeout' as const), + ]) + } finally { + timer.cancel() + } + if (gate === 'locked') return + if (gate === 'timeout') { + throw new Error(`Table-lock acquisition not observed within ${options.boundMs}ms`) + } + throw new Error('Blocker transaction settled before acquiring the table lock', { + cause: gate.settled.ok ? undefined : gate.settled.error, + }) +} + +// --------------------------------------------------------------------------------------------- +// Finalizer for the two native fixtures. Each independent obligation is started once, observed +// immediately and bounded within an absolute fixture deadline with held reserves; expiry is a +// failure, never settlement, and keeps any known after-bound error as its cause. Every step runs +// in its own guarded section so an internal fault (release, snapshot validation, observer +// construction, serialization, reporting) cannot skip later closes. This covers JavaScript +// exceptions only: synchronous stalls, OOM or runtime faults are not contained. +// --------------------------------------------------------------------------------------------- + +export const FIXTURE_CAPS = Object.freeze({ + holding: 3_000, + // Observation ceiling only: Client.stop may legitimately use four sequential 5s lifecycle + // phase budgets (~20s). With the 14.5s blocker/sample/admin reserve the full 22s fits only when + // the stop starts by deadline - 36.5s (origin + 17.5s). Not a lifecycle contract. + stop: 22_000, + blocker: 6_000, + sample: 2_500, + zeroWindow: 2_000, + pause: 25, + admin: 6_000, + freshWindow: 2_000, + observerClose: 6_000, + // Instrumentation budget for observing the existing factory drop; not a PostgreSQL timing fact. + drop: 8_000, + catalogProbe: 2_500, +}) + +export type FixtureCaps = typeof FIXTURE_CAPS + +export interface Snapshot { + count: number + sampled_at: string + sessions: unknown[] +} + +export interface FixtureObserver { + fresh: () => Promise + catalogHas: () => Promise + close: () => Promise +} + +export interface FinalizeInput { + clock: Clock + /** Clock time reported as 0 in drop/catalog timestamps (the test's origin). */ + origin?: number + /** Absolute clock time by which every observation ends. */ + deadline: number + /** Exact owned database name (never a connection URL). */ + database: string + /** Boxed so that undefined or falsy thrown values are never lost. */ + primary: { value: unknown } | undefined + body?: FixtureBody + release?: () => void + holding?: Promise + stop: () => Promise + endBlocker?: () => Promise + sample: () => Promise + endAdmin: () => Promise + openObserver: () => FixtureObserver + drop: () => Promise + report: (line: string) => void + caps?: Partial +} + +export interface CleanupFailure { + step: string + at: number + error: unknown + duplicateOfPrimary?: boolean +} + +export interface StepRecord { + step: string + status: Observation['status'] + startedAt: number + boundMs: number +} + +/** Structured drop state: what we attempted, what we know, and when. */ +export interface DropState { + attempt: 'not-started' | 'confirmed' | 'confirmed-after-bound' | 'refused' | 'unknown' + reason?: string + /** Point-in-time catalog observation after a non-confirmed drop (not proof of who dropped). */ + catalog?: { present: boolean | 'unavailable' | 'not probed'; at: number } + /** Our drop operation fulfilled after its observation bound, before the final report. */ + lateConfirmedAt?: number +} + +export interface FixtureOutcome { + database: string + primary: { value: unknown } | undefined + failures: CleanupFailure[] + boundary: string + first: Snapshot | undefined + followups: Snapshot[] + zeroReached: boolean | undefined + fresh: Snapshot[] + drop: DropState + /** True only when OUR drop operation is confirmed (in time, after bound, or late). */ + dropped: boolean + /** Human-readable rendering of `drop`, timestamps relative to the origin. */ + dropState: string + steps: StepRecord[] + late: LateRecord[] +} + +export class FixtureObservationTimeout extends Error { + constructor( + readonly step: string, + readonly boundMs: number, + readonly settledAfterBound: boolean, + options?: { cause: unknown }, + ) { + super( + `${step} not settled within its ${boundMs}ms observation bound${ + settledAfterBound ? ' (settled after the bound)' : ' (still pending)' + }`, + options, + ) + this.name = 'FixtureObservationTimeout' + } +} + +export class FixtureCleanupError extends Error { + readonly step: string + readonly database: string + readonly dropState: string + + constructor(failure: CleanupFailure, outcome: FixtureOutcome) { + super( + `Fixture cleanup step "${failure.step}" failed (database ${outcome.database}, drop ${ + outcome.dropState + }): ${describe(failure.error)}`, + { cause: failure.error }, + ) + this.name = 'FixtureCleanupError' + this.step = failure.step + this.database = outcome.database + this.dropState = outcome.dropState + } +} + +const REPORT_PREFIX = '[wait-native-fixture] ' +const DROP_REFUSAL = 'is being accessed by other users' + +/** Text for a thrown value, following `cause` with a depth and cycle bound (objects unchanged). */ +function describe(value: unknown, seen = new Set()): string { + try { + if (value instanceof Error) { + if (seen.has(value)) return '[cause cycle]' + if (seen.size >= 4) return '[cause depth limit]' + seen.add(value) + const cause = 'cause' in value ? ` (cause: ${describe(value.cause, seen)})` : '' + return `${value.name}: ${value.message}${cause}` + } + return String(value) + } catch { + return '[unprintable]' + } +} + +/** Compact JSON that never throws on getters, cycles, BigInt or non-finite numbers. */ +export function safeJson(value: unknown): string { + const ancestors = new Set() + const visit = (current: unknown, depth: number): unknown => { + try { + if (current === null || typeof current === 'string' || typeof current === 'boolean') { + return current + } + if (typeof current === 'number') return Number.isFinite(current) ? current : String(current) + if (typeof current === 'bigint') return `${current}n` + if (current === undefined) return undefined + if (typeof current !== 'object') return `[${typeof current}]` + if (depth > 8) return '[depth limit]' + if (ancestors.has(current)) return '[circular]' + ancestors.add(current) + try { + if (current instanceof Error) return describe(current) + if (Array.isArray(current)) return current.map((entry) => visit(entry, depth + 1)) + const out: Record = {} + for (const key of Object.keys(current)) { + try { + out[key] = visit((current as Record)[key], depth + 1) + } catch (error) { + out[key] = `[unreadable: ${describe(error)}]` + } + } + return out + } finally { + ancestors.delete(current) + } + } catch (error) { + return `[unserializable: ${describe(error)}]` + } + } + return JSON.stringify(visit(value, 0)) ?? 'undefined' +} + +/** + * Same failure already carried by the primary: only by OBJECT identity (the primary itself, or + * the lock gate's cause). Equal primitives or an absent cause never imply a shared origin, so an + * independent failure is never erased; retaining a duplicate observation is the safe choice. + */ +function carries(primary: unknown, error: unknown): boolean { + if (typeof error !== 'object' || error === null) return false + if (primary === error) return true + try { + return primary instanceof Error && 'cause' in primary && primary.cause === error + } catch { + return false + } +} + +function validSnapshot(row: unknown): Snapshot { + const candidate = row as Partial | undefined + if ( + !candidate || + !Number.isInteger(candidate.count) || + (candidate.count as number) < 0 || + typeof candidate.sampled_at !== 'string' || + !Array.isArray(candidate.sessions) || + candidate.sessions.length !== candidate.count + ) { + throw new Error(`Invalid session snapshot: ${safeJson(row)}`) + } + return { count: candidate.count!, sampled_at: candidate.sampled_at, sessions: candidate.sessions } +} + +function lateForReport(late: LateRecord, origin = 0) { + return { + step: late.step, + status: late.status, + kind: late.kind, + at: late.at - origin, + ...(late.status === 'error' ? { error: describe(late.error) } : {}), + } +} + +function bodyRecord(body: FixtureBody | undefined, origin = 0) { + if (!body) return undefined + const record = body.record() + return { ...record, late: record.late.map((late) => lateForReport(late, origin)) } +} + +export function renderDrop(drop: DropState, origin = 0): string { + const ms = (at: number) => `${Math.round(at - origin)}ms` + if (drop.attempt === 'not-started') return `not-started:${drop.reason ?? 'unknown'}` + let text: string = drop.attempt === 'unknown' ? `unknown:${drop.reason ?? 'error'}` : drop.attempt + if (drop.catalog) { + const present = + drop.catalog.present === true + ? 'present' + : drop.catalog.present === false + ? 'absent' + : drop.catalog.present + text += `; catalog ${present} at ${ms(drop.catalog.at)}` + } + if (drop.lateConfirmedAt !== undefined) { + text += `; our drop confirmed late at ${ms(drop.lateConfirmedAt)}` + } + return text +} + +export async function finalizeNativeFixture(input: FinalizeInput): Promise { + const { clock } = input + const origin = input.origin ?? 0 + const caps = { ...FIXTURE_CAPS, ...input.caps } + const outcome: FixtureOutcome = { + database: input.database, + primary: input.primary, + failures: [], + boundary: 'not reached', + first: undefined, + followups: [], + zeroReached: undefined, + fresh: [], + drop: { attempt: 'not-started', reason: 'not reached' }, + dropped: false, + dropState: 'not-started:not reached', + steps: [], + late: [], + } + const fail = (step: string, error: unknown, extra: Partial = {}) => { + outcome.failures.push({ step, at: clock.now(), error, ...extra }) + } + // Reserves still held for later always-attempted obligations. + const held = { blocker: input.endBlocker !== undefined, sample: true, admin: true } + const reserve = () => + (held.blocker ? caps.blocker : 0) + + (held.sample ? caps.sample : 0) + + (held.admin ? caps.admin : 0) + + /** Start once, observe, bound, record the step and (if not ok) its failure with the cause. */ + const attempt = async ( + step: string, + start: () => Promise | T, + cap: number, + reserveAfter: number, + options: { boundAt?: number; record?: boolean } = {}, + ): Promise> => { + const startedAt = clock.now() + const end = Math.max( + startedAt, + options.boundAt ?? Math.min(startedAt + cap, input.deadline - reserveAfter), + ) + const observation = await observe(clock, start, end, { + onLate: (late, kind) => outcome.late.push(lateRecord(step, late, kind)), + }) + outcome.steps.push({ step, status: observation.status, startedAt, boundMs: end - startedAt }) + if (options.record !== false) { + if (observation.status === 'error') fail(step, observation.error) + else if (observation.status === 'expired') { + fail( + step, + new FixtureObservationTimeout( + step, + end - startedAt, + observation.settled !== undefined, + lateCause(observation.settled), + ), + ) + } + } + return observation + } + const section = async (step: string, work: () => Promise | void) => { + try { + await work() + } catch (error) { + fail(step, error) + } + } + /** + * Repeated same-function observations inside an absolute window. A non-ok observation or + * invalid evidence is recorded with its own cause and makes the result 'unavailable'; only a + * measured snapshot can be 'zero' or 'nonzero'. + */ + const sampleUntil = async ( + step: string, + query: () => Promise, + until: number, + into: Snapshot[], + ): Promise<'zero' | 'nonzero' | 'unavailable' | 'no window'> => { + let result: 'zero' | 'nonzero' | 'unavailable' | 'no window' = 'no window' + while (clock.now() < until) { + const observation = await attempt(step, query, 0, 0, { boundAt: until }) + if (observation.status !== 'ok') return 'unavailable' + let snapshot: Snapshot + try { + snapshot = validSnapshot(observation.value) + } catch (error) { + fail(step, error) + return 'unavailable' + } + into.push(snapshot) + if (snapshot.count === 0) return 'zero' + result = 'nonzero' + const pause = Math.min(caps.pause, until - clock.now()) + if (pause > 0) await clock.timer(pause).promise + } + return result + } + const zeroFailure = ( + what: string, + result: 'nonzero' | 'unavailable' | 'no window', + last: unknown, + ) => + new Error( + result === 'nonzero' + ? `${what}: the last measured snapshot still counted sessions for ${input.database}: ${safeJson(last)}` + : result === 'no window' + ? `${what}: no observation window remained within the fixture budget, so no query was started; no claim about sessions for ${input.database}; last valid snapshot ${safeJson(last)}` + : `${what}: evidence unavailable (failed, late or invalid observation recorded separately); no claim about sessions for ${input.database}; last valid snapshot ${safeJson(last)}`, + ) + + let holdingOk = true + let stopOk = false + let blockerOk = input.endBlocker === undefined + let adminOk = false + + await section('release', () => input.release?.()) + await section('holding', async () => { + if (!input.holding) return + const holding = input.holding + const observation = await attempt('holding', () => holding, caps.holding, reserve(), { + record: false, + }) + holdingOk = observation.status === 'ok' + if (observation.status === 'error') { + // Not swallowed: an unexpected holder failure is a failure that prevents the drop. + const duplicate = + input.primary !== undefined && carries(input.primary.value, observation.error) + fail('holding', observation.error, duplicate ? { duplicateOfPrimary: true } : {}) + } else if (observation.status === 'expired') { + fail( + 'holding', + new FixtureObservationTimeout( + 'holding', + outcome.steps.at(-1)!.boundMs, + observation.settled !== undefined, + lateCause(observation.settled), + ), + ) + } + }) + await section('client.stop', async () => { + stopOk = (await attempt('client.stop', input.stop, caps.stop, reserve())).status === 'ok' + }) + await section('blocker.end', async () => { + if (!input.endBlocker) return + held.blocker = false + blockerOk = + (await attempt('blocker.end', input.endBlocker, caps.blocker, reserve())).status === 'ok' + }) + await section('boundary', () => { + const unsettled = [ + holdingOk ? undefined : 'holding', + stopOk ? undefined : 'client.stop', + blockerOk ? undefined : 'blocker.end', + ].filter((entry) => entry !== undefined) + outcome.boundary = unsettled.length + ? `cleanup-evidence (unsettled or failed: ${unsettled.join(', ')})` + : 'original' + }) + await section('first sample', async () => { + held.sample = false + const observation = await attempt('first sample', input.sample, caps.sample, reserve()) + if (observation.status === 'ok') outcome.first = validSnapshot(observation.value) + }) + await section('bounded zero', async () => { + if (!outcome.first || outcome.first.count === 0) return + const until = Math.min(clock.now() + caps.zeroWindow, input.deadline - reserve()) + const result = await sampleUntil('bounded zero sample', input.sample, until, outcome.followups) + outcome.zeroReached = result === 'zero' + if (result !== 'zero') { + fail( + 'bounded zero', + zeroFailure( + 'Bounded zero not established', + result, + outcome.followups.at(-1) ?? outcome.first, + ), + ) + } + }) + await section('admin.end', async () => { + held.admin = false + adminOk = (await attempt('admin.end', input.endAdmin, caps.admin, 0)).status === 'ok' + }) + // The approved first nonzero observation is persisted BEFORE any drop; failure blocks it. + await section('report first-nonzero', () => { + if (!outcome.first || outcome.first.count === 0) return + input.report( + REPORT_PREFIX + + safeJson({ + event: 'first-nonzero', + database: input.database, + boundary: outcome.boundary, + first: outcome.first, + last: outcome.followups.at(-1), + zeroReached: outcome.zeroReached, + }), + ) + }) + + let eligible = false + await section('eligibility', () => { + eligible = + input.primary === undefined && + outcome.failures.length === 0 && + outcome.first !== undefined && + (outcome.first.count === 0 || outcome.zeroReached === true) && + adminOk + outcome.drop = { + attempt: 'not-started', + reason: eligible + ? 'pending' + : input.primary !== undefined + ? 'primary failure' + : 'cleanup failure', + } + }) + + if (eligible) { + await section('fresh zero and drop', async () => { + if (input.deadline - clock.now() < caps.freshWindow + caps.observerClose) { + outcome.drop = { attempt: 'not-started', reason: 'insufficient budget' } + fail('drop budget', new Error('Insufficient fixture budget for strict fresh zero')) + return + } + let observer: FixtureObserver + try { + observer = input.openObserver() + } catch (error) { + outcome.drop = { attempt: 'not-started', reason: 'observer unavailable' } + fail('observer.open', error) + return + } + try { + outcome.drop = { attempt: 'not-started', reason: 'fresh zero not established' } + const until = Math.min(clock.now() + caps.freshWindow, input.deadline - caps.observerClose) + const fresh = await sampleUntil( + 'fresh zero sample', + () => observer.fresh(), + until, + outcome.fresh, + ) + if (fresh !== 'zero') { + outcome.drop = { + attempt: 'not-started', + reason: + fresh === 'nonzero' + ? 'fresh zero not observed' + : fresh === 'no window' + ? 'fresh zero not established (no observation window)' + : 'fresh zero evidence unavailable', + } + fail( + 'fresh zero', + zeroFailure('Fresh whole-target zero not established', fresh, outcome.fresh.at(-1)), + ) + return + } + if (input.deadline - clock.now() < caps.drop + caps.observerClose) { + outcome.drop = { attempt: 'not-started', reason: 'insufficient budget' } + fail('drop budget', new Error('Insufficient fixture budget to observe the drop')) + return + } + const drop = await attempt('deleteDb', input.drop, caps.drop, caps.observerClose) + if (drop.status === 'ok') { + outcome.drop = { attempt: 'confirmed' } + return + } + if (drop.status === 'expired' && drop.settled?.status === 'ok') { + outcome.drop = { attempt: 'confirmed-after-bound' } + return + } + const error = + drop.status === 'error' + ? drop.error + : drop.settled?.status === 'error' + ? drop.settled.error + : undefined + outcome.drop = + error !== undefined && describe(error).includes(DROP_REFUSAL) + ? { attempt: 'refused' } + : { + attempt: 'unknown', + reason: drop.status === 'expired' && !drop.settled ? 'timeout' : 'error', + } + // Point-in-time catalog observation; presence or absence does not say who dropped it. + const at = clock.now() + if (input.deadline - at < caps.catalogProbe + caps.observerClose) { + outcome.drop.catalog = { present: 'not probed', at } + return + } + const probe = await attempt( + 'catalog probe', + () => observer.catalogHas(), + caps.catalogProbe, + caps.observerClose, + ) + if (probe.status === 'ok' && typeof probe.value === 'boolean') { + outcome.drop.catalog = { present: probe.value, at: probe.at } + } else { + outcome.drop.catalog = { present: 'unavailable', at: clock.now() } + if (probe.status === 'ok') { + fail('catalog probe', new Error(`Catalog probe returned ${safeJson(probe.value)}`)) + } + } + } finally { + await section('observer.close', async () => { + await attempt('observer.close', () => observer.close(), caps.observerClose, 0) + }) + } + }) + } + + await section('report final', () => { + // Reflect our drop fulfilling after its bound but before this report (failure kept). + const lateDrop = outcome.late.find( + (l) => l.step === 'deleteDb' && l.kind === 'late' && l.status === 'ok', + ) + if (lateDrop && (outcome.drop.attempt === 'unknown' || outcome.drop.attempt === 'refused')) { + outcome.drop.lateConfirmedAt = lateDrop.at + } + outcome.dropped = + outcome.drop.attempt === 'confirmed' || + outcome.drop.attempt === 'confirmed-after-bound' || + outcome.drop.lateConfirmedAt !== undefined + outcome.dropState = renderDrop(outcome.drop, origin) + if (input.primary === undefined && outcome.failures.length === 0 && outcome.dropped) return + input.report( + REPORT_PREFIX + + safeJson({ + event: 'fixture-cleanup', + database: input.database, + drop: outcome.drop, + dropState: outcome.dropState, + dropped: outcome.dropped, + boundary: outcome.boundary, + primary: input.primary === undefined ? undefined : describe(input.primary.value), + failures: outcome.failures.map((f) => ({ + step: f.step, + at: f.at - origin, + error: describe(f.error), + })), + steps: outcome.steps.map((s) => ({ ...s, startedAt: s.startedAt - origin })), + first: outcome.first, + last: outcome.followups.at(-1), + fresh: outcome.fresh.at(-1), + body: bodyRecord(input.body, origin), + // Point-in-time: settlements observed after this report are not included. A late + // rejection's actual error (including undefined/falsy values) is described here; it was + // not known when the observation expired, which is recorded separately as a failure. + late: outcome.late.map((l) => lateForReport(l, origin)), + }), + ) + }) + return outcome +} + +/** Sole primary: rethrown unchanged. Otherwise primary first, then labelled cleanup failures. */ +export function throwFixtureOutcome(outcome: FixtureOutcome): void { + const cleanup = outcome.failures.filter((failure) => !failure.duplicateOfPrimary) + if (outcome.primary !== undefined && cleanup.length === 0) throw outcome.primary.value + const labelled = cleanup.map((failure) => new FixtureCleanupError(failure, outcome)) + if (outcome.primary === undefined) { + if (labelled.length === 0) return + if (labelled.length === 1) throw labelled[0] + } + throw new AggregateError( + [...(outcome.primary !== undefined ? [outcome.primary.value] : []), ...labelled], + `Native fixture failed (database ${outcome.database}, drop ${outcome.dropState}): ${cleanup + .map((failure) => failure.step) + .join(', ')}`, + ) +} diff --git a/packages/duron/test/wait-native.test.ts b/packages/duron/test/wait-native.test.ts index 70cde2c..9cfe28e 100644 --- a/packages/duron/test/wait-native.test.ts +++ b/packages/duron/test/wait-native.test.ts @@ -6,6 +6,16 @@ import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' import { Client } from '../src/client.js' import { getPostgresConnection } from './docker.js' +import { + type FixtureObserver, + FixtureBody, + awaitLockGate, + finalizeNativeFixture, + lockReadyWithStatementTimeout, + realClock, + statementTimeoutObserved, + throwFixtureOutcome, +} from './wait-native-fixture.js' async function eventually(check: () => boolean | Promise, timeout = 2_000): Promise { const end = performance.now() + timeout @@ -16,13 +26,70 @@ async function eventually(check: () => boolean | Promise, timeout = 2_0 } } +// The two native fixtures below share one bounded, primary-preserving cleanup (see +// wait-native-fixture.ts). Their outer test timeout is 60s so that the existing ~20s lifecycle +// stop budget plus independent cleanup can be observed; read/wait/observation values are unchanged. +const BODY_BUDGET_MS = 20_000 +const FIXTURE_DEADLINE_MS = 54_000 + +// The original post-stop count statement (same count and predicate) plus same-snapshot safe +// identities: no query text, parameters, client address or credentials (first SQL word only). +function sessionSnapshot(admin: postgres.Sql): Promise { + return admin`SELECT count(*)::int AS count, + clock_timestamp()::text AS sampled_at, + coalesce(json_agg(json_build_object( + 'pid', pid, 'backend_type', backend_type, 'application_name', application_name, + 'backend_start', backend_start, 'state', state, 'xact_start', xact_start, + 'wait_event_type', wait_event_type, 'wait_event', wait_event, + 'keyword', upper(substring(query FROM '^[[:space:]]*([A-Za-z]+)')) + ) ORDER BY pid), '[]'::json) AS sessions + FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid()`.then((rows) => rows[0]) +} + +// Separate observer on the main database: fresh whole-target zero (no pid exclusion) and catalog +// presence for the owned database, before and after its normal drop. Its connection is lazy, so +// the first fresh observation includes connection setup. Keep the session projection in sync with +// sessionSnapshot (different postgres instances, so no shared fragment). +function freshObserver(connectionUrl: string, database: string): FixtureObserver { + const url = new URL(connectionUrl) + url.pathname = '/duron' + const observer = postgres(url.toString(), { max: 1, connection: { statement_timeout: 2000 } }) + return { + fresh: () => + observer`SELECT count(*)::int AS count, + clock_timestamp()::text AS sampled_at, + coalesce(json_agg(json_build_object( + 'pid', pid, 'backend_type', backend_type, 'application_name', application_name, + 'backend_start', backend_start, 'state', state, 'xact_start', xact_start, + 'wait_event_type', wait_event_type, 'wait_event', wait_event, + 'keyword', upper(substring(query FROM '^[[:space:]]*([A-Za-z]+)')) + ) ORDER BY pid), '[]'::json) AS sessions + FROM pg_stat_activity + WHERE datname = ${database}`.then((rows) => rows[0]), + catalogHas: () => + observer`SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = ${database}) AS present`.then( + (rows) => rows[0]!['present'], + ), + close: () => observer.end({ timeout: 5 }), + } +} + +// Fixture evidence (first nonzero observation, retained/unknown DB, cleanup failures) goes to +// stderr independently of the tests' silent client logger. All-zero success prints nothing. +function reportFixture(line: string): void { + console.error(line) +} + const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip suite('Native PostgreSQL wait deadlines', () => { it('interrupts real finite SQL execution rather than only observing elapsed time (owned seeded view)', async () => { + const origin = realClock.now() const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ containerName: 'duron-postgres-test', port: 5440, }) + const database = new URL(CONNECTION_URL).pathname.slice(1) const adapter = new PostgresAdapter({ connection: CONNECTION_URL }) const client = new Client({ database: adapter, @@ -32,38 +99,68 @@ suite('Native PostgreSQL wait deadlines', () => { }) const admin = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 2000 } }) const errors: unknown[] = [] - client.logger.error = (error: unknown) => { + const loggerCalls: unknown[][] = [] + client.logger.error = (error: unknown, ...rest: unknown[]) => { errors.push(error) + loggerCalls.push([error, ...rest]) } + // Every awaited fixture I/O operation is a bounded, observed body step; after an expiry no + // later fixture statement is issued and the body unwinds into the shared finalizer. (The pure + // logger poll below issues no I/O and is bounded only by its own cooperative parameter.) + const body = new FixtureBody(realClock, origin + BODY_BUDGET_MS) + let primary: { value: unknown } | undefined try { - await client.start() - const id = (await adapter.createJob({ - queue: 'execution', - groupKey: 'execution', - input: {}, - timeoutMs: 30000, - checksum: 'execution', - concurrencyLimit: 1, - concurrencyStepLimit: 1, - }))! + await body.step('client.start', () => client.start()) + const id = (await body.step('createJob', () => + adapter.createJob({ + queue: 'execution', + groupKey: 'execution', + input: {}, + timeoutMs: 30000, + checksum: 'execution', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }), + ))! // SQL-only fault fixture in this fresh owned DB. The volatile subquery adds // finite server execution to the real built-in lookup without overriding it. - await admin`ALTER TABLE duron.jobs_active RENAME TO wait_execution_jobs` - await admin`CREATE VIEW duron.jobs_active AS SELECT jobs.* FROM duron.wait_execution_jobs jobs - CROSS JOIN (SELECT pg_sleep(0.4)) execution_delay` - expect(await client.waitForJob(id, { timeout: 1000 })).toBeNull() - await eventually(() => JSON.stringify(errors).includes('57014')) + await body.step( + 'rename jobs_active', + () => admin`ALTER TABLE duron.jobs_active RENAME TO wait_execution_jobs`, + ) + await body.step( + 'create delay view', + () => admin`CREATE VIEW duron.jobs_active AS SELECT jobs.* FROM duron.wait_execution_jobs jobs + CROSS JOIN (SELECT pg_sleep(0.4)) execution_delay`, + ) + expect( + await body.step('waitForJob', () => client.waitForJob(id, { timeout: 1000 })), + ).toBeNull() + // Structured SQLSTATE 57014 evidence, not any logged text containing those digits. + await eventually(() => statementTimeoutObserved(loggerCalls)) expect(JSON.stringify(errors)).toContain('statement timeout') - await client.stop() - const remaining = - await admin`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname=current_database() AND pid<>pg_backend_pid()` - expect(remaining[0]!['count']).toBe(0) - } finally { - await client.stop() - await admin.end({ timeout: 5 }) - await deleteDb() + } catch (error) { + primary = { value: error } } - }, 30_000) + // Stop, then the post-stop count with bounded zero, admin close, strict fresh whole-target + // zero from the main database and a normal drop only on an otherwise clean run. + throwFixtureOutcome( + await finalizeNativeFixture({ + clock: realClock, + origin, + deadline: origin + FIXTURE_DEADLINE_MS, + database, + primary, + body, + stop: () => client.stop(), + sample: () => sessionSnapshot(admin), + endAdmin: () => admin.end({ timeout: 5 }), + openObserver: () => freshObserver(CONNECTION_URL, database), + drop: () => deleteDb(), + report: reportFixture, + }), + ) + }, 60_000) for (const seam of [ 'Client.start', @@ -123,11 +220,13 @@ suite('Native PostgreSQL wait deadlines', () => { } it('bounds a real table-lock read and restores inherited timeout after rollback', async () => { + const origin = realClock.now() const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ containerName: 'duron-postgres-test', port: 5440, }) const url = new URL(CONNECTION_URL) + const database = url.pathname.slice(1) const adapter = new PostgresAdapter({ connection: { host: url.hostname, @@ -151,44 +250,80 @@ suite('Native PostgreSQL wait deadlines', () => { const locked = Promise.withResolvers() const release = Promise.withResolvers() const errors: unknown[] = [] - client.logger.error = (error: unknown) => { + const loggerCalls: unknown[][] = [] + client.logger.error = (error: unknown, ...rest: unknown[]) => { errors.push(error) + loggerCalls.push([error, ...rest]) } + const body = new FixtureBody(realClock, origin + BODY_BUDGET_MS) let holding: Promise | undefined + let primary: { value: unknown } | undefined try { - await client.start() + await body.step('client.start', () => client.start()) holding = blocker.begin(async (tx) => { await tx`LOCK TABLE duron.jobs_active IN ACCESS EXCLUSIVE MODE` locked.resolve() await release.promise }) - await locked.promise - expect(await client.waitForJob(crypto.randomUUID(), { timeout: 500 })).toBeNull() + const held = holding + // Holding is observed at once; lock acquisition is bounded (statement_timeout does not + // bound connection acquisition, JS continuations or driver promises). + await body.step('lock gate', () => + awaitLockGate({ clock: realClock, locked: locked.promise, holding: held, boundMs: 5_000 }), + ) + expect( + await body.step('waitForJob', () => + client.waitForJob(crypto.randomUUID(), { timeout: 500 }), + ), + ).toBeNull() // Native supplement: server timeout must actually end the blocked SELECT, // not merely settle the public observer while retaining a blocked backend. + // The client-side 57014 evidence is awaited in the same window: the native Lock count can + // reach zero before the statement-timeout error reaches the client logger. await eventually(async () => { - const rows = await admin`SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND wait_event_type = 'Lock'` - return rows[0]!['count'] === 0 + const rows = await body.step( + 'lock-wait sample', + () => admin`SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock'`, + ) + return lockReadyWithStatementTimeout(rows[0]!['count'], loggerCalls) }, 500) expect(errors.some((entry) => JSON.stringify(entry).includes('57014'))).toBe(true) release.resolve() - await holding + await body.step('holding', () => held) const driver = (adapter as unknown as { db: { $client: postgres.Sql } }).db.$client expect( - (await driver`SELECT current_setting('statement_timeout') AS timeout`)[0]!['timeout'], + ( + await body.step( + 'inherited timeout', + () => driver`SELECT current_setting('statement_timeout') AS timeout`, + ) + )[0]!['timeout'], ).toBe('2s') - expect(await client.getJobStatus(crypto.randomUUID())).toBeNull() - } finally { - release.resolve() - await holding?.catch(() => undefined) - await client.stop() - await blocker.end({ timeout: 5 }) - const remaining = await admin`SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid()` - expect(remaining[0]!['count']).toBe(0) - await admin.end({ timeout: 5 }) - await deleteDb() + expect( + await body.step('getJobStatus', () => client.getJobStatus(crypto.randomUUID())), + ).toBeNull() + } catch (error) { + primary = { value: error } } - }, 30_000) + throwFixtureOutcome( + await finalizeNativeFixture({ + clock: realClock, + origin, + deadline: origin + FIXTURE_DEADLINE_MS, + database, + primary, + body, + release: () => release.resolve(), + holding, + stop: () => client.stop(), + endBlocker: () => blocker.end({ timeout: 5 }), + sample: () => sessionSnapshot(admin), + endAdmin: () => admin.end({ timeout: 5 }), + openObserver: () => freshObserver(CONNECTION_URL, database), + drop: () => deleteDb(), + report: reportFixture, + }), + ) + }, 60_000) }) From ff7b9fb3c99fa6b1b51b8696d781f17686c62a54 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 28 Nov 2026 22:00:44 -0300 Subject: [PATCH 015/100] chore(postgres): test against postgres.js 4.1.1 postgres.js 3.4.9 throws an uncaught socket.write TypeError on rollback after a lost connection (F1) and reconnects queued work after end() resolves, leaking an idle session (F2); 4.1.1 fixes both in direct reproductions. - prune lock: 4.1.1 calls onclose only for connections that reached ready, so a startup failure never confirmed the owned close. After end(), zero open and opening connections in sql.stats now count as native close evidence; drivers without stats keep waiting for onclose. - tests: wire-based setup-reply oracle, plain-array row comparison, and prune bootstrap expectations for 4.1.1 close behaviour. --- bun.lock | 8 ++-- packages/duron/package.json | 2 +- .../duron/src/adapters/postgres/prune-lock.ts | 15 ++++++++ packages/duron/test/lifecycle-sql.test.ts | 9 +++-- packages/duron/test/prune-bootstrap.test.ts | 37 +++++++------------ packages/duron/test/wait-context.test.ts | 8 +++- 6 files changed, 45 insertions(+), 34 deletions(-) diff --git a/bun.lock b/bun.lock index 715dc78..9190aa5 100644 --- a/bun.lock +++ b/bun.lock @@ -45,7 +45,7 @@ }, "packages/duron": { "name": "duron", - "version": "0.4.0-beta.1", + "version": "0.5.0-beta.0", "dependencies": { "@opentelemetry/api": "^1.9.0", "@opentelemetry/resources": "^2.4.0", @@ -68,13 +68,13 @@ "@types/node": "^24.0.15", "drizzle-kit": "^1.0.0-rc.4", "drizzle-orm": "^1.0.0-rc.4", - "postgres": "^3.4.7", + "postgres": "^4.1.1", "typescript": "^7", }, }, "packages/duron-dashboard": { "name": "duron-dashboard", - "version": "0.4.0-beta.1", + "version": "0.5.0-beta.0", "dependencies": { "@dnd-kit/core": "^6.3.1", "@dnd-kit/modifiers": "^9.0.0", @@ -1344,7 +1344,7 @@ "postcss-selector-parser": ["postcss-selector-parser@7.1.4", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg=="], - "postgres": ["postgres@3.4.9", "", {}, "sha512-GD3qdB0x1z9xgFI6cdRD6xu2Sp2WCOEoe3mtnyB5Ee0XrrL5Pe+e4CCnJrRMnL1zYtRDZmQQVbvOttLnKDLnaw=="], + "postgres": ["postgres@4.1.1", "", {}, "sha512-1kJDojqNZC+iTHHXh6eif0J98LUtyLAePe/qkW1GK35eh2JixlsAiIKq3FGI+xqI+SUGTNodzf7TScVeIIyUug=="], "prettier": ["prettier@3.9.5", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-/FVl766LpUfB5vXgCYOYa0MeV/441Ia99AeICQIQFTY/Nw0roZwULcXpku5i1/m5kt/baz+s4Zogspd839HSMg=="], diff --git a/packages/duron/package.json b/packages/duron/package.json index 5e324c9..2d4a359 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -102,7 +102,7 @@ "@types/node": "^24.0.15", "drizzle-kit": "^1.0.0-rc.4", "drizzle-orm": "^1.0.0-rc.4", - "postgres": "^3.4.7", + "postgres": "^4.1.1", "typescript": "^7" } } diff --git a/packages/duron/src/adapters/postgres/prune-lock.ts b/packages/duron/src/adapters/postgres/prune-lock.ts index 50ef97e..8c3bee5 100644 --- a/packages/duron/src/adapters/postgres/prune-lock.ts +++ b/packages/duron/src/adapters/postgres/prune-lock.ts @@ -154,6 +154,17 @@ export class PostgresPruneLock { } } + /** + * postgres.js 4 creates a connection (and calls `onclose`) only after startup reaches ready; + * a failed startup destroys its socket before leaving `opening`. After `end()`, zero open and + * zero opening connections is native evidence that no socket remains. Drivers without `stats` + * (3.x) keep waiting for `onclose`. + */ + #noDriverConnections(): boolean { + const stats = (this.client as { stats?: { connections: number; opening: number } }).stats + return stats !== undefined && stats.connections === 0 && stats.opening === 0 + } + #confirmClosed(): void { if (!this.#physicallyClosed || !this.#endSettled) return this.#obligation.done = true @@ -167,6 +178,10 @@ export class PostgresPruneLock { // or still-pending acknowledgment cannot consume the owned-close opportunity. try { await this.client.end({ timeout: 5 }) + if (!this.#physicallyClosed && this.#noDriverConnections()) { + this.#physicallyClosed = true + this.#resolveClosed() + } if (!this.#physicallyClosed) await this.#closed this.#obligation.done = true } finally { diff --git a/packages/duron/test/lifecycle-sql.test.ts b/packages/duron/test/lifecycle-sql.test.ts index 00a8681..5e8897f 100644 --- a/packages/duron/test/lifecycle-sql.test.ts +++ b/packages/duron/test/lifecycle-sql.test.ts @@ -75,9 +75,10 @@ for (const factory of [ 'ordinary work has drained', ) const statement = "SELECT to_regclass('duron.clients') AS relation" + // postgres.js 4 Result arrays fail toMatchObject against plain arrays; compare row copies. const rows = driver.query ? (await driver.query(statement)).rows - : await driver.unsafe!(statement) + : [...(await driver.unsafe!(statement))] expect(rows).toMatchObject([{ relation: null }]) adapter._close = close expect(await adapter.stop()).toBe(true) @@ -104,7 +105,7 @@ for (const factory of [ const closeFailure = new Error('injected before owned close') const driver = adapter.db.$client const native = async (text: string): Promise => - driver.query ? (await driver.query(text)).rows : await driver.unsafe!(text) + driver.query ? (await driver.query(text)).rows : [...(await driver.unsafe!(text))] let completedReads = 0 let operation: Promise | undefined try { @@ -154,7 +155,9 @@ for (const factory of [ const closeFailure = new Error('injected before owned close') const driver = adapter.db.$client const native = async (text: string, params?: unknown[]): Promise => - driver.query ? (await driver.query(text, params)).rows : await driver.unsafe!(text, params) + driver.query + ? (await driver.query(text, params)).rows + : [...(await driver.unsafe!(text, params))] let operation: Promise | undefined try { await adapter.start() diff --git a/packages/duron/test/prune-bootstrap.test.ts b/packages/duron/test/prune-bootstrap.test.ts index 1f9eea1..0788953 100644 --- a/packages/duron/test/prune-bootstrap.test.ts +++ b/packages/duron/test/prune-bootstrap.test.ts @@ -183,7 +183,11 @@ if (process.env['POSTGRES_TEST'] === 'true') { client.options.host[0] = '127.0.0.1' client.options.port[0] = relay.port if (failure === 'close acknowledgment') { - const notify = client.options.onclose + // postgres.js 4 still honours options.onclose at runtime but omits it from + // ParsedOptions' type. + const notify = ( + client.options as typeof client.options & { onclose: (id: number) => void } + ).onclose // postgres.js driver option, not an EventTarget event property. Object.assign(client.options, { onclose: (id: number) => { @@ -270,23 +274,11 @@ if (process.env['POSTGRES_TEST'] === 'true') { } } if (failure === 'close acknowledgment') { - await eventually(async () => { - expect(closeNotice).toBe(true) - expect(closeSettled).toBe(true) - }) - let stopSettled = false + // postgres.js 4 creates no connection, and so sends no close notice, before startup + // reaches ready. The owned close settles from the driver's zero open/opening stats. + await eventually(async () => expect(closeSettled).toBe(true)) + expect(closeNotice).toBe(false) stopping = adapter.stop() - void stopping.then( - () => { - stopSettled = true - }, - () => { - stopSettled = true - }, - ) - await Bun.sleep(100) - expect(stopSettled).toBe(false) - deliverClose.resolve() expect(await stopping).toBe(true) } await eventually(async () => expect(reports.length).toBeGreaterThan(0)) @@ -294,14 +286,11 @@ if (process.env['POSTGRES_TEST'] === 'true') { const errors = reports[0] instanceof AggregateError ? reports[0].errors : reports const expected = failure === 'bootstrap reply' - ? [ - { code: 'CONNECTION_CLOSED' }, - { message: 'Incomplete shutdown: owned close exceeded five seconds' }, - ] + ? [{ code: 'CONNECTION_CLOSED' }] : [{ code: failure === 'authentication' ? '28P01' : '57P01' }] - // Real EOF during the identity reply reaches the driver's five-second end - // timeout. Its earlier observer expiry is a separate retained close error, - // not a successful close; require actual late settlement and native absence. + // postgres.js 4 closes promptly after real EOF during the identity reply (3.x waited for + // its five-second end timeout). Exactly one report is still required, and native absence + // and late settlement are asserted below. expect(errors).toMatchObject(expected) expect(reserves).toBe(0) expect(acquisitions).toBe(0) diff --git a/packages/duron/test/wait-context.test.ts b/packages/duron/test/wait-context.test.ts index 4d7c59a..59a7035 100644 --- a/packages/duron/test/wait-context.test.ts +++ b/packages/duron/test/wait-context.test.ts @@ -162,11 +162,15 @@ suite('Native wait transaction context', () => { it('does not start a lookup after a setup reply consumes the observer budget', async () => { const f = await fixture(80) let withholding = false + let setConfigRow = false try { f.queries.length = 0 - f.relay.hold = (tag, connection) => { + f.relay.hold = (tag, connection, frame) => { if (connection.pid !== f.pid) return false - if (tag === 'D' && f.queries.at(-1)?.query.includes('set_config')) withholding = true + // Identify the setup reply from the wire (its RowDescription names the set_config + // column), not from trace-log order, which differs between postgres.js majors. + if (tag === 'T') setConfigRow = frame.includes('set_config') + if (tag === 'D' && setConfigRow) withholding = true return withholding } const waiting = f.client.waitForJob(crypto.randomUUID(), { timeout: 1000 }) From 87caa18993ac4a8457e7921de060e206b7c87a82 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 28 Nov 2026 22:10:48 -0300 Subject: [PATCH 016/100] fix(postgres): wait for driver stats to drain after a timed-out end postgres.js 4 end() resolves after its timeout while a destroyed startup attempt is still counted in stats.opening, and that attempt never calls onclose. Sampling stats once left the prune lock's owned close pending forever. Wait for zero open and opening connections (or onclose) instead; add a native test where startup stalls past the end timeout. --- .../duron/src/adapters/postgres/prune-lock.ts | 31 +++++-- packages/duron/test/prune-bootstrap.test.ts | 92 +++++++++++++++++++ 2 files changed, 113 insertions(+), 10 deletions(-) diff --git a/packages/duron/src/adapters/postgres/prune-lock.ts b/packages/duron/src/adapters/postgres/prune-lock.ts index 8c3bee5..b67d60d 100644 --- a/packages/duron/src/adapters/postgres/prune-lock.ts +++ b/packages/duron/src/adapters/postgres/prune-lock.ts @@ -157,12 +157,27 @@ export class PostgresPruneLock { /** * postgres.js 4 creates a connection (and calls `onclose`) only after startup reaches ready; * a failed startup destroys its socket before leaving `opening`. After `end()`, zero open and - * zero opening connections is native evidence that no socket remains. Drivers without `stats` - * (3.x) keep waiting for `onclose`. + * zero opening connections is native evidence that no socket remains. `end()` can resolve + * after its timeout while a destroyed startup attempt is still leaving `opening`, so wait for + * zero rather than sampling once. Drivers without `stats` (3.x) rely on `onclose` alone. */ - #noDriverConnections(): boolean { - const stats = (this.client as { stats?: { connections: number; opening: number } }).stats - return stats !== undefined && stats.connections === 0 && stats.opening === 0 + #driverDrained(): Promise { + const client = this.client as { stats?: { connections: number; opening: number } } + if (client.stats === undefined) return new Promise(() => undefined) + return new Promise((resolve) => { + const check = () => { + if (this.#physicallyClosed) return resolve() + const stats = client.stats! + if (stats.connections === 0 && stats.opening === 0) { + this.#physicallyClosed = true + this.#resolveClosed() + return resolve() + } + // Bounded by the driver's connect_timeout for any pending startup attempt. + setTimeout(check, 10).unref() + } + check() + }) } #confirmClosed(): void { @@ -178,11 +193,7 @@ export class PostgresPruneLock { // or still-pending acknowledgment cannot consume the owned-close opportunity. try { await this.client.end({ timeout: 5 }) - if (!this.#physicallyClosed && this.#noDriverConnections()) { - this.#physicallyClosed = true - this.#resolveClosed() - } - if (!this.#physicallyClosed) await this.#closed + if (!this.#physicallyClosed) await Promise.race([this.#closed, this.#driverDrained()]) this.#obligation.done = true } finally { this.#endSettled = true diff --git a/packages/duron/test/prune-bootstrap.test.ts b/packages/duron/test/prune-bootstrap.test.ts index 0788953..127ec2e 100644 --- a/packages/duron/test/prune-bootstrap.test.ts +++ b/packages/duron/test/prune-bootstrap.test.ts @@ -144,6 +144,98 @@ if (process.env['POSTGRES_TEST'] === 'true') { } }, 30_000) } + it('bootstrap startup stalled past the driver end timeout still settles the owned close', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const relay = new PruneRelay() + // Startup never reaches ready and the held reply is never released. + relay.hold = (tag, connection) => tag === 'Z' && connection.ready === 1 + let ends = 0 + let endSettled = false + type PruneLockProbe = { client: Sql; close: () => Promise } + let lock: PruneLockProbe | undefined + class StalledBootstrap extends PostgresAdapter { + protected override _acquirePruneLock(): Promise { + const work = super._acquirePruneLock() + if (!lock) { + lock = (this as unknown as { pruneLock: PruneLockProbe }).pruneLock + const { client } = lock + client.options.host[0] = '127.0.0.1' + client.options.port[0] = relay.port + const end = client.end.bind(client) + client.end = async (options) => { + ends++ + try { + await end(options) + } finally { + endSettled = true + } + } + } + return work + } + protected override async _pruneArchive(): Promise { + return 0 + } + } + const adapter = new StalledBootstrap({ + connection: CONNECTION_URL, + pruneArchive: { olderThan: '1d', intervalMs: 20 }, + }) + adapter.setId('stalled-bootstrap-end-timeout') + const observer = postgres(CONNECTION_URL, { max: 1 }) + let stopped: Promise> | undefined + try { + expect(await adapter.start()).toBe(true) + await eventually(async () => expect(relay.held.length).toBeGreaterThan(0)) + stopped = Promise.allSettled([adapter.stop()]).then((results) => results[0]!) + // Stop drains (5s) and cleans up (5s) before the owned close; the driver's five-second + // end timeout then destroys the stalled startup attempt. + await eventually(async () => expect(endSettled).toBe(true), 25_000) + expect(ends).toBe(1) + // postgres.js 4 sends no close notice before ready; the owned close must still settle. + const settled = await Promise.race([ + lock!.close().then( + () => 'settled', + () => 'settled', + ), + Bun.sleep(3_000).then(() => 'pending'), + ]) + expect(settled).toBe('settled') + const stats = (lock!.client as unknown as { stats: { connections: number; opening: number } }) + .stats + expect(stats).toMatchObject({ connections: 0, opening: 0 }) + // Every stop phase waits on the stalled bootstrap: these are reported, never a false close. + const outcome = await stopped + expect(outcome.status).toBe('rejected') + const reason = (outcome as PromiseRejectedResult).reason + const errors: Error[] = reason instanceof AggregateError ? reason.errors : [reason] + expect(errors.map((error) => error.message)).toEqual([ + 'Incomplete shutdown: admitted-work drain exceeded five seconds', + 'Liveness release withheld because admitted work did not drain', + 'Incomplete shutdown: database cleanup exceeded five seconds', + 'Incomplete shutdown: owned close exceeded five seconds', + ]) + await eventually(async () => { + expect( + await observer` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() + `, + ).toHaveLength(0) + }) + expect(relay.errors).toEqual([]) + } finally { + relay.flush() + await stopped + await adapter.stop().catch(() => undefined) + await relay.close() + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 50_000) for (const failure of [ 'authentication', 'initial readiness', From 102f059b89e9153325509d2c9ede52b32cde5bb4 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 28 Nov 2026 23:29:19 -0300 Subject: [PATCH 017/100] fix(postgres): lock recovery jobs before reading their steps Each recovery phase (expired archival, then requeue) now runs in its own transaction: a standalone lock SELECT with the existing predicate and FOR UPDATE SKIP LOCKED, then the existing modifying CTE restricted to the locked IDs through one uuid[] parameter. Under READ COMMITTED the second statement sees every step committed before the job lock, so a discarded checksum no longer leaves a surviving step and expired archival no longer loses a step a creator received. Each phase uses its BEGIN-time now(). Adds native KR tests (old-arm red / candidate green) and adapts the heartbeat-clock fixture so recovery's phase transactions join its owned transaction. --- packages/duron/src/adapters/postgres/base.ts | 69 +- packages/duron/test/heartbeat-clock.test.ts | 9 +- packages/duron/test/recover-snapshot.test.ts | 1247 ++++++++++++++++++ 3 files changed, 1313 insertions(+), 12 deletions(-) create mode 100644 packages/duron/test/recover-snapshot.test.ts diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 8c372d5..f367129 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1261,6 +1261,7 @@ export abstract class PostgresBaseAdapter< /** * Internal method to recover stuck jobs (jobs that were active but the process that owned them is no longer running). * Uses the clients liveness table to detect dead owners: a client whose heartbeat is older than staleTimeoutMs (or missing) is considered dead. + * Expired archival and then requeue each run in their own transaction (see `_recoverLockedJobs`). * * @returns Promise resolving to the number of jobs recovered */ @@ -1290,8 +1291,17 @@ export abstract class PostgresBaseAdapter< let recoveredCount = 0 // Archive expired active jobs from unresponsive clients - const expiredJobs = this._map( - await this.db.execute<{ id: string }>(sql` + recoveredCount += await this._recoverLockedJobs( + sql` + SELECT j.id + FROM ${this.tables.jobsActiveTable} j + WHERE j.status = ${JOB_STATUS_ACTIVE} + AND j.expires_at IS NOT NULL + AND j.expires_at <= now() + AND j.client_id IN ${unresponsiveClientIds} + FOR UPDATE OF j SKIP LOCKED + `, + (lockedIds) => sql` WITH locked_expired_jobs AS ( SELECT j.* FROM ${this.tables.jobsActiveTable} j @@ -1299,6 +1309,7 @@ export abstract class PostgresBaseAdapter< AND j.expires_at IS NOT NULL AND j.expires_at <= now() AND j.client_id IN ${unresponsiveClientIds} + AND j.id = ANY(${lockedIds}) FOR UPDATE OF j SKIP LOCKED ), archived_jobs AS ( @@ -1337,20 +1348,27 @@ export abstract class PostgresBaseAdapter< RETURNING id ) SELECT id FROM deleted_jobs - `), + `, ) - recoveredCount += expiredJobs.length - if (unresponsiveClientIds.length > 0) { - const result = this._map( - await this.db.execute<{ id: string }>(sql` + recoveredCount += await this._recoverLockedJobs( + sql` + SELECT j.id + FROM ${this.tables.jobsActiveTable} j + WHERE j.status = ${JOB_STATUS_ACTIVE} + AND j.client_id IN ${unresponsiveClientIds} + AND (j.expires_at IS NULL OR j.expires_at > now()) + FOR UPDATE OF j SKIP LOCKED + `, + (lockedIds) => sql` WITH locked_jobs AS ( SELECT j.id FROM ${this.tables.jobsActiveTable} j WHERE j.status = ${JOB_STATUS_ACTIVE} AND j.client_id IN ${unresponsiveClientIds} AND (j.expires_at IS NULL OR j.expires_at > now()) + AND j.id = ANY(${lockedIds}) FOR UPDATE OF j SKIP LOCKED ), updated_jobs AS ( @@ -1374,15 +1392,46 @@ export abstract class PostgresBaseAdapter< ) ) SELECT id FROM updated_jobs - `), + `, ) - - recoveredCount += result.length } return recoveredCount } + /** + * Run one recovery phase in its own transaction. The first statement locks the + * phase's jobs; the second runs the phase's modifying statement on those IDs only. + * Under READ COMMITTED the second statement takes a new snapshot after the job + * locks, so it sees every step committed before them. Both statements use the + * transaction's BEGIN-time now(). + * + * @returns Promise resolving to the number of rows the modifying statement returned + */ + private async _recoverLockedJobs( + lockJobs: SQL, + modifyLockedJobs: (lockedIds: SQL) => SQL, + ): Promise { + let phase: Promise | undefined + try { + return await this.db.transaction((tx) => { + phase = (async () => { + const locked: { id: string }[] = this._map(await tx.execute<{ id: string }>(lockJobs)) + if (locked.length === 0) return 0 + // One uuid[] parameter, issued immediately after the lock statement: + // no other await between the two statements. + const lockedIds = sql`${sql.param(locked.map((row) => row.id))}::uuid[]` + return this._map(await tx.execute<{ id: string }>(modifyLockedJobs(lockedIds))).length + })() + return phase + }) + } finally { + // A driver can reject the transaction on connection close before this + // callback settles. That does not discharge the phase's own work. + await phase?.catch(() => undefined) + } + } + // ============================================================================ // Step Methods // ============================================================================ diff --git a/packages/duron/test/heartbeat-clock.test.ts b/packages/duron/test/heartbeat-clock.test.ts index d0df4af..494581f 100644 --- a/packages/duron/test/heartbeat-clock.test.ts +++ b/packages/duron/test/heartbeat-clock.test.ts @@ -143,6 +143,7 @@ for (const factory of [ const adapter = instance.adapter as ClockProbe adapter.setId('clock-own') const execute = adapter.db.execute.bind(adapter.db) + const transaction = adapter.db.transaction const owners = [ 'clock-minus', 'clock-equal', @@ -168,10 +169,12 @@ for (const factory of [ } for (const timeout of [undefined, 1000, 0]) { const milliseconds = timeout ?? 15_000 - // This fixture freezes all predicate references. Ordinary recovery is - // still multi-statement and receives no new snapshot/consistency promise. + // This fixture freezes all predicate references: recovery's statements and + // its phase transactions join this one. Ordinary recovery is still + // multi-statement and receives no new snapshot/consistency promise. await adapter.db.transaction(async (tx) => { adapter.db.execute = tx.execute.bind(tx) + adapter.db.transaction = (work) => work(tx) try { for (const [index, owner] of owners.entries()) { await tx.execute(sql` @@ -223,11 +226,13 @@ for (const factory of [ ]) } finally { adapter.db.execute = execute + adapter.db.transaction = transaction } }) } } finally { adapter.db.execute = execute + adapter.db.transaction = transaction await adapter.stop().catch(() => undefined) const driver = adapter.db.$client if (driver.close && !driver.closed) await driver.close() diff --git a/packages/duron/test/recover-snapshot.test.ts b/packages/duron/test/recover-snapshot.test.ts new file mode 100644 index 0000000..3609e4f --- /dev/null +++ b/packages/duron/test/recover-snapshot.test.ts @@ -0,0 +1,1247 @@ +import { describe, expect, it } from 'bun:test' + +import type { SQL } from 'drizzle-orm' +import postgres from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { type Adapter, type AdapterFactory, pgliteFactory } from './adapters.js' +import { getPostgresConnection } from './docker.js' + +// Recovery step membership (follow-up K-R). Each recovery phase (expired archival, +// then requeue) locks its jobs in a first statement and then runs the modifying +// statement on the locked IDs only, in one transaction. Under READ COMMITTED the +// second statement's snapshot therefore includes every step committed before the +// job lock. Native cases each use a fresh owned database and assert committed rows +// by ID. Controls: owned application_name-filtered advisory-lock triggers, a +// test-only barrier inside one recovery transaction, owned step-row locks and +// SELECT-only native observation. No connection close or session termination. + +const KEY_RECOVERY = 91_401 +const KEY_CREATOR = 91_402 +const OBSERVE_MS = 2_000 +const TEST_MS = 30_000 +const OLD_CHECKSUM = 'old-checksum' +const NEW_CHECKSUM = 'new-checksum' + +type Settled = { status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown } + +function observe(promise: Promise): Promise> { + return promise.then( + (value) => ({ status: 'fulfilled', value }), + (reason: unknown) => ({ status: 'rejected', reason }), + ) +} + +function fulfilment(settled: Settled): T { + if (settled.status === 'rejected') { + throw new Error('Expected fulfilment', { cause: settled.reason }) + } + return settled.value +} + +function rejection(settled: Settled): unknown { + expect(settled.status).toBe('rejected') + return (settled as { reason: unknown }).reason +} + +async function eventually(check: () => boolean | Promise): Promise { + const end = performance.now() + OBSERVE_MS + while (!(await check())) { + if (performance.now() >= end) throw new Error('Condition exceeded bounded observation') + await Bun.sleep(5) + } +} + +async function within(promise: Promise, label: string): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`${label} exceeded bounded observation`)), + OBSERVE_MS, + ) + }), + ]) + } finally { + clearTimeout(timer) + } +} + +// Evidence: every case prints the rows it asserts. +function record(label: string, value: unknown): void { + // oxlint-disable-next-line no-console + console.log(`[KR] ${label} ${JSON.stringify(value)}`) +} + +type TransactionDb = { + transaction: (work: (tx: any) => Promise, config?: unknown) => Promise + dialect: { sqlToQuery: (query: SQL) => { sql: string; params: unknown[] } } +} + +function dbOf(adapter: Adapter): TransactionDb { + return (adapter as unknown as { db: TransactionDb }).db +} + +type Gate = { reached: Promise; release: () => void; fail: (error: Error) => void } + +// Test-only barrier inside recovery's Nth transaction (1 = expired archival, +// 2 = requeue): pauses before its Nth statement (1 = job lock, 2 = modifying +// statement). fail() rejects inside the callback, so the transaction rolls back. +// The single-statement shape opens no transaction and never reaches it. +function gateRecovery( + adapter: Adapter, + pause: { transaction: 1 | 2; beforeStatement: 1 | 2 }, +): Gate { + const db = dbOf(adapter) + const guarded = db.transaction + const reached = Promise.withResolvers() + const open = Promise.withResolvers() + reached.promise.catch(() => undefined) + open.promise.catch(() => undefined) + let transactions = 0 + db.transaction = (work, config) => { + if (++transactions < pause.transaction) return guarded.call(db, work, config) + db.transaction = guarded + const transaction = guarded.call( + db, + (tx: object) => { + let statements = 0 + return work( + new Proxy(tx, { + get(object, property) { + const value = Reflect.get(object, property, object) + if (property !== 'execute') { + return typeof value === 'function' ? value.bind(object) : value + } + return async (...args: unknown[]) => { + if (++statements === pause.beforeStatement) { + reached.resolve() + await open.promise + } + return await value.apply(object, args) + } + }, + }), + ) + }, + config, + ) + const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) + transaction.then(endedEarly, endedEarly) + return transaction + } + return { + reached: reached.promise, + release: () => { + db.transaction = guarded + open.resolve() + }, + fail: (error) => { + db.transaction = guarded + open.reject(error) + }, + } +} + +type RecordedStatement = { transaction: number; sql: string; params: unknown[] } + +// Records the SQL text and parameters of every transaction statement issued +// during one call (static binding evidence); the statements still run unchanged. +async function recordTransactions( + adapter: Adapter, + call: () => Promise, +): Promise<{ result: T; statements: RecordedStatement[] }> { + const db = dbOf(adapter) + const guarded = db.transaction + const statements: RecordedStatement[] = [] + let transactions = 0 + db.transaction = (work, config) => { + const transaction = ++transactions + return guarded.call( + db, + (tx: object) => + work( + new Proxy(tx, { + get(object, property) { + const value = Reflect.get(object, property, object) + if (property !== 'execute') { + return typeof value === 'function' ? value.bind(object) : value + } + return (query: SQL) => { + const { sql, params } = db.dialect.sqlToQuery(query) + statements.push({ transaction, sql, params }) + return value.call(object, query) + } + }, + }), + ), + config, + ) + } + try { + return { result: await call(), statements } + } finally { + db.transaction = guarded + } +} + +function arrays(statement: RecordedStatement): unknown[] { + return statement.params.filter((param) => Array.isArray(param)) +} + +function errorMessages(error: unknown): string { + const messages: string[] = [] + let cause = error as { message?: unknown; cause?: unknown } | null | undefined + for (let depth = 0; cause && depth < 5; depth++) { + messages.push(String(cause.message)) + cause = cause.cause as typeof cause + } + return messages.join(' <- ') +} + +type StepRow = { id: string; status: string } + +async function recoveryDatabase() { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + const url = new URL(CONNECTION_URL) + const name = url.pathname.slice(1) + const session = (applicationName: string) => + postgres(CONNECTION_URL, { + max: 1, + connection: { application_name: applicationName, statement_timeout: 5_000 }, + }) + const admin = session('kr-admin') + const barrier = session('kr-barrier') + const locker = session('kr-locker') + const adapters: PostgresAdapter[] = [] + const inFlight: Promise[] = [] + let lockHolder: { release: () => void; done: Promise } | null = null + + const lockWaitBlockers = async (applicationName: string): Promise => { + const rows = await admin` + SELECT ARRAY( + SELECT b.application_name FROM pg_stat_activity b + WHERE b.pid = ANY(pg_blocking_pids(a.pid)) + ) AS blockers + FROM pg_stat_activity a + WHERE a.datname = current_database() AND a.application_name = ${applicationName} + AND a.wait_event_type = 'Lock'` + return rows.length > 0 ? (rows.flatMap((row) => row['blockers']) as string[]) : null + } + const atAdvisory = async (applicationName: string): Promise => { + const rows = await admin` + SELECT 1 FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid + WHERE l.locktype = 'advisory' AND NOT l.granted AND a.application_name = ${applicationName}` + return rows.length > 0 + } + + return { + admin, + async adapter(id: string) { + const instance = new PostgresAdapter({ + connection: { + host: url.hostname, + port: Number(url.port), + database: name, + user: url.username, + password: url.password, + connection: { application_name: id, statement_timeout: 10_000 }, + }, + }) + instance.setId(id) + adapters.push(instance) + await instance.start() + return instance + }, + // Observes a call without rejecting; cleanup awaits it after every gate is released. + observe(promise: Promise): Promise> { + const settled = observe(promise) + inFlight.push(settled) + return settled + }, + // Native row-lock wait evidence (pg_blocking_pids), or settlement, whichever is first. + async settledOrWaiting( + pending: Promise>, + applicationName: string, + ): Promise<{ outcome: 'settled' } | { outcome: 'waiting'; blockers: string[] }> { + let settled = false + void pending.then(() => (settled = true)) + let blockers: string[] | null = null + await eventually(async () => { + if (settled) return true + blockers = await lockWaitBlockers(applicationName) + return blockers !== null + }) + return settled ? { outcome: 'settled' } : { outcome: 'waiting', blockers: blockers! } + }, + async settledOrAtAdvisory( + pending: Promise>, + applicationName: string, + ): Promise<'settled' | 'advisory'> { + let settled = false + void pending.then(() => (settled = true)) + await eventually(async () => settled || (await atAdvisory(applicationName))) + return settled ? 'settled' : 'advisory' + }, + async waitingAtAdvisory(applicationName: string): Promise { + await eventually(() => atAdvisory(applicationName)) + }, + // First pause reached: the recovery transaction barrier or an advisory trigger. + async firstPause(gate: Gate, applicationName: string): Promise<'barrier' | 'advisory'> { + let barrierReached = false + void gate.reached.then( + () => (barrierReached = true), + () => undefined, + ) + await eventually(async () => barrierReached || (await atAdvisory(applicationName))) + return barrierReached ? 'barrier' : 'advisory' + }, + async untilExpired(jobId: string): Promise { + await eventually(async () => { + const rows = await admin` + SELECT expires_at <= now() AS expired FROM duron.jobs_active WHERE id = ${jobId}` + return rows[0]?.['expired'] === true + }) + }, + async job(jobId: string) { + const active = await admin` + SELECT status, client_id, started_at, expires_at, finished_at, output, error + FROM duron.jobs_active WHERE id = ${jobId}` + const archive = await admin` + SELECT status, client_id, error, finished_at::text AS finished_at, + updated_at::text AS updated_at + FROM duron.jobs_archive WHERE id = ${jobId}` + return { active: active[0] ?? null, archive: archive[0] ?? null } + }, + async steps(jobId: string): Promise<{ active: StepRow[]; archive: StepRow[] }> { + const active = await admin` + SELECT id, status FROM duron.job_steps_active WHERE job_id = ${jobId} ORDER BY id` + const archive = await admin` + SELECT id, status FROM duron.job_steps_archive WHERE job_id = ${jobId} ORDER BY id` + return { active: [...active], archive: [...archive] } + }, + // Owned row lock on one step, held in an owned session until released. + async lockStepRow(stepId: string): Promise { + const locked = Promise.withResolvers() + const open = Promise.withResolvers() + const done = locker + .begin(async (sql) => { + await sql`SELECT id FROM duron.job_steps_active WHERE id = ${stepId} FOR UPDATE` + locked.resolve() + await open.promise + }) + .catch((error: unknown) => locked.reject(error)) + lockHolder = { release: () => open.resolve(), done } + await locked.promise + }, + async releaseStepRow(): Promise { + const holder = lockHolder + lockHolder = null + if (!holder) return + holder.release() + await holder.done + }, + // Owned test-only trigger: the named session's statement (or row) waits on an + // advisory lock held by the barrier session. Statement triggers fire after the + // statement snapshot exists and before the statement takes any row lock. + async installBarrier(options: { + name: string + table: 'jobs_active' | 'jobs_archive' | 'job_steps_active' + event: 'INSERT' | 'UPDATE' + level: 'STATEMENT' | 'ROW' + applicationName: string + key: number + stepName?: string + }): Promise { + const stepFilter = options.stepName ? ` AND NEW.name = '${options.stepName}'` : '' + const result = options.level === 'ROW' ? 'NEW' : 'NULL' + await admin.unsafe(` + CREATE FUNCTION duron.${options.name}() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF current_setting('application_name') = '${options.applicationName}'${stepFilter} THEN + PERFORM pg_advisory_xact_lock(${options.key}); + END IF; + RETURN ${result}; + END $$; + CREATE TRIGGER ${options.name} BEFORE ${options.event} ON duron.${options.table} + FOR EACH ${options.level} EXECUTE FUNCTION duron.${options.name}(); + `) + }, + async hold(key: number): Promise { + await barrier`SELECT pg_advisory_lock(${key})` + }, + async release(key: number): Promise { + await barrier`SELECT pg_advisory_unlock(${key})` + }, + // Drop only after fresh evidence of zero other sessions; otherwise retain and fail. + async cleanup(): Promise { + try { + lockHolder?.release() + await lockHolder?.done + await barrier`SELECT pg_advisory_unlock_all()`.catch(() => undefined) + const drained = await Promise.race([ + Promise.all(inFlight).then(() => true), + Bun.sleep(5_000).then(() => false), + ]) + if (!drained) throw new Error('Observed calls did not settle after release') + for (const instance of adapters) await instance.stop().catch(() => undefined) + await barrier.end({ timeout: 5 }) + await locker.end({ timeout: 5 }) + await eventually(async () => { + const rows = await admin` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid()` + return rows[0]!['count'] === 0 + }) + } catch (error) { + throw new Error(`Retained owned database ${name}`, { cause: error }) + } finally { + await admin.end({ timeout: 5 }) + } + await deleteDb() + }, + } +} + +type RecoveryDatabase = Awaited> + +// Keeps the primary test failure when cleanup also fails (and retains the database). +async function withDatabase(test: (db: RecoveryDatabase) => Promise): Promise { + const db = await recoveryDatabase() + let failed = false + let failure: unknown + try { + await test(db) + } catch (error) { + failed = true + failure = error + } + try { + await db.cleanup() + } catch (cleanupError) { + if (!failed) throw cleanupError + // oxlint-disable-next-line preserve-caught-error + throw new AggregateError([failure, cleanupError], 'Test failed and cleanup failed') + } + if (failed) throw failure +} + +let jobCounter = 0 + +async function createJob( + adapter: Adapter, + options: { timeoutMs?: number; checksum?: string } = {}, +): Promise { + const index = ++jobCounter + return (await adapter.createJob({ + queue: 'recover-snapshot', + groupKey: `recover-snapshot-${index}-${crypto.randomUUID()}`, + input: { index }, + timeoutMs: options.timeoutMs ?? 60_000, + checksum: options.checksum ?? OLD_CHECKSUM, + concurrencyLimit: 100, + concurrencyStepLimit: 10, + }))! +} + +function createStep(adapter: Adapter, jobId: string, name: string) { + return adapter.createOrRecoverJobStep({ jobId, name, timeoutMs: 60_000, retriesLimit: 0 }) +} + +// Worker W claims a job and creates an active step s1. +async function claimedJobWithStep(w: Adapter, timeoutMs = 60_000) { + const jobId = await createJob(w, { timeoutMs }) + expect((await w.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + const s1 = (await createStep(w, jobId, 's1'))! + expect(s1).not.toBeNull() + return { jobId, s1: s1.id } +} + +// Requeue and expired archival lock the job and then block on an owned step-row +// lock (the requeue step DELETE / the archival cascade), so they hold the job. +async function recoveryHoldingJob(db: RecoveryDatabase, r: Adapter, s1: string) { + await db.lockStepRow(s1) + const recovery = db.observe(r.recoverJobs({ checksums: [NEW_CHECKSUM] })) + expect(await db.settledOrWaiting(recovery, 'r')).toEqual({ + outcome: 'waiting', + blockers: ['kr-locker'], + }) + return { recovery } +} + +const native = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip + +native('Native PostgreSQL recovery step membership', () => { + describe('requeue with a discarded checksum (KR1/KR1b)', () => { + it( + 'KR1: a step created after the requeue selects the job never survives the requeue', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w) + // Single-statement shape: pauses after its snapshot, before its job lock. + // Lock-first shape: pauses inside the modifying statement, after the lock. + await db.installBarrier({ + name: 'kr_requeue_barrier', + table: 'jobs_active', + event: 'UPDATE', + level: 'STATEMENT', + applicationName: 'r', + key: KEY_RECOVERY, + }) + await db.hold(KEY_RECOVERY) + try { + const recovery = db.observe(r.recoverJobs({ checksums: [NEW_CHECKSUM] })) + await db.waitingAtAdvisory('r') + const creation = db.observe(createStep(w, jobId, 's2')) + const creator = await db.settledOrWaiting(creation, 'w') + await db.release(KEY_RECOVERY) + const recovered = fulfilment(await recovery) + const created = fulfilment(await creation) + const steps = await db.steps(jobId) + const job = await db.job(jobId) + record('KR1', { s1, created: created?.id ?? null, creator, recovered, steps, job }) + // Storage by row ID first: a returned step must not survive the discard. + if (created) expect(steps.active.map((step) => step.id)).not.toContain(created.id) + expect(steps).toEqual({ active: [], archive: [] }) + expect(recovered).toBe(1) + expect(job.active).toMatchObject({ status: 'created', client_id: 'w' }) + expect(created).toBeNull() + expect(creator).toEqual({ outcome: 'waiting', blockers: ['r'] }) + } finally { + await db.release(KEY_RECOVERY) + } + }) + }, + TEST_MS, + ) + + for (const writer of ['completeJobStep', 'failJobStep'] as const) { + it( + `KR1b: the next run never recovers a ${writer === 'completeJobStep' ? 'completed' : 'failed'} step from the discarded execution`, + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId } = await claimedJobWithStep(w) + await db.installBarrier({ + name: 'kr_requeue_barrier', + table: 'jobs_active', + event: 'UPDATE', + level: 'STATEMENT', + applicationName: 'r', + key: KEY_RECOVERY, + }) + await db.hold(KEY_RECOVERY) + let stale: { id: string } | null = null + let staleWrite: boolean | null = null + try { + const recovery = db.observe(r.recoverJobs({ checksums: [NEW_CHECKSUM] })) + await db.waitingAtAdvisory('r') + const creation = db.observe(createStep(w, jobId, 's2')) + const creator = await db.settledOrWaiting(creation, 'w') + if (creator.outcome === 'settled') { + // The stale execution finishes its step while the job is still active. + stale = fulfilment(await creation) + if (stale) { + staleWrite = + writer === 'completeJobStep' + ? await w.completeJobStep({ stepId: stale.id, output: { stale: true } }) + : await w.failJobStep({ stepId: stale.id, error: { message: 'stale' } }) + } + } + await db.release(KEY_RECOVERY) + expect(fulfilment(await recovery)).toBe(1) + stale ??= fulfilment(await creation) + // The next execution of the requeued job asks for the same step. + expect((await w.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + const again = await createStep(w, jobId, 's2') + record('KR1b', { writer, creator, stale: stale?.id ?? null, staleWrite, again }) + expect(again).toMatchObject({ isNew: true, status: 'active', output: null }) + expect(again?.id).not.toBe(stale?.id) + expect(stale).toBeNull() + expect(creator).toEqual({ outcome: 'waiting', blockers: ['r'] }) + } finally { + await db.release(KEY_RECOVERY) + } + }) + }, + TEST_MS, + ) + } + }) + + it( + 'KR2: a retained checksum keeps every step a creator committed or returned (preserved)', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w) + await db.installBarrier({ + name: 'kr_requeue_barrier', + table: 'jobs_active', + event: 'UPDATE', + level: 'STATEMENT', + applicationName: 'r', + key: KEY_RECOVERY, + }) + await db.hold(KEY_RECOVERY) + try { + const recovery = db.observe(r.recoverJobs({ checksums: [OLD_CHECKSUM] })) + await db.waitingAtAdvisory('r') + const creation = db.observe(createStep(w, jobId, 's2')) + const creator = await db.settledOrWaiting(creation, 'w') + await db.release(KEY_RECOVERY) + const recovered = fulfilment(await recovery) + const created = fulfilment(await creation) + const steps = await db.steps(jobId) + record('KR2', { s1, created: created?.id ?? null, creator, recovered, steps }) + const expected = [s1, ...(created ? [created.id] : [])].toSorted() + expect(steps.active.map((step) => step.id)).toEqual(expected) + expect(steps.archive).toEqual([]) + expect(recovered).toBe(1) + expect((await db.job(jobId)).active).toMatchObject({ status: 'created', client_id: 'w' }) + } finally { + await db.release(KEY_RECOVERY) + } + }) + }, + TEST_MS, + ) + + describe('expired archival (KR3)', () => { + it( + 'KR3a: a creator holding the job at the lock makes archival skip it; the next pass archives its step', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w, 1_500) + // The creator passes its job check (KEY SHARE) and then waits in its row insert. + await db.installBarrier({ + name: 'kr_creator_barrier', + table: 'job_steps_active', + event: 'INSERT', + level: 'ROW', + applicationName: 'w', + key: KEY_CREATOR, + stepName: 's-late', + }) + await db.installBarrier({ + name: 'kr_archive_barrier', + table: 'jobs_archive', + event: 'INSERT', + level: 'STATEMENT', + applicationName: 'r', + key: KEY_RECOVERY, + }) + await db.hold(KEY_CREATOR) + await db.hold(KEY_RECOVERY) + try { + const creation = db.observe(createStep(w, jobId, 's-late')) + await db.waitingAtAdvisory('w') + await db.untilExpired(jobId) + const firstRecovery = db.observe(r.recoverJobs({ checksums: [OLD_CHECKSUM] })) + const firstOutcome = await db.settledOrAtAdvisory(firstRecovery, 'r') + await db.release(KEY_CREATOR) + const created = fulfilment(await creation) + await db.release(KEY_RECOVERY) + const firstPass = fulfilment(await firstRecovery) + const stillActive = (await db.job(jobId)).active !== null + const secondPass = stillActive + ? fulfilment(await db.observe(r.recoverJobs({ checksums: [OLD_CHECKSUM] }))) + : 0 + const steps = await db.steps(jobId) + const job = await db.job(jobId) + record('KR3a', { + s1, + created: created?.id ?? null, + firstOutcome, + firstPass, + secondPass, + steps, + job, + }) + // Storage by row ID first: the returned step is in one of the two stores. + expect(created).not.toBeNull() + const stored = [...steps.active, ...steps.archive].map((step) => step.id) + expect(stored).toContain(created!.id) + expect(steps.active).toEqual([]) + expect(steps.archive.map((step) => step.id)).toEqual([s1, created!.id].toSorted()) + expect(job.active).toBeNull() + expect(job.archive).toMatchObject({ + status: 'failed', + error: { message: 'Job expired after exceeding timeout' }, + }) + expect(firstPass + secondPass).toBe(1) + // Branch: the first pass skipped the job held by the creator. + expect({ firstOutcome, firstPass, secondPass }).toEqual({ + firstOutcome: 'settled', + firstPass: 0, + secondPass: 1, + }) + } finally { + await db.release(KEY_CREATOR) + await db.release(KEY_RECOVERY) + } + }) + }, + TEST_MS, + ) + + it( + 'KR3b: a creator reaching its job check after the archival lock waits and returns null', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w, 1_500) + // The creator's statement fixes now() before expiry, then waits before its job check. + await db.installBarrier({ + name: 'kr_creator_barrier', + table: 'job_steps_active', + event: 'INSERT', + level: 'STATEMENT', + applicationName: 'w', + key: KEY_CREATOR, + }) + await db.installBarrier({ + name: 'kr_archive_barrier', + table: 'jobs_archive', + event: 'INSERT', + level: 'STATEMENT', + applicationName: 'r', + key: KEY_RECOVERY, + }) + await db.hold(KEY_CREATOR) + await db.hold(KEY_RECOVERY) + try { + const creation = db.observe(createStep(w, jobId, 's-late')) + await db.waitingAtAdvisory('w') + await db.untilExpired(jobId) + const recovery = db.observe(r.recoverJobs({ checksums: [OLD_CHECKSUM] })) + await db.waitingAtAdvisory('r') + await db.release(KEY_CREATOR) + const creator = await db.settledOrWaiting(creation, 'w') + await db.release(KEY_RECOVERY) + const recovered = fulfilment(await recovery) + const created = fulfilment(await creation) + const steps = await db.steps(jobId) + const job = await db.job(jobId) + record('KR3b', { s1, created: created?.id ?? null, creator, recovered, steps, job }) + if (created) { + const stored = [...steps.active, ...steps.archive].map((step) => step.id) + expect(stored).toContain(created.id) + } + expect(steps).toEqual({ active: [], archive: [{ id: s1, status: 'active' }] }) + expect(job.archive?.['status']).toBe('failed') + expect(recovered).toBe(1) + expect(created).toBeNull() + expect(creator).toEqual({ outcome: 'waiting', blockers: ['r'] }) + } finally { + await db.release(KEY_CREATOR) + await db.release(KEY_RECOVERY) + } + }) + }, + TEST_MS, + ) + + // S2 freshness, not a latest-version guarantee. completeJobStep is not used: + // its expiry guard rejects every write on an expired job. + const writers = [ + { + name: 'failJobStep', + write: (w: Adapter, stepId: string) => w.failJobStep({ stepId, error: { message: 'x' } }), + expected: { status: 'failed', retries_count: 0, delayed_ms: null }, + }, + { + name: 'delayJobStep', + write: (w: Adapter, stepId: string) => + w.delayJobStep({ stepId, delayMs: 1_234, error: { message: 'x' } }), + expected: { status: 'active', retries_count: 1, delayed_ms: 1_234 }, + }, + { + name: 'cancelJobStep', + write: (w: Adapter, stepId: string) => w.cancelJobStep({ stepId }), + expected: { status: 'cancelled', retries_count: 0, delayed_ms: null }, + }, + ] + for (const writer of writers) { + it( + `KR3c: archival copies a ${writer.name} write committed after the job was selected`, + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w, 500) + // Single-statement shape: pauses after its snapshot, before its job lock. + await db.installBarrier({ + name: 'kr_archive_barrier', + table: 'jobs_archive', + event: 'INSERT', + level: 'STATEMENT', + applicationName: 'r', + key: KEY_RECOVERY, + }) + await db.hold(KEY_RECOVERY) + await db.untilExpired(jobId) + // Lock-first shape: pauses after the archival job lock, before the copy. + const gate = gateRecovery(r, { transaction: 1, beforeStatement: 2 }) + try { + const recovery = db.observe(r.recoverJobs({ checksums: [OLD_CHECKSUM] })) + const pause = await db.firstPause(gate, 'r') + const written = fulfilment(await db.observe(writer.write(w, s1))) + await db.release(KEY_RECOVERY) + gate.release() + const recovered = fulfilment(await recovery) + const archived = await db.admin` + SELECT id, status, retries_count, delayed_ms FROM duron.job_steps_archive + WHERE job_id = ${jobId}` + const steps = await db.steps(jobId) + record('KR3c', { writer: writer.name, pause, written, recovered, archived }) + expect(written).toBe(true) + expect(steps.active).toEqual([]) + expect([...archived]).toEqual([{ id: s1, ...writer.expected }]) + expect(recovered).toBe(1) + expect(pause).toBe('barrier') + } finally { + gate.release() + await db.release(KEY_RECOVERY) + } + }) + }, + TEST_MS, + ) + } + }) + + it( + 'KR5: a creator holding the job makes requeue skip it; the next pass requeues and discards (preserved)', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w) + await db.installBarrier({ + name: 'kr_creator_barrier', + table: 'job_steps_active', + event: 'INSERT', + level: 'ROW', + applicationName: 'w', + key: KEY_CREATOR, + stepName: 's2', + }) + await db.hold(KEY_CREATOR) + try { + const creation = db.observe(createStep(w, jobId, 's2')) + await db.waitingAtAdvisory('w') + const firstPass = fulfilment( + await db.observe(r.recoverJobs({ checksums: [NEW_CHECKSUM] })), + ) + await db.release(KEY_CREATOR) + const created = fulfilment(await creation) + const secondPass = fulfilment( + await db.observe(r.recoverJobs({ checksums: [NEW_CHECKSUM] })), + ) + const steps = await db.steps(jobId) + record('KR5', { s1, created: created?.id ?? null, firstPass, secondPass, steps }) + expect(created).not.toBeNull() + expect(steps).toEqual({ active: [], archive: [] }) + expect({ firstPass, secondPass }).toEqual({ firstPass: 0, secondPass: 1 }) + expect((await db.job(jobId)).active).toMatchObject({ status: 'created', client_id: 'w' }) + } finally { + await db.release(KEY_CREATOR) + } + }) + }, + TEST_MS, + ) + + it( + 'KR7: each phase uses its BEGIN-time now(); a job expiring before the requeue phase is deferred', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const expired = await createJob(w, { timeoutMs: 300 }) + const straddling = await createJob(w, { timeoutMs: 1_500 }) + expect((await w.fetch({ batch: 2 })).map((job) => job.id).toSorted()).toEqual( + [expired, straddling].toSorted(), + ) + const expiredStep = (await createStep(w, expired, 's1'))! + const straddlingStep = (await createStep(w, straddling, 's1'))! + await db.untilExpired(expired) + // Pause the archival transaction after BEGIN, before its job lock. + const gate = gateRecovery(r, { transaction: 1, beforeStatement: 1 }) + try { + const recovery = db.observe(r.recoverJobs({ checksums: [OLD_CHECKSUM] })) + await within(gate.reached, 'archival transaction barrier') + const [begin] = await db.admin` + SELECT xact_start::text AS xact_start FROM pg_stat_activity + WHERE datname = current_database() AND application_name = 'r' + AND xact_start IS NOT NULL` + // The straddling job expires after archival's BEGIN and before requeue's. + await db.untilExpired(straddling) + gate.release() + const firstPass = fulfilment(await recovery) + const archivedJob = (await db.job(expired)).archive + const [archivedStep] = await db.admin` + SELECT job_finished_at::text AS job_finished_at FROM duron.job_steps_archive + WHERE id = ${expiredStep.id}` + const deferred = await db.job(straddling) + const deferredSteps = await db.steps(straddling) + record('KR7', { begin, firstPass, archivedJob, archivedStep, deferred, deferredSteps }) + expect(firstPass).toBe(1) + expect(archivedJob).toMatchObject({ + status: 'failed', + finished_at: begin!['xact_start'], + updated_at: begin!['xact_start'], + }) + expect(archivedStep).toEqual({ job_finished_at: begin!['xact_start'] }) + expect(deferred.archive).toBeNull() + expect(deferred.active).toMatchObject({ status: 'active', client_id: 'w' }) + expect(deferredSteps).toEqual({ + active: [{ id: straddlingStep.id, status: 'active' }], + archive: [], + }) + // The next pass archives the deferred job. + expect(fulfilment(await db.observe(r.recoverJobs({ checksums: [OLD_CHECKSUM] })))).toBe(1) + expect((await db.job(straddling)).archive?.['status']).toBe('failed') + } finally { + gate.release() + } + }) + }, + TEST_MS, + ) + + it( + 'KR8: a stop before the modifying statement rolls the phase back and rejects recovery', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const { jobId, s1 } = await claimedJobWithStep(w, 300) + await db.untilExpired(jobId) + const probe = r as unknown as { _close: () => Promise } + const close = probe._close + const closeFailure = new Error('injected before owned close') + // Keep the connection usable: this is a lifecycle gate, not a socket fault. + probe._close = async () => { + throw closeFailure + } + const gate = gateRecovery(r, { transaction: 1, beforeStatement: 2 }) + try { + const recovery = db.observe(r.recoverJobs({ checksums: [OLD_CHECKSUM] })) + await within(gate.reached, 'archival modifying-statement barrier') + const stopped = await r.stop().catch((error: unknown) => error) + expect(stopped).toBeInstanceOf(AggregateError) + expect((stopped as AggregateError).errors).toContain(closeFailure) + gate.release() + const error = errorMessages(rejection(await recovery)) + const job = await db.job(jobId) + const steps = await db.steps(jobId) + record('KR8', { error, job, steps }) + expect(error).toContain('ordinary work has drained') + expect(job.archive).toBeNull() + expect(job.active).toMatchObject({ status: 'active', client_id: 'w' }) + expect(steps).toEqual({ active: [{ id: s1, status: 'active' }], archive: [] }) + // The rolled-back phase released its job lock: another recovery archives the job. + const r2 = await db.adapter('r2') + expect(await r2.recoverJobs({ checksums: [OLD_CHECKSUM] })).toBe(1) + expect((await db.steps(jobId)).archive).toEqual([{ id: s1, status: 'active' }]) + probe._close = close + expect(await r.stop()).toBe(true) + } finally { + gate.release() + probe._close = close + } + }) + }, + TEST_MS, + ) + + describe('competitors against a requeue holding the job (KR9, preserved)', () => { + it( + 'KR9: a cancellation waits for the requeue and then cancels the requeued job', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const c = await db.adapter('c') + const { jobId, s1 } = await claimedJobWithStep(w) + try { + const { recovery } = await recoveryHoldingJob(db, r, s1) + const cancel = db.observe(c.cancelJob({ jobId })) + const waited = await db.settledOrWaiting(cancel, 'c') + await db.releaseStepRow() + expect(fulfilment(await recovery)).toBe(1) + expect(fulfilment(await cancel)).toBe(true) + const job = await db.job(jobId) + const steps = await db.steps(jobId) + record('KR9-cancel', { waited, job, steps }) + expect(waited).toEqual({ outcome: 'waiting', blockers: ['r'] }) + expect(job.archive?.['status']).toBe('cancelled') + expect(steps).toEqual({ active: [], archive: [] }) + } finally { + await db.releaseStepRow() + } + }) + }, + TEST_MS, + ) + + it( + 'KR9: deleteJob, a second recovery and a claim do not wait and leave the held job alone', + async () => { + await withDatabase(async (db) => { + const w = await db.adapter('w') + const r = await db.adapter('r') + const r2 = await db.adapter('r2') + const d = await db.adapter('d') + const f = await db.adapter('f') + const { jobId, s1 } = await claimedJobWithStep(w) + try { + const { recovery } = await recoveryHoldingJob(db, r, s1) + const deleted = fulfilment(await db.observe(d.deleteJob({ jobId }))) + const second = fulfilment( + await db.observe(r2.recoverJobs({ checksums: [NEW_CHECKSUM] })), + ) + const claimed = fulfilment(await db.observe(f.fetch({ batch: 1 }))) + await db.releaseStepRow() + const recovered = fulfilment(await recovery) + record('KR9-skip', { + deleted, + second, + claimed: claimed.map((job) => job.id), + recovered, + }) + expect({ deleted, second, claimed, recovered }).toEqual({ + deleted: false, + second: 0, + claimed: [], + recovered: 1, + }) + expect(await db.steps(jobId)).toEqual({ active: [], archive: [] }) + expect((await f.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + } finally { + await db.releaseStepRow() + } + }) + }, + TEST_MS, + ) + }) +}) + +// Sequential selection, counts, fields and array binding on both SQL engines (KR6/KR10/KR11). +// No concurrency is claimed here; PGLite runs one transaction at a time. +const engines: AdapterFactory[] = [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' + ? [ + { + name: 'postgres' as const, + create: async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + return { + adapter: new PostgresAdapter({ connection: CONNECTION_URL }), + deleteDb, + connectionUrl: CONNECTION_URL, + } + }, + }, + ] + : []), +] + +for (const factory of engines) { + describe(`Recovery selection and binding with ${factory.name}`, () => { + async function withAdapter(test: (adapter: Adapter) => Promise): Promise { + const instance = await factory.create() + instance.adapter.setId('r') + try { + await instance.adapter.start() + await test(instance.adapter) + } finally { + // A failed stop retains the database rather than dropping it. + await instance.adapter.stop() + await instance.deleteDb() + } + } + + async function claimAs(adapter: Adapter, owner: string, timeoutMs: number, checksum: string) { + adapter.setId(owner) + const jobId = await createJob(adapter, { timeoutMs, checksum }) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + const step = (await createStep(adapter, jobId, 's1'))! + return { jobId, stepId: step.id } + } + + it( + 'KR6: keeps selection, counts, checksum retention and written fields', + async () => { + await withAdapter(async (adapter) => { + const ownExpired = await claimAs(adapter, 'r', 300, OLD_CHECKSUM) + const deadExpired = await claimAs(adapter, 'dead', 300, OLD_CHECKSUM) + const ownDiscard = await claimAs(adapter, 'r', 60_000, OLD_CHECKSUM) + const ownRetain = await claimAs(adapter, 'r', 60_000, 'kept') + const deadDiscard = await claimAs(adapter, 'dead', 60_000, OLD_CHECKSUM) + adapter.setId('alive') + await adapter.heartbeat() + const alive = await claimAs(adapter, 'alive', 60_000, OLD_CHECKSUM) + const aliveExpired = await claimAs(adapter, 'alive', 300, OLD_CHECKSUM) + const completed = await claimAs(adapter, 'r', 60_000, OLD_CHECKSUM) + expect(await adapter.completeJob({ jobId: completed.jobId, output: { ok: 1 } })).toBe( + true, + ) + const created = await createJob(adapter) + adapter.setId('r') + await Bun.sleep(400) + + const recovered = await adapter.recoverJobs({ checksums: ['kept'] }) + + const job = (id: string) => adapter.getJobById(id) + const stepStatuses = async (jobId: string) => + (await adapter.getJobSteps({ jobId })).steps.map((step) => [step.id, step.status]) + const seeded = { + ownExpired, + deadExpired, + ownDiscard, + ownRetain, + deadDiscard, + alive, + aliveExpired, + completed, + } + const snapshot: Record = { recovered } + for (const [label, seed] of Object.entries(seeded)) { + const value = await job(seed.jobId) + snapshot[label] = { + id: seed.jobId, + status: value?.status, + clientId: value?.clientId, + error: value?.error, + steps: await stepStatuses(seed.jobId), + } + } + snapshot['created'] = { id: created, status: (await job(created))?.status } + record(`KR6 ${factory.name}`, snapshot) + expect(recovered).toBe(5) + for (const archived of [ownExpired, deadExpired]) { + const value = await job(archived.jobId) + expect(value).toMatchObject({ + status: 'failed', + error: { message: 'Job expired after exceeding timeout' }, + clientId: archived === ownExpired ? 'r' : 'dead', + }) + expect(value?.finishedAt).not.toBeNull() + expect(value?.finishedAt?.getTime()).toBe(value?.updatedAt?.getTime()) + expect(await stepStatuses(archived.jobId)).toEqual([[archived.stepId, 'active']]) + } + for (const requeued of [ownDiscard, ownRetain, deadDiscard]) { + expect(await job(requeued.jobId)).toMatchObject({ + status: 'created', + clientId: requeued === deadDiscard ? 'dead' : 'r', + startedAt: null, + expiresAt: null, + finishedAt: null, + output: null, + error: null, + }) + } + expect(await stepStatuses(ownDiscard.jobId)).toEqual([]) + expect(await stepStatuses(deadDiscard.jobId)).toEqual([]) + expect(await stepStatuses(ownRetain.jobId)).toEqual([[ownRetain.stepId, 'active']]) + for (const untouched of [alive, aliveExpired]) { + expect(await job(untouched.jobId)).toMatchObject({ + status: 'active', + clientId: 'alive', + }) + expect(await stepStatuses(untouched.jobId)).toEqual([[untouched.stepId, 'active']]) + } + expect(await job(completed.jobId)).toMatchObject({ status: 'completed', clientId: 'r' }) + expect(await job(created)).toMatchObject({ status: 'created' }) + expect(await adapter.recoverJobs({ checksums: ['kept'] })).toBe(0) + }) + }, + TEST_MS, + ) + + it( + 'KR11: binds each phase ID set as one uuid[] parameter (none, one and many IDs)', + async () => { + await withAdapter(async (adapter) => { + // None: each phase issues only its lock statement. + const none = await recordTransactions(adapter, () => + adapter.recoverJobs({ checksums: [NEW_CHECKSUM] }), + ) + expect(none.result).toBe(0) + expect(none.statements.map((statement) => statement.transaction)).toEqual([1, 2]) + for (const statement of none.statements) { + expect(statement.sql).toContain('FOR UPDATE OF j SKIP LOCKED') + expect(statement.sql).not.toContain('ANY(') + } + + // One requeued job. + const one = await claimAs(adapter, 'r', 60_000, OLD_CHECKSUM) + const single = await recordTransactions(adapter, () => + adapter.recoverJobs({ checksums: [NEW_CHECKSUM] }), + ) + expect(single.result).toBe(1) + expect(single.statements.map((statement) => statement.transaction)).toEqual([1, 2, 2]) + expect(single.statements[2]!.sql).toContain('::uuid[]') + expect(arrays(single.statements[2]!)).toEqual([[one.jobId]]) + expect(await adapter.getJobSteps({ jobId: one.jobId })).toMatchObject({ steps: [] }) + + // Many: expired archival and requeue each bind all their IDs in one parameter. + const expiring: string[] = [] + const running: string[] = [] + for (let index = 0; index < 3; index++) { + expiring.push(await createJob(adapter, { timeoutMs: 300 })) + } + for (let index = 0; index < 30; index++) running.push(await createJob(adapter)) + // The earlier requeued job is claimable again too. + expect(await adapter.fetch({ batch: 100 })).toHaveLength(34) + await Bun.sleep(400) + const many = await recordTransactions(adapter, () => + adapter.recoverJobs({ checksums: [NEW_CHECKSUM] }), + ) + expect(many.result).toBe(34) + const [, archival, , requeue] = many.statements + const [archivalIds] = arrays(archival!) as string[][] + const [requeueIds] = arrays(requeue!) as string[][] + record(`KR11 ${factory.name}`, { + transactions: many.statements.map((statement) => statement.transaction), + archivalParams: archival!.params.length, + requeueParams: requeue!.params.length, + archivalIds: archivalIds?.length, + requeueIds: requeueIds?.length, + }) + expect(many.statements.map((statement) => statement.transaction)).toEqual([1, 1, 2, 2]) + expect(arrays(archival!)).toHaveLength(1) + expect(arrays(requeue!)).toHaveLength(1) + expect(archivalIds!.toSorted()).toEqual(expiring.toSorted()) + expect(requeueIds!.toSorted()).toEqual([...running, one.jobId].toSorted()) + expect(requeue!.params.length).toBeLessThan(30) + for (const id of expiring) { + expect((await adapter.getJobById(id))?.status).toBe('failed') + } + }) + }, + TEST_MS, + ) + }) +} From 9b5015dd0be9f9bd7a90b63e27941039877009de Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 28 Nov 2026 23:30:19 -0300 Subject: [PATCH 018/100] docs: describe recovery's per-phase step membership guarantee Replace the unfixed recovery residual note with the implemented lock-then-modify guarantee and its limits (effective READ COMMITTED, built-in writers only, membership not version fidelity, no fencing, BEGIN-time reference per phase, rollback on stop between statements). --- packages/docs/content/docs/adapters.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 683de2b..9f82137 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -282,7 +282,7 @@ See the [Adapter API Reference](/docs/adapters) for all required methods. `Adapter.fetch()` dispatches to your `_fetch` override, and so does `Client.fetch()` when the Client has actions configured. A custom `_fetch` is responsible for its own cross-worker capacity safety; it only receives the built-in `SERIALIZABLE` claim protection when it delegates to the built-in PostgreSQL/PGLite `_fetch` (see [Multi-Worker Setup](/docs/multi-worker#claim-admission-and-group-capacity)). -Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). +Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). ## Best Practices diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index ac81b7a..d0c1623 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -254,7 +254,7 @@ Limits: - They describe the stored result as of the cancellation's commit, until a later time travel, prune or reset changes the job. False time travel restores the job and its steps as they were archived, and each step method keeps its existing guard, so `cancelJobStep` still accepts an active step under a restored `cancelled` job. - A call that waited checks expiry against its transaction's start time, not the time it acquired the lock. Archived `finishedAt` and `updatedAt` are the application time taken before any wait. - Lock waits have no deadline. A cancellation can wait for in-flight step creations, other terminators, recovery and claims (including claims holding candidate rows they did not select). `completeJob` and `failJob` can wait for step creations, cancellation and recovery. A step creation can wait for terminators and recovery. Step creations can keep overtaking a waiting cancellation, completion or failure, so a busy job can delay them. `client.stop()` observes such waits within its shutdown budgets but does not cut them short; an unfinished wait is reported as an incomplete drain. -- Known recovery residual (not fixed): a recovery pass works from a snapshot taken before it locks the job. A step committed in between can survive a requeue that should have deleted it, and, if its creation began before the job expired, can be lost when an expired job is archived. +- Recovery's own step handling, including steps created while recovery runs, is described in [Recovery and concurrent steps](#recovery-and-concurrent-steps). - This is storage behavior only. `client.cancelJob()` aborts a job that this Client is running in memory; otherwise it cancels in the database. A database cancellation does not stop a handler that is already running elsewhere, and a job this Client has claimed but not yet started (still being fetched or queued) also takes the database path: its handler can still start and then fail when step creation returns `null`. Either handler continues until a step write returns "not active". Local handling of claimed-but-not-started jobs is separate follow-up work. - PGLite runs one statement at a time; it shows the same sequential results, not concurrent locking behavior. @@ -270,6 +270,21 @@ Duron uses heartbeat-based liveness detection for crashed-instance recovery: - **Expired jobs** (exceeded timeout): Archived as failed with error information - **Stuck jobs** (not expired): Reset to `created` status and can be picked up by any worker +### Recovery and concurrent steps + +On PostgreSQL, each recovery phase (expired archival, then requeue) runs in its own transaction. It first locks the eligible jobs, skipping jobs another transaction holds, and then archives or requeues only those jobs in a second statement. That statement sees every step committed before the job was locked: + +- A requeue that discards steps (job checksum not retained) deletes them all, so the next run cannot recover a step from the discarded execution. +- Expired archival archives every such step before the job's active rows are deleted. A step ID that a step creation returned is in active or archive storage. +- A step creation that holds the job when recovery locks it makes recovery skip that job until a later pass. A step creation that arrives after the lock waits and then returns `null`. + +Limits: + +- The guarantees hold only under effective `READ COMMITTED` isolation (the PostgreSQL default) and only for the built-in writers. Duron does not set the isolation level. Other isolation levels have not been verified. Custom `_recoverJobs` overrides, workers on older Duron versions and direct SQL do not take part. +- This covers which steps are archived or deleted, not their versions. A step status write can still commit while recovery copies its steps, and the copy can then have the earlier version. It is not ownership or execution fencing. +- Each phase uses its own transaction start time for expiry checks and written timestamps. A job that expires after archival starts and before requeue starts is handled by a later pass. A failure or shutdown between the two statements rolls that phase back and rejects `recoverJobs`. A phase that already committed stays committed. +- Recovery holds its job locks until the phase commits, with no deadline. It needs a few more database round trips than a single statement. + After a successful drain, shutdown deletes the instance's liveness row before closing its database resources. Other instances can then discover eligible jobs on their next recovery pass without waiting for heartbeat staleness. If admitted work does not drain, Duron withholds that deletion and reports incomplete shutdown. A failed deletion is not reported as a successful release; existing staleness recovery still applies to a retained row. ### Heartbeat clock and failure limits From f94723f9ee5fe4794723be8d6264f09dea534836 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sat, 28 Nov 2026 23:47:31 -0300 Subject: [PATCH 019/100] test(postgres): keep recovery snapshot test output quiet Print the [KR] evidence rows only with KR_EVIDENCE=1, silence driver notices on the test's own sessions, and release barrier advisory keys only while held. No assertion or behaviour change. --- packages/duron/test/recover-snapshot.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/duron/test/recover-snapshot.test.ts b/packages/duron/test/recover-snapshot.test.ts index 3609e4f..c3dfd5e 100644 --- a/packages/duron/test/recover-snapshot.test.ts +++ b/packages/duron/test/recover-snapshot.test.ts @@ -70,8 +70,9 @@ async function within(promise: Promise, label: string): Promise { } } -// Evidence: every case prints the rows it asserts. +// Evidence: with KR_EVIDENCE=1, every case prints the rows it asserts. function record(label: string, value: unknown): void { + if (process.env['KR_EVIDENCE'] !== '1') return // oxlint-disable-next-line no-console console.log(`[KR] ${label} ${JSON.stringify(value)}`) } @@ -214,6 +215,7 @@ async function recoveryDatabase() { const session = (applicationName: string) => postgres(CONNECTION_URL, { max: 1, + onnotice: () => undefined, connection: { application_name: applicationName, statement_timeout: 5_000 }, }) const admin = session('kr-admin') @@ -222,6 +224,7 @@ async function recoveryDatabase() { const adapters: PostgresAdapter[] = [] const inFlight: Promise[] = [] let lockHolder: { release: () => void; done: Promise } | null = null + const heldKeys = new Set() const lockWaitBlockers = async (applicationName: string): Promise => { const rows = await admin` @@ -375,8 +378,11 @@ async function recoveryDatabase() { }, async hold(key: number): Promise { await barrier`SELECT pg_advisory_lock(${key})` + heldKeys.add(key) }, + // Idempotent: releases a key only while the barrier session holds it. async release(key: number): Promise { + if (!heldKeys.delete(key)) return await barrier`SELECT pg_advisory_unlock(${key})` }, // Drop only after fresh evidence of zero other sessions; otherwise retain and fail. @@ -384,6 +390,7 @@ async function recoveryDatabase() { try { lockHolder?.release() await lockHolder?.done + heldKeys.clear() await barrier`SELECT pg_advisory_unlock_all()`.catch(() => undefined) const drained = await Promise.race([ Promise.all(inFlight).then(() => true), From dbe0f78ad3245f8da9b5e291df3fc341d606fca3 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 01:00:32 -0300 Subject: [PATCH 020/100] fix(duron): coordinate worker discovery and monotonic recovery One Client-local discovery coordinator serves the startup pass, periodic safety (pullInterval, all enabled modes), availability hints and manual fetch calls: one chain at a time, one coalesced automatic request, FIFO among eligible requests. - Automatic claims stay within a Client-wide ceiling of B outstanding local claims (claimed, queued, running, finalizing incl. a lingering timed-out handler, unknown-action failure writes, reservations). Manual batches keep their own size/results and may exceed B. - Due periodic recovery pauses all new claims until local work settles; its interval uses floor(performance.now()), anchored at startup recovery success and each attempt's settlement, strict >. - Any chain failure logs once (background) or rejects (manual) and applies one pullInterval cooldown to every trigger; automatic demand is retried as a fresh claim, never replayed. - Stop rejects queued calls, clears demand, issues no new claim after the gate and starts no handler for late results. - Automatic discovery calls Adapter fetch/recoverJobs directly instead of the public Client.fetch. Docs: multi-worker and client-api describe the batchSize ceiling vs actionConcurrencyLimit vs SQL group admission vs direct Adapter calls. Ticket: postgres-implementation 10-worker-reconciliation --- packages/docs/content/docs/client-api.mdx | 34 +- packages/docs/content/docs/multi-worker.mdx | 27 +- packages/duron/src/action-job.ts | 33 +- packages/duron/src/action-manager.ts | 53 +- packages/duron/src/client.ts | 161 +- packages/duron/src/worker-discovery.ts | 278 ++++ packages/duron/test/lifecycle.test.ts | 5 +- packages/duron/test/wait-cadence.test.ts | 18 +- packages/duron/test/worker-discovery.test.ts | 1408 ++++++++++++++++++ packages/duron/test/worker-recovery.test.ts | 304 ++++ 10 files changed, 2187 insertions(+), 134 deletions(-) create mode 100644 packages/duron/src/worker-discovery.ts create mode 100644 packages/duron/test/worker-discovery.test.ts create mode 100644 packages/duron/test/worker-recovery.test.ts diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 43639f8..ccedb9d 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -77,10 +77,12 @@ const client = duron({ **Optional.** Synchronization pattern for fetching jobs. Defaults to `'hybrid'`. -- `'pull'` - Periodically poll the database -- `'push'` - Listen for database notifications -- `'hybrid'` - Use both pull and push (recommended) -- `false` - Disable automatic fetching (manual only) +- `'pull'` - Periodic discovery at `pullInterval` +- `'push'` - Database availability notifications as a fast path, plus the same periodic discovery +- `'hybrid'` - Same as `'push'` (recommended) +- `false` - Disable automatic fetching. Explicit `fetch()` still works, and `recoverJobsOnStart` still applies + +In every enabled mode, a Client with actions starts one background discovery pass as soon as it is running (`start()` does not wait for it) and then checks for work every `pullInterval`, so jobs whose notification was lost, jobs requeued by recovery and jobs that became claimable when a group slot freed up are still found. Without `actions`, a Client never claims or recovers jobs; `fetch()` returns `[]`. `actions: {}` keeps worker behavior, so a claimed job of an unknown action is failed. ```ts { @@ -104,9 +106,14 @@ const client = new Client({ database, waitReadTimeout: 3000 }) ### `pullInterval` -**Optional.** Interval in milliseconds between worker pull operations, and the cadence and error cooldown for pending-wait reconciliation in every sync mode. Defaults to `5000`. Wait reconciliation also runs without actions and with `syncPattern: false`; it never fetches or executes jobs. +**Optional.** Defaults to `5000`. Used for two independent schedules: + +- **Worker discovery** (Clients with actions and an enabled `syncPattern`): the interval between periodic discovery checks, and the cooldown after a failed discovery or recovery attempt. +- **Pending-wait reconciliation** (every sync mode, with or without actions): its cadence and error cooldown. It never fetches or executes jobs. -For wait scheduling only, a positive finite interval is floored and clamped to `1–2,147,483,647`; other accepted values use `5000`. Existing worker option validation and cadence are unchanged. +For both schedules, a positive finite interval is floored and clamped to `1–2,147,483,647`; other accepted values use `5000`. `getConfig()` still returns the value you passed. + +Periodic discovery is not reset or postponed by notifications or `fetch()` calls. Missed ticks are not replayed: while a discovery is running, further demand is merged into one pending request. After any discovery failure (for example, a `40001` serialization failure from a concurrent claim), every trigger waits one interval before the next claim, including notifications and queued `fetch()` calls. The failed claim is not replayed; the next claim is a new one. ```ts { @@ -116,7 +123,12 @@ For wait scheduling only, a positive finite interval is floored and clamped to ` ### `batchSize` -**Optional.** Maximum number of jobs to fetch in a single batch. Defaults to `10`. +**Optional.** Defaults to `10`. Two meanings: + +- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Automatic requests from notifications claim one job; startup and periodic requests claim up to the remaining room. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. +- **Default `fetch()` batch.** `fetch()` without `batchSize` passes this value unchanged. + +B is not the number of handlers that run at once. That is `actionConcurrencyLimit` per action, so with the defaults (B = 10, `actionConcurrencyLimit` = 100) at most ten automatically claimed jobs are outstanding. SQL group admission (`groupConcurrencyLimit` or `groups.concurrency`) is a separate limit across all workers. Jobs claimed by `fetch()` count toward B, and a `fetch()` batch can exceed B; automatic claiming then pauses until enough work settles. B limits claim admission only. It does not bound the rows that recovery examines, the backlog that manual calls create, or the total query rate. ```ts { @@ -168,6 +180,10 @@ For wait scheduling only, a positive finite interval is floored and clamped to ` **Optional.** Interval in milliseconds between periodic job recovery runs. Defaults to `60000` (1 minute). Set to `0` to disable periodic recovery (only runs on startup). +Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Without startup recovery, the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies. + +Before recovery runs, the Client stops making new claims, including `fetch()` calls, and waits until all of its locally claimed jobs have settled, so recovery does not requeue jobs this Client is still running. A slow or stuck handler therefore also delays recovery and `fetch()`. One recovery call can affect any number of jobs and has no time limit. + Recovery checks for: - **Expired jobs**: Jobs that exceeded their timeout are archived as failed @@ -244,7 +260,7 @@ await client.start() ### `stop()` -Stop the Duron instance. Stops the pull loop, aborts all running jobs, waits for queues to drain, and stops the database. +Stop the Duron instance. Stops worker discovery, aborts all running jobs, waits for queues to drain, and stops the database. ```ts await client.stop() @@ -275,6 +291,8 @@ const jobId = await client.runAction('sendEmail', { Manually fetch and process jobs from the database. +Each call keeps its own batch and returns the jobs it actually claimed, after its claim (not after the handlers finish). Calls are served one at a time together with automatic discovery, in arrival order, so a call can wait behind a running discovery, a due recovery (see `recoverJobsInterval`) or a failure cooldown. A failed call rejects with the original error and is not retried. Calls still waiting when `stop()` begins reject; a call whose claim was already issued returns its jobs, but no handler starts after `stop()`. Direct `client.database.fetch()` calls are outside this coordination. + ```ts const jobs = await client.fetch({ batchSize: 20, diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index d0c1623..cf0e9e9 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -224,7 +224,7 @@ process.on('SIGINT', async () => { The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` transaction per fetch. The claim query itself is unchanged: the latest unexpired job for each action name and group key supplies the concurrency limit, candidates are row-locked with `SKIP LOCKED`, and the oldest eligible jobs are claimed first. Claimed jobs are returned, and their handlers can start, only after the transaction commits. -When concurrent claims from different workers would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. Duron does not retry inside the fetch and does not turn the error into an empty result: a manual `client.fetch()` or `adapter.fetch()` call rejects with the original error, while automatic pull and push fetches log it and fetch again on their next pull or notification. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so occasional conflicts between unrelated groups are possible. Handle the rejection of a `fetch()` you start without awaiting. +When concurrent claims from different workers would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. Duron does not retry inside the fetch and does not turn the error into an empty result: a manual `client.fetch()` or `adapter.fetch()` call rejects with the original error. Automatic discovery logs the failure once, waits one `pullInterval`, and then makes a new claim; notifications and queued `client.fetch()` calls also wait for that cooldown. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so occasional conflicts between unrelated groups are possible. Handle the rejection of a `fetch()` you start without awaiting. Limits of this protection: @@ -235,6 +235,18 @@ Limits of this protection: - Known driver limitation, observed with postgres.js 3.4.9: if the database connection closes while any built-in transaction is open, including a claim, the driver can throw an uncaught exception from its own rollback attempt and keep that pooled connection unusable until the adapter closes. Under Node.js's default handling, an uncaught exception terminates the process. The uncommitted claim is not returned. - PGLite is a single-engine test backend; it runs claims one at a time and is not evidence of multi-process isolation. +## Worker Discovery + +Each Client with actions coordinates its own job discovery: + +- **One discovery at a time.** The startup pass, periodic checks, notifications and `client.fetch()` calls share one queue and are served one at a time in arrival order. Notifications and periodic checks that arrive while a discovery is running are merged into one pending request. +- **Safety in every mode.** With `syncPattern` `'push'`, `'hybrid'` or `'pull'`, the Client discovers work immediately after startup and then every `pullInterval`. Notifications only make discovery faster. Work whose notification was lost, work requeued by recovery, and work that becomes claimable after a group slot frees up or a job expires is found by the next periodic check. +- **Automatic claim ceiling.** Automatic claims stop while this Client has `batchSize` claimed jobs outstanding (claimed, queued, running or finishing). See [`batchSize`](/docs/client-api#batchsize) for how this differs from `actionConcurrencyLimit` and SQL group limits. +- **Recovery barrier.** When periodic recovery is due, the Client stops claiming and waits for its own claimed jobs to settle before it runs recovery. This keeps recovery from requeuing jobs that this Client is still running. It is not a database lock and does not coordinate with other workers. +- **Failures.** After a failed discovery or recovery attempt, all discovery waits one `pullInterval`. Failed claims are never replayed. + +This coordination is local to one Client. Other Clients, and direct calls such as `client.database.fetch()` or `client.database.recoverJobs()`, are not coordinated with it. Cross-worker group limits rely on the claim admission described above, not on this local coordination. + ## Cancellation and Stored Steps Cancelling a job in the database archives the job as `cancelled` and archives every one of its steps as `cancelled`, including steps that had already completed or failed. On PostgreSQL, a cancellation that commits keeps every step committed before it took the job, and no step for that job can be created while it runs. A step creation that arrives while the cancellation holds the job waits for it and then returns `null` (the existing "job is not active" result) instead of failing with a foreign-key error. A step creation that took the job first makes the cancellation wait, and its step is archived as `cancelled`. A step status write that reaches its step first succeeds and is then overwritten to `cancelled`; one that arrives later waits and returns `false`. @@ -263,7 +275,7 @@ Limits: Duron uses heartbeat-based liveness detection for crashed-instance recovery: 1. **Heartbeat**: Each instance periodically upserts a liveness record in the `clients` table (every `heartbeatInterval`). PostgreSQL and PGLite use SQL `now()` for both the first write and subsequent updates. -2. **Fetch-driven recovery**: A worker with configured actions checks recovery from `fetch()` after `recoverJobsInterval` elapses (default: 60 seconds). This interval does not create an independent recovery timer. Without a fetch, elapsed time alone does not trigger recovery. Setting `recoverJobsInterval` to `0` disables this fetch-triggered check. +2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery waits until this Client's own claimed jobs have settled (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. 3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. 4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery includes the current client ID regardless of its heartbeat and does not newly include null owners. 5. **Recovery behavior**: @@ -303,11 +315,11 @@ A rejected notification reply does not prove nondelivery: listeners may already The whole `${schema}.${event}` string is one exact channel, including dots, case and quotes. Built-in payloads remain `{jobId}` for availability and `{jobId,status,clientId}` for terminal status. Emission uses bound `pg_notify` arguments; native channel/text/payload limits still apply, with no truncation, renaming or chunking. PostgreSQL channels are limited to 63 bytes and payloads to fewer than 8,000 bytes in the tested default configurations. This transport handling does not establish full custom-schema migration support. -There is no ordinary notification deadline or background delivery queue. A stuck attempt can delay its caller even after the mutation commits. Shutdown observes it under the shared lifecycle budgets below; a timeout is not cancellation or proof of nondelivery. Notifications alone do not provide missed-event recovery. Recovery remains fetch-driven as described above, and this transport change adds no wait/worker reconciliation or recovery events. +There is no ordinary notification deadline or background delivery queue. A stuck attempt can delay its caller even after the mutation commits. Shutdown observes it under the shared lifecycle budgets below; a timeout is not cancellation or proof of nondelivery. Notifications alone do not provide missed-event recovery. Periodic worker discovery and pending-wait reconciliation cover lost hints; recovery emits no notification and there are no recovery events. ## Lifecycle and Shutdown -`client.stop()` closes admission immediately: it cancels scheduled heartbeat/pull/prune timers, disables new event-driven work, settles pending waits with `null`, and requests action cancellation. It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler. +`client.stop()` closes admission immediately: it cancels scheduled heartbeat/discovery/prune timers, discards pending automatic discovery, rejects queued `client.fetch()` calls that have not started, disables new event-driven work, settles pending waits with `null`, and requests action cancellation. A discovery that has already started issues no new claim after the stop, and locally queued jobs do not start. It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler. Client and Adapter share four internal shutdown budgets. Each budget applies to the whole phase, not separately to nested calls or individual resources: @@ -376,9 +388,10 @@ Keep `heartbeatTimeout` at least 3x `heartbeatInterval` to tolerate occasional m If jobs aren't being processed: 1. **Check worker status**: Verify workers are running and connected to the database -2. **Check sync pattern**: Ensure workers have `syncPattern: 'hybrid'` or `'pull'` -3. **Check database connection**: Verify all processes can connect to the database -4. **Check logs**: Look for errors in worker logs +2. **Check sync pattern**: Ensure workers have `syncPattern` `'hybrid'`, `'push'` or `'pull'` (not `false`), and that `pullInterval` is not larger than the delay you can accept for work whose notification was lost +3. **Check outstanding work**: Automatic claims pause while `batchSize` claimed jobs are still outstanding, and a due recovery waits for them to settle; a stuck handler delays both +4. **Check database connection**: Verify all processes can connect to the database +5. **Check logs**: Look for errors in worker logs ### Jobs Stuck in Active Status diff --git a/packages/duron/src/action-job.ts b/packages/duron/src/action-job.ts index 8174e88..4a570d8 100644 --- a/packages/duron/src/action-job.ts +++ b/packages/duron/src/action-job.ts @@ -49,6 +49,7 @@ export class ActionJob> { #timeoutId: NodeJS.Timeout | null = null #done: Promise #resolve: (() => void) | null = null + #handler: Promise = Promise.resolve() #jobSpan!: Span // ============================================================================ @@ -151,18 +152,20 @@ export class ActionJob> { // Execute handler within the job span context so that child spans inherit the trace const spanContext = trace.setSpan(context.active(), this.#jobSpan) + // Keep the raw handler promise: an abort/timeout can settle the race first. + const handler = lifecycleFor(this.#database).run(() => + context.with(spanContext, () => { + // The tracked invocation is deferred. Stop can win after preparation. + if (!lifecycleFor(this.#database).accepting) { + throw new ActionCancelError(this.#action.name, this.#job.id) + } + this.#abortController.signal.throwIfAborted() + return this.#action.handler(ctx) + }), + ) + this.#handler = handler await Promise.race([ - lifecycleFor(this.#database) - .run(() => - context.with(spanContext, () => { - // The tracked invocation is deferred. Stop can win after preparation. - if (!lifecycleFor(this.#database).accepting) { - throw new ActionCancelError(this.#action.name, this.#job.id) - } - this.#abortController.signal.throwIfAborted() - return this.#action.handler(ctx) - }), - ) + handler .then((res) => { if (res !== undefined) { result = res @@ -254,6 +257,14 @@ export class ActionJob> { return this.#done } + /** + * Actual local settlement: execution/finalization finished and the raw handler promise + * settled, even when an abort or timeout won the race. Never rejects. + */ + settled(): Promise { + return Promise.allSettled([this.#done, this.#handler]).then(() => undefined) + } + /** * Cancel the job execution. * Clears the timeout and aborts the action handler. diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index d851737..5f8a85e 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -7,6 +7,18 @@ import type { Action } from './action.js' import type { Adapter, Job } from './adapters/adapter.js' import { lifecycleFor } from './lifecycle.js' +export interface QueuedJob { + /** Execution outcome, as before: rejects when execution throws. */ + done: Promise + /** Actual local settlement across queued, running and finalizing stages. Never rejects. */ + settled: Promise +} + +interface QueueEntry { + job: Job + settle: (settlement: Promise) => void +} + export interface ActionManagerOptions> { action: TAction database: Adapter @@ -28,7 +40,8 @@ export class ActionManager> { #tracer: Tracer #variables: Record #logger: Logger - #queue: fastq.queueAsPromised + #queue: fastq.queueAsPromised + #unstarted = new Set() #concurrencyLimit: number #activeJobs = new Map>() #stopped: boolean = false @@ -51,12 +64,23 @@ export class ActionManager> { this.#concurrencyLimit = options.concurrencyLimit // Create fastq queue with action concurrency limit - this.#queue = fastq.promise(async (job: Job) => { + this.#queue = fastq.promise(async (entry: QueueEntry) => { + this.#unstarted.delete(entry) if (this.#stopped || !lifecycleFor(this.#database).accepting) { + entry.settle(Promise.resolve()) return } - await lifecycleFor(this.#database).run(() => this.#executeJob(job)) + let actionJob: ActionJob | undefined + try { + await lifecycleFor(this.#database).run(() => + this.#executeJob(entry.job, (created) => { + actionJob = created + }), + ) + } finally { + entry.settle(actionJob?.settled() ?? Promise.resolve()) + } }, this.#concurrencyLimit) } @@ -68,10 +92,18 @@ export class ActionManager> { * Queue a job for execution. * * @param job - The job to queue - * @returns Promise that resolves when the job is queued + * @returns The execution outcome and its actual local settlement */ - async push(job: Job): Promise { - return this.#queue.push(job) + push(job: Job): QueuedJob { + let settle!: (settlement: Promise) => void + const settled = new Promise((resolve) => { + settle = (settlement) => { + void settlement.then(resolve, resolve) + } + }) + const entry: QueueEntry = { job, settle } + this.#unstarted.add(entry) + return { done: this.#queue.push(entry), settled } } /** @@ -129,7 +161,11 @@ export class ActionManager> { this.#stopped = true this.abortAll() - await this.#queue.killAndDrain() + const drained = this.#queue.killAndDrain() + // Killed queue entries never start a handler; their local accounting settles now. + for (const entry of this.#unstarted) entry.settle(Promise.resolve()) + this.#unstarted.clear() + await drained await Promise.all( Array.from(this.#activeJobs.values()).map((actionJob) => actionJob.waitForDone()), ) @@ -144,7 +180,7 @@ export class ActionManager> { * * @param job - The job to execute */ - async #executeJob(job: Job) { + async #executeJob(job: Job, created: (actionJob: ActionJob) => void) { // Create ActionJob for this job const actionJob = new ActionJob({ job: { @@ -161,6 +197,7 @@ export class ActionManager> { logger: this.#logger, }) this.#activeJobs.set(job.id, actionJob) + created(actionJob) try { // Execute the job - all error handling is done inside ActionJob.execute() diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 7959245..b4e6619 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -30,6 +30,7 @@ import { JOB_STATUS_CANCELLED, JOB_STATUS_FAILED, type JobStatus } from './const import { type Lifecycle, lifecycleFor } from './lifecycle.js' import { validateSchema } from './standard-schema.js' import { WaitManager } from './wait-manager.js' +import { WorkerDiscovery } from './worker-discovery.js' /** * Extracts the inferred type from an action's input/output schema. @@ -139,10 +140,12 @@ export interface BaseOptionsInput { /** * Synchronization pattern for fetching jobs from the database. * - * - `'pull'`: Periodically poll the database for new jobs at `pullInterval` - * - `'push'`: Listen for database notifications when jobs are available (real-time) - * - `'hybrid'`: Use both pull and push patterns (recommended for reliability) - * - `false`: Disable automatic job fetching (use `fetch()` manually) + * - `'pull'`: Periodic discovery at `pullInterval` + * - `'push'`: Availability notifications as a fast path, plus periodic discovery + * - `'hybrid'`: Same as `'push'` (recommended) + * - `false`: Disable automatic job fetching (use `fetch()` manually; startup recovery still runs) + * + * Enabled modes start one background discovery pass once the Client is running. * * @default 'hybrid' * @@ -158,9 +161,10 @@ export interface BaseOptionsInput { syncPattern?: 'pull' | 'push' | 'hybrid' | false /** - * Worker pull interval and pending-wait reconciliation cadence/error cooldown. - * Wait reconciliation runs independently of actions and syncPattern, without fetching jobs. - * For waits only: floor/clamp positive finite values to 1–2,147,483,647; otherwise use 5000. + * Worker discovery cadence and failure cooldown, and (independently) pending-wait + * reconciliation cadence/error cooldown. Wait reconciliation runs regardless of actions and + * syncPattern, without fetching jobs. For both schedules: floor/clamp positive finite values + * to 1–2,147,483,647; otherwise use 5000. * * @default 5000 */ @@ -175,8 +179,12 @@ export interface BaseOptionsInput { waitReadTimeout?: number /** - * Maximum number of jobs to fetch in a single batch from the database. - * Higher values reduce database round-trips but may increase memory usage. + * Automatic claim ceiling B and the default `fetch()` batch. + * Automatic discovery claims only while fewer than B claimed jobs are outstanding locally + * (queued, running or finalizing); hints claim one job. For the ceiling, positive finite + * values are floored/clamped to 1–Number.MAX_SAFE_INTEGER; otherwise 10. Manual `fetch()` + * batches are passed unchanged and may exceed B. Distinct from `actionConcurrencyLimit` + * and SQL group limits. * * @default 10 */ @@ -247,6 +255,9 @@ export interface BaseOptionsInput { * Interval in milliseconds between job recovery runs. * Recovery checks for expired or stuck jobs and handles them appropriately. * Set to `0` to disable periodic recovery (only runs on startup). + * Runs inside worker discovery once strictly more than this many monotonic milliseconds + * have elapsed since startup recovery success or the last attempt's settlement; new claims + * pause until this Client's local work settles first. * * @default 60000 */ @@ -358,9 +369,8 @@ export class Client< #logger: Logger #lifecycle: Lifecycle #stopping: Promise | null = null - #pullInterval: NodeJS.Timeout | null = null #heartbeatTimer: NodeJS.Timeout | null = null - #lastRecoveryAt: number = 0 + #discovery: WorkerDiscovery | null = null #actionManagers = new Map>>() #mockInputSchemas = new Map() #waits: WaitManager @@ -391,6 +401,25 @@ export class Client< this.#logger = this.#normalizeLogger(options?.logger) this.#database.setId(this.#id) this.#database.setLogger(this.#logger) + if (this.#actions) { + const actions = this.#actions + this.#discovery = new WorkerDiscovery({ + lifecycle: this.#lifecycle, + logger: this.#logger, + automatic: this.#options.syncPattern !== false, + pullInterval: this.#options.pullInterval, + batchSize: this.#options.batchSize, + recoverJobsInterval: this.#options.recoverJobsInterval, + // Automatic and manual discovery call the Adapter's public methods directly. + recover: () => + this.#database.recoverJobs({ + checksums: Object.values(actions).map((action) => action.checksum), + staleTimeoutMs: this.#options.heartbeatTimeout, + }), + claim: (batch) => this.#database.fetch({ batch }), + dispatch: (job) => this.#executeJob(job), + }) + } this.#waits = new WaitManager( this.#database, this.#lifecycle, @@ -710,6 +739,9 @@ export class Client< /** * Fetch and process jobs from the database. * Concurrency limits are determined from the latest job created for each groupKey. + * Calls are served one at a time with automatic discovery; a call may wait behind an + * admitted chain, a due recovery barrier or a failure cooldown. It returns after its claim, + * not after the claimed handlers finish. Without actions it returns [] without claiming. * * @param [options.batchSize] - Maximum number of jobs to fetch in this batch (defaults to `batchSize` from client options) * @returns Promise resolving to the array of fetched jobs @@ -718,37 +750,11 @@ export class Client< return this.#lifecycle.run(async () => { await this.start() - if (!this.#actions) { + if (!this.#discovery) { return [] } - // Run recovery periodically (time-based, always multi-process) - const now = Date.now() - if ( - this.#options.recoverJobsInterval > 0 && - now - this.#lastRecoveryAt > this.#options.recoverJobsInterval - ) { - this.#lastRecoveryAt = now - await this.#database.recoverJobs({ - checksums: Object.values(this.#actions).map((action) => action.checksum), - staleTimeoutMs: this.#options.heartbeatTimeout, - }) - } - - this.#lifecycle.assertContinuation() - - // Fetch jobs from each action's queue - // Concurrency limits are determined from the latest job created for each groupKey - const jobs = await this.#database.fetch({ - batch: options.batchSize ?? this.#options.batchSize, - }) - - // Process fetched jobs - for (const job of jobs) { - this.#executeJob(job) - } - - return jobs + return this.#discovery.fetch(options.batchSize ?? this.#options.batchSize) }) } @@ -1084,7 +1090,7 @@ export class Client< * @returns Promise resolving to `true` if started successfully, `false` otherwise */ async start(): Promise { - return this.#lifecycle.start( + const started = await this.#lifecycle.start( this, async () => { if (!(await this.#database.start()) || !this.#lifecycle.accepting) return false @@ -1096,11 +1102,10 @@ export class Client< staleTimeoutMs: this.#options.heartbeatTimeout, }) if (!this.#lifecycle.accepting) return false + this.#discovery?.anchorRecovery() } this.#scheduleHeartbeat() if (this.#actions) { - if (this.#options.syncPattern === 'pull' || this.#options.syncPattern === 'hybrid') - this.#startPullLoop() if (this.#options.syncPattern === 'push' || this.#options.syncPattern === 'hybrid') this.#setupPushListener() } @@ -1108,6 +1113,9 @@ export class Client< }, () => this.stop(), ) + // Worker discovery is admitted only once the Client is running. + if (started && this.#lifecycle.accepting) this.#discovery?.start() + return started } /** Quiesce synchronously, then preserve public Adapter.stop override dispatch. */ @@ -1127,10 +1135,7 @@ export class Client< clearTimeout(this.#heartbeatTimer) this.#heartbeatTimer = null } - if (this.#pullInterval) { - clearTimeout(this.#pullInterval) - this.#pullInterval = null - } + this.#discovery?.stop() if (this.#jobStatusListener) { this.#database.off('job-status-changed', this.#jobStatusListener) this.#jobStatusListener = null @@ -1173,10 +1178,11 @@ export class Client< * Execute a job by finding its action and queuing it with the appropriate ActionManager. * * @param job - The job to execute + * @returns Actual local settlement (queued, running and finalizing work). Never rejects. */ - #executeJob(job: Job) { + #executeJob(job: Job): Promise { if (!this.#actions || !this.#lifecycle.accepting) { - return + return Promise.resolve() } const action = Object.values(this.#actions).find((a) => a.name === job.actionName) @@ -1189,10 +1195,17 @@ export class Client< { jobId: job.id, actionName: job.actionName }, `[Duron] Action not found for job ${job.id}`, ) - this.#database.failJob({ jobId: job.id, error }).catch((dbError) => { - this.#logger.error({ error: dbError, jobId: job.id }, `[Duron] Error failing job ${job.id}`) - }) - return + return this.#lifecycle + .run(() => this.#database.failJob({ jobId: job.id, error })) + .then( + () => undefined, + (dbError: unknown) => { + this.#logger.error( + { error: dbError, jobId: job.id }, + `[Duron] Error failing job ${job.id}`, + ) + }, + ) } // Get or create ActionManager for this action @@ -1210,13 +1223,15 @@ export class Client< } // Queue job execution - actionManager.push(job).catch((err) => { + const queued = actionManager.push(job) + queued.done.catch((err) => { // Only log unexpected errors (not cancellation/timeout which are handled elsewhere) this.#logger.error( { err, jobId: job.id, actionName: action.name }, `[Duron] Error executing job ${job.id} for action ${action.name}`, ) }) + return queued.settled } /** @@ -1245,40 +1260,9 @@ export class Client< }, this.#options.heartbeatInterval) } - /** - * Start the pull loop for periodically fetching jobs. - * Only starts if not already running. - */ - #startPullLoop() { - if (this.#pullInterval) { - return - } - - const pull = () => { - if (!this.#lifecycle.accepting) return - void this.#lifecycle - .run(async () => { - try { - await this.fetch({ batchSize: this.#options.batchSize }) - } catch (error) { - this.#logger.error({ error }, '[Duron] [PullLoop] Error in pull loop') - } - if (this.#lifecycle.accepting) { - this.#pullInterval = setTimeout(pull, this.#options.pullInterval) - } - }) - .catch((error: unknown) => { - this.#logger.error({ error }, '[Duron] Pull callback failed') - }) - } - - // Start immediately - pull() - } - /** * Setup the push listener for database notifications. - * Listens for 'job-available' events and fetches jobs when notified. + * Each 'job-available' hint merges one-job demand into worker discovery. */ #setupPushListener() { if (this.#pushListenerSetup || !this.#lifecycle.accepting) { @@ -1288,12 +1272,7 @@ export class Client< this.#pushListenerSetup = true this.#pushListener = () => { - if (!this.#lifecycle.accepting) return - void this.#lifecycle - .run(() => this.fetch({ batchSize: 1 })) - .catch((error: unknown) => { - this.#logger.error({ error }, '[Duron] [PushListener] Error fetching job') - }) + this.#discovery?.request('hint') } this.#database.on('job-available', this.#pushListener) diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts new file mode 100644 index 0000000..a9fe89c --- /dev/null +++ b/packages/duron/src/worker-discovery.ts @@ -0,0 +1,278 @@ +import type { Logger } from 'pino' + +import type { Job } from './adapters/adapter.js' +import type { Lifecycle } from './lifecycle.js' + +export type DiscoveryTrigger = 'startup' | 'periodic' | 'hint' + +interface AutomaticRequest { + kind: 'automatic' + batch: number + triggers: Set +} + +interface ManualRequest { + kind: 'manual' + batch: number + resolve: (jobs: Job[]) => void + reject: (error: unknown) => void +} + +type DiscoveryRequest = AutomaticRequest | ManualRequest + +export interface WorkerDiscoveryOptions { + lifecycle: Lifecycle + logger: Logger + /** False for syncPattern:false; explicit fetch remains available. */ + automatic: boolean + pullInterval: number + batchSize: number + recoverJobsInterval: number + recover: () => Promise + claim: (batch: number) => Promise + /** Queue a claimed job locally; resolves (never rejects) at its actual local settlement. */ + dispatch: (job: Job) => Promise +} + +/** Worker cadence: floor/clamp positive finite values to 1–2,147,483,647 ms; otherwise 5000. */ +export function workerInterval(value: number): number { + return Number.isFinite(value) && value > 0 + ? Math.min(2_147_483_647, Math.max(1, Math.floor(value))) + : 5_000 +} + +/** Automatic batch B: floor/clamp positive finite values to 1–MAX_SAFE_INTEGER; otherwise 10. */ +export function automaticBatch(value: number): number { + return Number.isFinite(value) && value > 0 + ? Math.min(Number.MAX_SAFE_INTEGER, Math.max(1, Math.floor(value))) + : 10 +} + +// Process-local whole-millisecond monotonic sample. Never persisted or compared with job dates. +function monotonicMs(): number { + return Math.floor(performance.now()) +} + +const notAccepting = () => new Error('Lifecycle is not accepting work') + +/** + * Client-local worker discovery coordinator (internal; not a public API). + * + * - One actual discovery chain at a time across startup, periodic safety, hints and manual + * fetch calls. A chain is: optional due recovery, then at most one Adapter.fetch claim. + * - At most one coalesced automatic request. Requests are served FIFO among eligible ones; + * cooldown, automatic claim room and the recovery barrier decide eligibility. + * - Automatic claims use only the room left under a Client-wide ceiling of B outstanding + * local claims (claimed, queued, running and finalizing work, plus reservations). Manual + * calls keep their own batch and returned jobs and may exceed B. + * - Due recovery pauses every new claim until local work actually settles. Its interval is + * measured monotonically from startup recovery success or any attempt's settlement. + * - Any chain failure applies one effective pullInterval cooldown to all triggers. + * - Direct Adapter calls (including via client.database) are outside this coordinator. + */ +export class WorkerDiscovery { + readonly #options: WorkerDiscoveryOptions + readonly #interval: number + readonly #batch: number + #queue: DiscoveryRequest[] = [] + #automatic: AutomaticRequest | null = null + #chain = false + #started = false + #stopped = false + #cooldownUntil = -Infinity + #recoveredAt = -Infinity + #reserved = 0 + #local = new Set>() + #tick: ReturnType | null = null + #wake: ReturnType | null = null + + constructor(options: WorkerDiscoveryOptions) { + this.#options = options + this.#interval = workerInterval(options.pullInterval) + this.#batch = automaticBatch(options.batchSize) + } + + /** Successful startup recovery anchors the next periodic recovery interval. */ + anchorRecovery(): void { + this.#recoveredAt = monotonicMs() + } + + /** Admit discovery after the Client is running: one immediate pass, then periodic safety. */ + start(): void { + if (this.#started || this.#stopped || !this.#options.lifecycle.accepting) return + this.#started = true + if (this.#options.automatic) { + this.#scheduleTick() + this.request('startup') + } + this.#pump() + } + + /** Merge automatic demand. Hints request one job; startup/periodic request B. */ + request(trigger: DiscoveryTrigger): void { + if (!this.#options.automatic || this.#stopped || !this.#options.lifecycle.accepting) return + this.#mergeAutomatic(trigger === 'hint' ? 1 : this.#batch, [trigger]) + this.#pump() + } + + /** A distinct manual call: its own batch and actual claimed jobs, never merged. */ + fetch(batch: number): Promise { + if (this.#stopped || !this.#options.lifecycle.accepting) return Promise.reject(notAccepting()) + return new Promise((resolve, reject) => { + this.#queue.push({ kind: 'manual', batch, resolve, reject }) + this.#pump() + }) + } + + /** Close admission immediately; admitted chains and local work keep their own tracking. */ + stop(): void { + if (this.#stopped) return + this.#stopped = true + if (this.#tick) clearTimeout(this.#tick) + if (this.#wake) clearTimeout(this.#wake) + this.#tick = null + this.#wake = null + const queued = this.#queue + this.#queue = [] + this.#automatic = null + for (const request of queued) { + if (request.kind === 'manual') request.reject(notAccepting()) + } + } + + get #open(): boolean { + return this.#started && !this.#stopped && this.#options.lifecycle.accepting + } + + get #room(): number { + return this.#batch - this.#local.size - this.#reserved + } + + #mergeAutomatic(batch: number, triggers: Iterable): void { + if (this.#automatic) { + this.#automatic.batch = Math.max(this.#automatic.batch, batch) + for (const trigger of triggers) this.#automatic.triggers.add(trigger) + return + } + this.#automatic = { kind: 'automatic', batch, triggers: new Set(triggers) } + this.#queue.push(this.#automatic) + } + + #scheduleTick(): void { + // Independent of hints/manual calls and of chain settlement; no catch-up of missed ticks. + this.#tick = setTimeout(() => { + this.#tick = null + if (this.#stopped || !this.#options.lifecycle.accepting) return + this.#scheduleTick() + this.request('periodic') + }, this.#interval) + } + + #recoveryDue(now: number): boolean { + const interval = this.#options.recoverJobsInterval + return interval > 0 && now - this.#recoveredAt > interval + } + + #pump(): void { + if (this.#chain || !this.#open || this.#queue.length === 0) return + const now = monotonicMs() + if (now < this.#cooldownUntil) { + this.#wake ??= setTimeout(() => { + this.#wake = null + this.#pump() + }, this.#cooldownUntil - now) + return + } + if (this.#recoveryDue(now)) { + // Quiescent barrier: no new claim (manual included) until local work actually settles. + if (this.#local.size === 0) this.#serve(this.#queue[0]!, true) + return + } + const request = this.#queue.find((item) => item.kind === 'manual' || this.#room > 0) + if (request) this.#serve(request, false) + } + + #serve(request: DiscoveryRequest, recover: boolean): void { + this.#queue.splice(this.#queue.indexOf(request), 1) + if (request === this.#automatic) this.#automatic = null + this.#chain = true + let chain: Promise + try { + chain = this.#options.lifecycle.run(() => this.#chainWork(request, recover)) + } catch (error) { + chain = Promise.reject(error) + } + void chain + .catch((error: unknown) => { + // Admission itself was refused; nothing was issued. + if (request.kind === 'manual') request.reject(error) + }) + .finally(() => { + this.#chain = false + this.#pump() + }) + } + + async #chainWork(request: DiscoveryRequest, recover: boolean): Promise { + let stage: 'recovery' | 'claim' = 'recovery' + let reserved = 0 + try { + if (recover) { + try { + await this.#options.recover() + } finally { + this.#recoveredAt = monotonicMs() + } + } + stage = 'claim' + // No new claim after the stop gate; an admitted manual call rejects. + if (this.#stopped || !this.#options.lifecycle.accepting) { + if (request.kind === 'manual') request.reject(notAccepting()) + return + } + let batch = request.batch + if (request.kind === 'automatic') { + batch = Math.min(batch, this.#room) + if (batch <= 0) { + this.#mergeAutomatic(request.batch, request.triggers) + return + } + reserved = batch + this.#reserved += reserved + } + this.#options.lifecycle.assertContinuation() + const jobs = await this.#options.claim(batch) + // Transfer the reservation into local accounting without a gap or double count. + this.#reserved -= reserved + reserved = 0 + if (!this.#stopped && this.#options.lifecycle.accepting) { + for (const job of jobs) this.#track(this.#options.dispatch(job)) + } + if (request.kind === 'manual') request.resolve(jobs) + } catch (error) { + this.#cooldownUntil = monotonicMs() + this.#interval + if (request.kind === 'manual') { + request.reject(error) + } else { + this.#options.logger.error( + { error, stage, triggers: [...request.triggers] }, + `[Duron] [WorkerDiscovery] Background ${stage} failed`, + ) + // A fresh claim after cooldown, never a replay of the uncertain one. + if (this.#options.automatic && !this.#stopped && this.#options.lifecycle.accepting) { + this.#mergeAutomatic(request.batch, request.triggers) + } + } + } finally { + this.#reserved -= reserved + } + } + + #track(settlement: Promise): void { + this.#local.add(settlement) + void settlement.finally(() => { + this.#local.delete(settlement) + this.#pump() + }) + } +} diff --git a/packages/duron/test/lifecycle.test.ts b/packages/duron/test/lifecycle.test.ts index 0649bbb..62104a4 100644 --- a/packages/duron/test/lifecycle.test.ts +++ b/packages/duron/test/lifecycle.test.ts @@ -125,7 +125,8 @@ for (const factory of [ }, 30_000) for (const syncPattern of ['pull', 'push'] as const) { - it(`drains the whole ${syncPattern} callback through public fetch dispatch`, async () => { + // Automatic discovery calls the Adapter's public fetch directly (not Client.fetch). + it(`drains the whole ${syncPattern} discovery chain through public Adapter fetch dispatch`, async () => { const instance = await factory.create() const adapter = instance.adapter as LifecycleProbe const entered = Promise.withResolvers() @@ -141,7 +142,7 @@ for (const factory of [ logger: 'silent', }) let calls = 0 - client.fetch = async () => { + adapter.fetch = async () => { calls++ entered.resolve() await release.promise diff --git a/packages/duron/test/wait-cadence.test.ts b/packages/duron/test/wait-cadence.test.ts index 72dffd6..349893a 100644 --- a/packages/duron/test/wait-cadence.test.ts +++ b/packages/duron/test/wait-cadence.test.ts @@ -206,7 +206,7 @@ for (const factory of [ ) it.serial( - 'keeps the worker delay fractional while normalizing only the wait timer', + 'normalizes the worker and wait timers independently without rewriting config', async () => { const instance = await factory.create() const action = defineAction()({ @@ -225,24 +225,28 @@ for (const factory of [ }) const abort = new AbortController() let observation: ReturnType | undefined + // Automatic discovery calls the Adapter's public fetch (ticket 10), not Client.fetch. let fetches = 0 - const fetch = client.fetch.bind(client) - client.fetch = async (options) => { + const fetch = instance.adapter.fetch.bind(instance.adapter) + instance.adapter.fetch = async (options) => { fetches++ return fetch(options) } try { - // Existing worker validation is not broadened by wait normalization. + // Existing constructor validation is not broadened by cadence normalization. for (const pullInterval of [NaN, Infinity, -Infinity]) { expect(() => new Client({ database: instance.adapter, pullInterval })).toThrow() } observation = observeTimers() await client.start() await eventually(() => fetches >= 2) - expect(observation.scheduled.some((entry) => entry.delay === 0.4)).toBe(true) - expect(observation.scheduled.some((entry) => entry.delay === 1)).toBe(false) + // Worker discovery floors/clamps 0.4 to 1 ms (worker policy), like waits. + expect(observation.scheduled.some((entry) => entry.delay === 0.4)).toBe(false) + expect(observation.scheduled.some((entry) => entry.delay === 1)).toBe(true) + // The wait loop's own normalization is covered by the cases above. const wait = client.waitForJob(crypto.randomUUID(), { signal: abort.signal }) - await eventually(() => observation!.scheduled.some((entry) => entry.delay === 1)) + await Bun.sleep(20) + expect(observation.scheduled.some((entry) => entry.delay === 0.4)).toBe(false) expect(client.getConfig().pullInterval).toBe(0.4) abort.abort() expect(await wait).toBeNull() diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts new file mode 100644 index 0000000..6f90648 --- /dev/null +++ b/packages/duron/test/worker-discovery.test.ts @@ -0,0 +1,1408 @@ +import { describe, expect, it } from 'bun:test' + +import pino from 'pino' + +import { defineAction } from '../src/action.js' +import type { Adapter } from '../src/adapters/adapter.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' + +// Control classes used below: +// - public-only: public Client/Adapter calls and public reads. +// - held: an instance-level pass-through wrapper on a public Adapter method that can +// pause before returning. The real method still runs; override dispatch is preserved. +// - fault-injected: a deliberate loss/error before transport or an injected rejection. + +const OBSERVE_MS = 10_000 +const TEST_MS = 40_000 + +async function eventually(check: () => boolean | Promise, message: string) { + const end = performance.now() + OBSERVE_MS + while (!(await check())) { + if (performance.now() >= end) throw new Error(`Bounded observation exceeded: ${message}`) + await Bun.sleep(5) + } +} + +async function status(adapter: Adapter, jobId: string) { + return (await adapter.getJobById(jobId))?.status +} + +// Fault-injected: drop availability notifications before transport. +function dropAvailabilityHints(adapter: Adapter) { + const target = adapter as unknown as { _notify: (event: string, data: unknown) => Promise } + const notify = target._notify.bind(adapter) + let dropped = 0 + target._notify = async (event, data) => { + if (event === 'job-available') { + dropped++ + return + } + return notify(event, data) + } + return () => dropped +} + +// Held: pass-through wrapper on the public Adapter.fetch instance method. Every call is +// recorded; while holding, each call waits for its own release before the real claim runs. +function holdFetch(adapter: Adapter) { + const real = adapter.fetch.bind(adapter) + const batches: number[] = [] + const gates: Array> = [] + let holding = true + let active = 0 + let maxActive = 0 + adapter.fetch = async (options) => { + batches.push(options.batch) + active++ + maxActive = Math.max(maxActive, active) + try { + if (holding) { + const gate = Promise.withResolvers() + gates.push(gate) + await gate.promise + } + return await real(options) + } finally { + active-- + } + } + return { + batches, + get active() { + return active + }, + get maxActive() { + return maxActive + }, + get held() { + return gates.length + }, + releaseNext() { + gates.shift()?.resolve() + }, + releaseAll() { + holding = false + for (const gate of gates.splice(0)) gate.resolve() + }, + } +} + +// Observational only: callbacks and delays reach the native timer unchanged. +function observeTimers() { + const schedule = globalThis.setTimeout + const delays: Array = [] + globalThis.setTimeout = ((...args: Parameters) => { + delays.push(args[1]) + return schedule(...args) + }) as typeof setTimeout + return { + delays, + restore() { + globalThis.setTimeout = schedule + }, + } +} + +async function statuses(adapter: Adapter, ids: string[]) { + return Promise.all(ids.map((id) => status(adapter, id))) +} + +function count(values: T[], value: T) { + return values.filter((item) => item === value).length +} + +// Held: pass-through wrapper on a public Adapter instance method, paused until released. +function holdMethod( + adapter: Adapter, + name: K, +) { + const target = adapter as any + const real = target[name].bind(adapter) + const gate = Promise.withResolvers() + let entered = 0 + target[name] = async (...args: unknown[]) => { + entered++ + await gate.promise + return real(...args) + } + return { + get entered() { + return entered + }, + release: () => gate.resolve(), + } +} + +// Fault-injected: the next `failures` public Adapter.fetch calls reject before the real claim. +function failFetch(adapter: Adapter, failures: number, error: Error) { + const real = adapter.fetch.bind(adapter) + const calls: number[] = [] + let remaining = failures + adapter.fetch = async (options) => { + calls.push(performance.now()) + if (remaining > 0) { + remaining-- + throw error + } + return real(options) + } + return calls +} + +function captureLogs() { + const entries: Array> = [] + const logger = pino( + { level: 'error' }, + { write: (line: string) => entries.push(JSON.parse(line)) }, + ) + return { + logger, + discovery: () => entries.filter((entry) => /WorkerDiscovery/.test(entry['msg'])), + } +} + +// A 40001-shaped error, as raised by a serializable claim conflict (injected, not natural). +function serializationFailure() { + return Object.assign(new Error('could not serialize access due to concurrent update'), { + code: '40001', + }) +} + +async function closeInstance( + client: Client | null, + instance: { deleteDb(): Promise }, +) { + await client?.stop().catch(() => undefined) + await instance.deleteDb() +} + +const factories: AdapterFactory[] = [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +] + +for (const factory of factories) { + describe(`Worker discovery with ${factory.name}`, () => { + it( + 'push worker discovers a pre-existing backlog at startup without a hint (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + let ran = 0 + const action = defineAction()({ + name: 'backlog', + handler: async () => { + ran++ + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { backlog: action }, + syncPattern: 'push', + pullInterval: 60_000, + recoverJobsOnStart: false, + logger: 'silent', + }) + // The job exists before the worker Client starts, so no hint reaches it. + expect(await instance.adapter.start()).toBe(true) + const jobId = await instance.adapter.createJob({ + queue: action.name, + groupKey: '@default', + input: {}, + timeoutMs: 10_000, + checksum: action.checksum, + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }) + expect(await client.start()).toBe(true) + await eventually( + async () => (await status(instance.adapter, jobId!)) === 'completed', + 'startup discovery completes backlog', + ) + expect(ran).toBe(1) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'push worker discovers work whose hint was dropped through periodic safety (fault-injected)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + const action = defineAction()({ name: 'dropped', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { dropped: action }, + syncPattern: 'push', + pullInterval: 50, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + const dropped = dropAvailabilityHints(instance.adapter) + const jobId = await client.runAction('dropped', {}) + expect(dropped()).toBe(1) + await eventually( + async () => (await status(instance.adapter, jobId)) === 'completed', + 'periodic safety completes the unhinted job', + ) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'push worker progresses after completion releases SQL group capacity without a new hint (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + const release = Promise.withResolvers() + let started = 0 + const action = defineAction()({ + name: 'grouped', + groups: { concurrency: async () => 1 }, + handler: async () => { + started++ + if (started === 1) await release.promise + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { grouped: action }, + syncPattern: 'push', + pullInterval: 50, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + const first = await client.runAction('grouped', {}) + await eventually(() => started === 1, 'first handler holds the only group slot') + const second = await client.runAction('grouped', {}) + await Bun.sleep(150) + expect(await status(instance.adapter, second)).toBe('created') + release.resolve() + await eventually( + async () => (await status(instance.adapter, second)) === 'completed', + 'released capacity is rediscovered', + ) + expect(await status(instance.adapter, first)).toBe('completed') + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'push worker runs recovery-produced work without a notification (real SQL claim, public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + let ran = 0 + const action = defineAction()({ + name: 'recovered', + handler: async () => { + ran++ + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { recovered: action }, + syncPattern: 'push', + pullInterval: 200, + recoverJobsOnStart: false, + recoverJobsInterval: 100, + logger: 'silent', + }) + const dropped = dropAvailabilityHints(instance.adapter) + expect(await client.start()).toBe(true) + const jobId = await client.runAction('recovered', {}) + // Direct Adapter claim is outside the Client coordinator: SQL-active, never executed. + const claimed = await instance.adapter.fetch({ batch: 1 }) + expect(claimed.map((job) => job.id)).toEqual([jobId]) + await eventually( + async () => (await status(instance.adapter, jobId)) === 'completed', + 'periodic recovery requeues and the worker completes the same job', + ) + expect(ran).toBe(1) + expect(dropped()).toBe(1) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + it( + 'push worker runs work requeued by startup recovery without a notification (real SQL claim, public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + let ran = 0 + const action = defineAction()({ + name: 'startup-recovered', + handler: async () => { + ran++ + return {} + }, + }) + client = new Client({ + id: 'startup-recovery-worker', + database: instance.adapter, + actions: { 'startup-recovered': action }, + syncPattern: 'push', + pullInterval: 60_000, + recoverJobsOnStart: true, + logger: 'silent', + }) + expect(await instance.adapter.start()).toBe(true) + const jobId = await instance.adapter.createJob({ + queue: action.name, + groupKey: '@default', + input: {}, + timeoutMs: 10_000, + checksum: action.checksum, + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }) + // Same-owner SQL claim that never executes; startup recovery includes the own ID. + expect((await instance.adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([ + jobId!, + ]) + const dropped = dropAvailabilityHints(instance.adapter) + expect(await client.start()).toBe(true) + await eventually( + async () => (await status(instance.adapter, jobId!)) === 'completed', + 'startup discovery runs the requeued job', + ) + expect(ran).toBe(1) + expect(dropped()).toBe(0) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'push worker claims work after expiry frees SQL group capacity without a new hint (real SQL claim, public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + let ran = 0 + const action = defineAction()({ + name: 'expiry', + expire: 500, + groups: { concurrency: async () => 1 }, + handler: async () => { + ran++ + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { expiry: action }, + syncPattern: 'push', + pullInterval: 200, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + const dropped = dropAvailabilityHints(instance.adapter) + expect(await client.start()).toBe(true) + const blocker = await client.runAction('expiry', {}) + // Direct Adapter claim outside the coordinator holds the only group slot until expiry. + const held = await instance.adapter.fetch({ batch: 1 }) + expect(held.map((job) => job.id)).toEqual([blocker]) + const waiting = await client.runAction('expiry', {}) + await Bun.sleep(100) + expect(await status(instance.adapter, waiting)).toBe('created') + await eventually( + async () => (await status(instance.adapter, waiting)) === 'completed', + 'periodic safety claims after expiry', + ) + expect(ran).toBe(1) + expect(dropped()).toBe(2) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'serves startup, hints, periodic ticks and manual calls through one chain in FIFO order (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + try { + const action = defineAction()({ name: 'mixed', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { mixed: action }, + syncPattern: 'hybrid', + pullInterval: 10, + batchSize: 3, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await eventually(() => fetch.held === 1, 'startup pass is held') + for (let i = 0; i < 5; i++) instance.adapter.emit('job-available', { jobId: `hint-${i}` }) + await Bun.sleep(60) // several periodic ticks elapse while the chain is held + const first = client.fetch({ batchSize: 7 }) + const second = client.fetch({ batchSize: 9 }) + await Bun.sleep(20) + expect(fetch.batches).toEqual([3]) + // One merged automatic marker (hint + periodic => B), then the manual calls in order. + for (const expected of [ + [3, 3], + [3, 3, 7], + [3, 3, 7, 9], + ]) { + fetch.releaseNext() + await eventually( + () => fetch.batches.length === expected.length, + `next call ${expected}`, + ) + expect(fetch.batches).toEqual(expected) + } + fetch.releaseAll() + expect(await first).toEqual([]) + expect(await second).toEqual([]) + expect(fetch.maxActive).toBe(1) + } finally { + fetch.releaseAll() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'coalesces hint-only demand into one single-job follow-up (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + try { + const action = defineAction()({ name: 'hinted', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { hinted: action }, + syncPattern: 'push', + pullInterval: 60_000, + batchSize: 4, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await eventually(() => fetch.held === 1, 'startup pass is held') + for (let i = 0; i < 6; i++) instance.adapter.emit('job-available', { jobId: `hint-${i}` }) + fetch.releaseNext() + await eventually(() => fetch.batches.length === 2, 'one follow-up') + fetch.releaseAll() + await Bun.sleep(50) + expect(fetch.batches).toEqual([4, 1]) + expect(fetch.maxActive).toBe(1) + } finally { + fetch.releaseAll() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + for (const [pullInterval, interval] of [ + [0, 5_000], + [-3, 5_000], + [2.9, 2], + [2_147_483_648, 2_147_483_647], + ] as const) { + it.serial( + `normalizes worker cadence ${pullInterval} to ${interval} with one timer (observational)`, + async () => { + const instance = await factory.create() + let client: Client | null = null + const timers = observeTimers() + try { + const action = defineAction()({ name: 'cadence', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { cadence: action }, + syncPattern: 'hybrid', + pullInterval, + heartbeatInterval: 123_456, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await Bun.sleep(20) + timers.restore() + expect(client.getConfig().pullInterval).toBe(pullInterval) + expect(timers.delays).toContain(interval) + // Every case changes the value, so the raw delay never reaches a timer. + expect(timers.delays).not.toContain(pullInterval) + // One worker timer; no parallel pull and safety loops. + if (interval >= 5_000) + expect(timers.delays.filter((d) => d === interval)).toHaveLength(1) + } finally { + timers.restore() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + } + + for (const [batchSize, batch] of [ + [0, 10], + [-1, 10], + [2.9, 2], + [1e20, Number.MAX_SAFE_INTEGER], + ] as const) { + it( + `normalizes the automatic batch ${batchSize} to ${batch} (held)`, + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + try { + const action = defineAction()({ name: 'batch', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { batch: action }, + syncPattern: 'pull', + pullInterval: 60_000, + batchSize, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await eventually(() => fetch.batches.length === 1, 'startup pass') + expect(fetch.batches).toEqual([batch]) + expect(client.getConfig().batchSize).toBe(batchSize) + } finally { + fetch.releaseAll() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + } + it( + 'keeps automatic claims within B across claimed, queued and running local work (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const gates: Array> = [] + try { + const action = defineAction()({ + name: 'ceiling', + handler: async () => { + const gate = Promise.withResolvers() + gates.push(gate) + await gate.promise + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { ceiling: action }, + syncPattern: 'pull', + pullInterval: 20, + batchSize: 2, + actionConcurrencyLimit: 1, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + const ids: string[] = [] + for (let i = 0; i < 5; i++) ids.push(await client.runAction('ceiling', {})) + await eventually( + async () => count(await statuses(instance.adapter, ids), 'active') === 2, + 'B claims', + ) + await Bun.sleep(150) // many periodic ticks: one running + one locally queued fill B + expect(count(await statuses(instance.adapter, ids), 'active')).toBe(2) + expect(gates).toHaveLength(1) + for (let done = 1; done <= 5; done++) { + await eventually(() => gates.length >= done, `handler ${done} starts`) + gates[done - 1]!.resolve() + await eventually( + async () => count(await statuses(instance.adapter, ids), 'completed') === done, + `job ${done} completes`, + ) + expect(count(await statuses(instance.adapter, ids), 'active')).toBeLessThanOrEqual(2) + } + } finally { + for (const gate of gates) gate.resolve() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'counts finalization and a lingering timed-out handler until actual settlement (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const lingering = Promise.withResolvers() + const complete = holdMethod(instance.adapter, 'completeJob') + try { + let started = 0 + const slow = defineAction()({ + name: 'slow', + expire: 100, + // Ignores abort: its raw promise outlives the timeout race and failure write. + handler: async () => { + started++ + await lingering.promise + return {} + }, + }) + const quick = defineAction()({ + name: 'quick', + handler: async () => { + started++ + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { slow, quick }, + syncPattern: 'pull', + pullInterval: 20, + batchSize: 1, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + const timedOut = await client.runAction('slow', {}) + await eventually( + async () => (await status(instance.adapter, timedOut)) === 'failed', + 'timeout failure is written', + ) + const next = await client.runAction('quick', {}) + await Bun.sleep(150) + expect(await status(instance.adapter, next)).toBe('created') + lingering.resolve() + // The quick handler returns, then its completion write is held: still outstanding. + await eventually( + () => started === 2 && complete.entered === 1, + 'quick finalization is held', + ) + const third = await client.runAction('quick', {}) + await Bun.sleep(150) + expect(await status(instance.adapter, third)).toBe('created') + complete.release() + await eventually( + async () => + (await statuses(instance.adapter, [next, third])).every((s) => s === 'completed'), + 'released finalization frees room', + ) + } finally { + lingering.resolve() + complete.release() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'lets manual batches exceed B and pauses automatic claims until enough work settles (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const gates: Array> = [] + try { + const action = defineAction()({ + name: 'manual', + handler: async () => { + const gate = Promise.withResolvers() + gates.push(gate) + await gate.promise + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { manual: action }, + syncPattern: 'pull', + pullInterval: 20, + batchSize: 1, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await instance.adapter.start()).toBe(true) + const ids: string[] = [] + for (let i = 0; i < 3; i++) { + ids.push( + (await instance.adapter.createJob({ + queue: action.name, + groupKey: `g${i}`, + input: {}, + timeoutMs: 10_000, + checksum: action.checksum, + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }))!, + ) + } + // FIFO: the startup pass claims B=1, then this manual call claims the other two. + const claimed = await client.fetch({ batchSize: 3 }) + expect(claimed).toHaveLength(2) + await eventually(() => gates.length === 3, 'three handlers run') + const later = await client.runAction('manual', {}) + await Bun.sleep(150) // periodic ticks while 3 > B outstanding + expect(await status(instance.adapter, later)).toBe('created') + gates[0]!.resolve() + gates[1]!.resolve() + await eventually( + async () => count(await statuses(instance.adapter, ids), 'completed') === 2, + 'two settle', + ) + await Bun.sleep(150) + expect(await status(instance.adapter, later)).toBe('created') + gates[2]!.resolve() + await eventually(() => gates.length === 4, 'automatic claiming resumes') + gates[3]!.resolve() + await eventually( + async () => (await status(instance.adapter, later)) === 'completed', + 'later completes', + ) + } finally { + for (const gate of gates) gate.resolve() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'counts an unknown-action failure write as outstanding local work (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fail = holdMethod(instance.adapter, 'failJob') + try { + const known = defineAction()({ name: 'known', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { known }, + syncPattern: 'pull', + pullInterval: 20, + batchSize: 1, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await instance.adapter.start()).toBe(true) + const ghost = await instance.adapter.createJob({ + queue: 'ghost', + groupKey: '@default', + input: {}, + timeoutMs: 10_000, + checksum: 'ghost', + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }) + expect(await client.start()).toBe(true) + await eventually(() => fail.entered === 1, 'unknown-action failure write is held') + const next = await client.runAction('known', {}) + await Bun.sleep(150) + expect(await status(instance.adapter, next)).toBe('created') + fail.release() + await eventually( + async () => (await status(instance.adapter, next)) === 'completed', + 'room frees', + ) + expect(await status(instance.adapter, ghost!)).toBe('failed') + } finally { + fail.release() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + it( + 'logs a background claim failure once, cools down all triggers, then claims afresh (fault-injected)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + const logs = captureLogs() + const action = defineAction()({ name: 'cooldown', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { cooldown: action }, + syncPattern: 'hybrid', + pullInterval: 300, + batchSize: 2, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: logs.logger, + }) + const injected = serializationFailure() + const calls = failFetch(instance.adapter, 1, injected) + expect(await client.start()).toBe(true) + await eventually(() => calls.length === 1, 'startup claim fails') + const failedAt = calls[0]! + // Hints and a manual call during cooldown wait; they are not rejected. + for (let i = 0; i < 3; i++) instance.adapter.emit('job-available', { jobId: `hint-${i}` }) + const jobId = await client.runAction('cooldown', {}) + let manualAt = 0 + const manual = client.fetch({ batchSize: 1 }).then((jobs) => { + manualAt = performance.now() + return jobs + }) + await Bun.sleep(150) + expect(calls).toHaveLength(1) + await manual + expect(calls[1]! - failedAt).toBeGreaterThanOrEqual(290) + expect(manualAt - failedAt).toBeGreaterThanOrEqual(290) + await eventually( + async () => (await status(instance.adapter, jobId)) === 'completed', + 'progress after cooldown', + ) + const failures = logs.discovery() + expect(failures).toHaveLength(1) + expect(failures[0]!['stage']).toBe('claim') + expect(failures[0]!['triggers']).toEqual(['startup']) + expect(failures[0]!['error']['code']).toBe('40001') + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'rejects a failed manual call without replay or autonomous retry in disabled mode (fault-injected)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + const logs = captureLogs() + const action = defineAction()({ name: 'disabled', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { disabled: action }, + syncPattern: false, + pullInterval: 200, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: logs.logger, + }) + const injected = serializationFailure() + const calls = failFetch(instance.adapter, 1, injected) + await expect(client.fetch()).rejects.toBe(injected) + await Bun.sleep(250) + expect(calls).toHaveLength(1) + expect(logs.discovery()).toHaveLength(0) + const jobId = await client.runAction('disabled', {}) + expect((await client.fetch()).map((job) => job.id)).toEqual([jobId]) + expect(calls).toHaveLength(2) + // The next manual call after a fresh failure waits one cooldown before its claim. + const again = failFetch(instance.adapter, 1, injected) + await expect(client.fetch()).rejects.toBe(injected) + await client.fetch() + expect(again).toHaveLength(2) + expect(again[1]! - again[0]!).toBeGreaterThanOrEqual(190) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'skips the claim after a background recovery failure and claims after cooldown without rerunning recovery (fault-injected)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + const logs = captureLogs() + const action = defineAction()({ name: 'recovery-fail', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { 'recovery-fail': action }, + syncPattern: 'pull', + pullInterval: 100, + recoverJobsOnStart: false, + recoverJobsInterval: 60_000, + logger: logs.logger, + }) + const realRecover = instance.adapter.recoverJobs.bind(instance.adapter) + let recoveries = 0 + instance.adapter.recoverJobs = async (options) => { + recoveries++ + if (recoveries === 1) throw new Error('injected recovery failure') + return realRecover(options) + } + const calls = failFetch(instance.adapter, 0, new Error('unused')) + expect(await client.start()).toBe(true) + await eventually(() => recoveries === 1, 'unanchored first turn recovers') + await Bun.sleep(50) + expect(calls).toHaveLength(0) + await eventually(() => calls.length >= 1, 'a later turn claims') + expect(recoveries).toBe(1) + const failures = logs.discovery() + expect(failures).toHaveLength(1) + expect(failures[0]!['stage']).toBe('recovery') + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + it( + 'stop rejects queued manual calls, clears automatic demand and never resurrects timers (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + try { + const action = defineAction()({ name: 'stop-queued', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { 'stop-queued': action }, + syncPattern: 'hybrid', + pullInterval: 10, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await eventually(() => fetch.held === 1, 'startup pass is held') + instance.adapter.emit('job-available', { jobId: 'hint' }) + const queued = client.fetch({ batchSize: 2 }) + const outcome = queued.then( + () => 'resolved', + (error: Error) => error.message, + ) + await Bun.sleep(30) + const stopped = client.stop() + expect(await outcome).toBe('Lifecycle is not accepting work') + fetch.releaseAll() + expect(await stopped).toBe(true) + await Bun.sleep(100) + expect(fetch.batches).toHaveLength(1) + } finally { + fetch.releaseAll() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'stop during the recovery barrier rejects waiting calls and starts no recovery (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const release = Promise.withResolvers() + try { + let started = 0 + let aborted = false + const action = defineAction()({ + name: 'stop-barrier', + handler: async (ctx) => { + started++ + await ctx.step('hold', async ({ signal }) => { + signal.addEventListener('abort', () => { + aborted = true + }) + await release.promise + return {} + }) + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { 'stop-barrier': action }, + syncPattern: false, + recoverJobsOnStart: true, + recoverJobsInterval: 100, + logger: 'silent', + }) + const realRecover = instance.adapter.recoverJobs.bind(instance.adapter) + let recoveries = 0 + instance.adapter.recoverJobs = async (options) => { + recoveries++ + return realRecover(options) + } + await client.runAction('stop-barrier', {}) + expect(await client.fetch()).toHaveLength(1) + await eventually(() => started === 1, 'handler holds local work') + await Bun.sleep(150) // recovery is now due + const waiting = client.fetch().then( + () => 'resolved', + (error: Error) => error.message, + ) + await Bun.sleep(50) + const before = recoveries + const stopped = client.stop() + expect(await waiting).toBe('Lifecycle is not accepting work') + expect(aborted).toBe(true) + release.resolve() + expect(await stopped).toBe(true) + expect(recoveries).toBe(before) + } finally { + release.resolve() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'stop after admitted recovery issues no new claim and rejects the admitted manual call (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const gate = holdMethod(instance.adapter, 'recoverJobs') + const fetch = holdFetch(instance.adapter) + fetch.releaseAll() + try { + const action = defineAction()({ name: 'stop-recovery', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { 'stop-recovery': action }, + syncPattern: false, + recoverJobsOnStart: false, + recoverJobsInterval: 1_000, + logger: 'silent', + }) + await client.runAction('stop-recovery', {}) + const admitted = client.fetch().then( + () => 'resolved', + (error: Error) => error.message, + ) + await eventually(() => gate.entered === 1, 'admitted recovery is held') + const stopped = client.stop() + gate.release() + expect(await admitted).toBe('Lifecycle is not accepting work') + expect(await stopped).toBe(true) + expect(fetch.batches).toHaveLength(0) + } finally { + gate.release() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'an automatic claim issued before stop returns without starting a handler (held after SQL)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const release = Promise.withResolvers() + try { + let started = 0 + const action = defineAction()({ + name: 'stop-claim', + handler: async () => { + started++ + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { 'stop-claim': action }, + syncPattern: 'pull', + pullInterval: 60_000, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await instance.adapter.start()).toBe(true) + const id = await instance.adapter.createJob({ + queue: action.name, + groupKey: '@default', + input: {}, + timeoutMs: 10_000, + checksum: action.checksum, + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }) + const real = instance.adapter.fetch.bind(instance.adapter) + const claimed = Promise.withResolvers() + instance.adapter.fetch = async (options) => { + const jobs = await real(options) + claimed.resolve(jobs.map((job) => job.id)) + await release.promise + return jobs + } + expect(await client.start()).toBe(true) + expect(await claimed.promise).toEqual([id!]) + const stopped = client.stop() + release.resolve() + expect(await stopped).toBe(true) + expect(started).toBe(0) + } finally { + release.resolve() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'stop prevents a locally queued claimed job from starting after the gate (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const release = Promise.withResolvers() + try { + let started = 0 + const action = defineAction()({ + name: 'stop-local', + handler: async () => { + started++ + await release.promise + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { 'stop-local': action }, + syncPattern: false, + actionConcurrencyLimit: 1, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + await client.runAction('stop-local', {}) + await client.runAction('stop-local', {}) + expect(await client.fetch({ batchSize: 2 })).toHaveLength(2) + await eventually(() => started === 1, 'one runs, one is locally queued') + const stopped = client.stop() + release.resolve() + expect(await stopped).toBe(true) + await Bun.sleep(50) + expect(started).toBe(1) + } finally { + release.resolve() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + it( + 'omitted actions never claim or recover, and explicit fetch returns [] without Adapter.fetch (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + fetch.releaseAll() + try { + let recoveries = 0 + const recover = instance.adapter.recoverJobs.bind(instance.adapter) + instance.adapter.recoverJobs = async (options) => { + recoveries++ + return recover(options) + } + client = new Client({ + database: instance.adapter, + syncPattern: 'hybrid', + pullInterval: 10, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + instance.adapter.emit('job-available', { jobId: 'hint' }) + const waited = await client.waitForJob(crypto.randomUUID(), { timeout: 50 }) + expect(waited).toBeNull() + expect(await client.fetch()).toEqual([]) + await Bun.sleep(50) + expect(fetch.batches).toHaveLength(0) + expect(recoveries).toBe(0) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'actions:{} keeps worker behavior: startup discovery fails an unknown-action job (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + client = new Client({ + database: instance.adapter, + actions: {}, + syncPattern: 'push', + pullInterval: 60_000, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await instance.adapter.start()).toBe(true) + const ghost = await instance.adapter.createJob({ + queue: 'ghost', + groupKey: '@default', + input: {}, + timeoutMs: 10_000, + checksum: 'ghost', + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }) + expect(await client.start()).toBe(true) + await eventually( + async () => (await status(instance.adapter, ghost!)) === 'failed', + 'unknown action fails', + ) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'syncPattern:false keeps startup recovery and explicit fetch without automatic claims (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + fetch.releaseAll() + try { + let recoveries = 0 + const recover = instance.adapter.recoverJobs.bind(instance.adapter) + instance.adapter.recoverJobs = async (options) => { + recoveries++ + return recover(options) + } + const action = defineAction()({ name: 'manual-only', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { 'manual-only': action }, + syncPattern: false, + pullInterval: 10, + recoverJobsOnStart: true, + recoverJobsInterval: 60_000, + logger: 'silent', + }) + const jobId = await client.runAction('manual-only', {}) + expect(recoveries).toBe(1) + instance.adapter.emit('job-available', { jobId }) + const waiting = client.waitForJob(jobId, { timeout: 100 }) + await Bun.sleep(100) + expect(fetch.batches).toHaveLength(0) + expect(await waiting).toBeNull() + expect((await client.fetch({ batchSize: 3 })).map((job) => job.id)).toEqual([jobId]) + expect(fetch.batches).toEqual([3]) + expect(recoveries).toBe(1) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + }) +} + +if (process.env['POSTGRES_TEST'] === 'true') { + describe('Worker discovery across PostgreSQL workers', () => { + it( + 'two push workers drain a backlog with no hints, each job once, within group limits (public-only)', + async () => { + const instance = await postgresFactory.create() + const second = new PostgresAdapter({ + connection: instance.connectionUrl, + migrateOnStart: true, + }) + const clients: Client[] = [] + try { + const runs = new Map() + let active = 0 + let maxActive = 0 + const action = defineAction()({ + name: 'shared-backlog', + groups: { groupKey: async () => 'shared', concurrency: async () => 2 }, + handler: async (ctx) => { + runs.set(ctx.jobId, (runs.get(ctx.jobId) ?? 0) + 1) + active++ + maxActive = Math.max(maxActive, active) + await Bun.sleep(30) + active-- + return {} + }, + }) + for (const [id, adapter] of [ + ['worker-a', instance.adapter], + ['worker-b', second], + ] as const) { + clients.push( + new Client({ + id, + database: adapter, + actions: { 'shared-backlog': action }, + syncPattern: 'push', + pullInterval: 50, + batchSize: 3, + recoverJobsOnStart: false, + logger: 'silent', + }), + ) + } + expect(await instance.adapter.start()).toBe(true) + const ids: string[] = [] + for (let i = 0; i < 8; i++) { + ids.push( + (await instance.adapter.createJob({ + queue: action.name, + groupKey: 'shared', + input: {}, + timeoutMs: 10_000, + checksum: action.checksum, + concurrencyLimit: 2, + concurrencyStepLimit: 10, + description: null, + }))!, + ) + } + for (const client of clients) expect(await client.start()).toBe(true) + await eventually( + async () => count(await statuses(instance.adapter, ids), 'completed') === ids.length, + 'both workers drain the backlog', + ) + expect([...runs.values()].every((value) => value === 1)).toBe(true) + expect(runs.size).toBe(ids.length) + expect(maxActive).toBeLessThanOrEqual(2) + } finally { + for (const client of clients) await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + }) +} diff --git a/packages/duron/test/worker-recovery.test.ts b/packages/duron/test/worker-recovery.test.ts new file mode 100644 index 0000000..b1f8a46 --- /dev/null +++ b/packages/duron/test/worker-recovery.test.ts @@ -0,0 +1,304 @@ +import { afterEach, describe, expect, it, spyOn } from 'bun:test' + +import { defineAction } from '../src/action.js' +import type { Adapter } from '../src/adapters/adapter.js' +import { Client } from '../src/client.js' + +import { type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' + +// Control classes used below: +// - public-only: public Client/Adapter calls and public reads. +// - held: pass-through wrapper on a public Adapter instance method that can pause. +// - fault-injected: an injected rejection from a public Adapter instance method. +// - controlled clock: serial-only spies on the global performance.now / Date.now. Serial +// tests never interleave with other tests (verified under `bun test --concurrent`); +// both spies are restored before stop so lifecycle budgets observe the real clock. + +const OBSERVE_MS = 10_000 +const TEST_MS = 40_000 + +async function eventually(check: () => boolean | Promise, message: string) { + const end = performance.now() + OBSERVE_MS + while (!(await check())) { + if (performance.now() >= end) throw new Error(`Bounded observation exceeded: ${message}`) + await Bun.sleep(5) + } +} + +async function status(adapter: Adapter, jobId: string) { + return (await adapter.getJobById(jobId))?.status +} + +type Event = string + +// Held pass-through wrappers that log entry/exit of recovery and claim calls. +function traceCalls(adapter: Adapter, events: Event[]) { + const recover = adapter.recoverJobs.bind(adapter) + const fetch = adapter.fetch.bind(adapter) + let active = 0 + let overlap = 0 + let recoverGate: PromiseWithResolvers | null = null + let recoverFailure: Error | null = null + const enter = (name: string) => { + active++ + if (active > 1) overlap++ + events.push(`${name}:start`) + } + const leave = (name: string) => { + active-- + events.push(`${name}:end`) + } + adapter.recoverJobs = async (options) => { + enter('recover') + try { + if (recoverGate) await recoverGate.promise + if (recoverFailure) throw recoverFailure + return await recover(options) + } finally { + leave('recover') + } + } + adapter.fetch = async (options) => { + enter('fetch') + try { + return await fetch(options) + } finally { + leave('fetch') + } + } + return { + get overlap() { + return overlap + }, + holdRecovery() { + recoverGate = Promise.withResolvers() + }, + releaseRecovery() { + recoverGate?.resolve() + recoverGate = null + }, + failRecovery(error: Error | null) { + recoverFailure = error + }, + recoveries: () => events.filter((event) => event === 'recover:start').length, + } +} + +const factories: AdapterFactory[] = [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +] + +for (const factory of factories) { + describe(`Worker recovery with ${factory.name}`, () => { + it( + 'due recovery under a full ceiling waits for actual local settlement and precedes the next claim (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const release = Promise.withResolvers() + const events: Event[] = [] + try { + let runs = 0 + const action = defineAction()({ + name: 'barrier', + handler: async () => { + runs++ + events.push('handler:start') + await release.promise + events.push('handler:end') + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { barrier: action }, + syncPattern: 'pull', + pullInterval: 20, + batchSize: 1, + recoverJobsOnStart: true, + recoverJobsInterval: 150, + logger: 'silent', + }) + const trace = traceCalls(instance.adapter, events) + expect(await client.start()).toBe(true) + const first = await client.runAction('barrier', {}) + await eventually(() => runs === 1, 'first handler holds the only automatic slot') + const recoveriesWhileHeld = trace.recoveries() + // A manual call issued while recovery is due must wait behind the barrier. + await Bun.sleep(300) + let manualSettled = false + const manual = client.fetch({ batchSize: 5 }).finally(() => { + manualSettled = true + }) + await Bun.sleep(100) + expect(trace.recoveries()).toBe(recoveriesWhileHeld) + expect(manualSettled).toBe(false) + const second = await client.runAction('barrier', {}) + await Bun.sleep(100) + expect(await status(instance.adapter, second)).toBe('created') + // Still-live local work was not requeued by a recovery pass. + expect(await status(instance.adapter, first)).toBe('active') + release.resolve() + await manual + await eventually( + async () => (await status(instance.adapter, second)) === 'completed', + 'claiming resumes after recovery', + ) + expect(await status(instance.adapter, first)).toBe('completed') + expect(runs).toBe(2) + const firstEnd = events.indexOf('handler:end') + const nextRecovery = events.indexOf('recover:start', firstEnd) + expect(nextRecovery).toBeGreaterThan(firstEnd) + expect(events.indexOf('fetch:start', firstEnd)).toBeGreaterThan(nextRecovery) + expect(trace.overlap).toBe(0) + } finally { + release.resolve() + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + + describe('monotonic recovery cadence (controlled clock)', () => { + let restore: Array<() => void> = [] + afterEach(() => { + for (const undo of restore.splice(0)) undo() + }) + + function controlClocks() { + let monotonic = 0 + let wallOffset = 0 + const realDate = Date.now.bind(Date) + const perf = spyOn(performance, 'now').mockImplementation(() => monotonic) + const date = spyOn(Date, 'now').mockImplementation(() => realDate() + wallOffset) + const undo = () => { + perf.mockRestore() + date.mockRestore() + } + restore.push(undo) + return { + set monotonic(value: number) { + monotonic = value + }, + set wallOffset(value: number) { + wallOffset = value + }, + restore: undo, + } + } + + it.serial( + 'anchors at startup and settlement, floors samples, uses strict >, ignores wall offsets and jumps', + async () => { + const instance = await factory.create() + let client: Client | null = null + const events: Event[] = [] + const clock = controlClocks() + try { + const action = defineAction()({ name: 'cadence', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { cadence: action }, + syncPattern: false, + pullInterval: 50, + recoverJobsOnStart: true, + recoverJobsInterval: 1_000, + logger: 'silent', + }) + const trace = traceCalls(instance.adapter, events) + clock.wallOffset = 60_000 // constant application wall offset + clock.monotonic = 10_000.4 + expect(await client.start()).toBe(true) + expect(trace.recoveries()).toBe(1) // startup recovery anchors at floor(10000.4) + + clock.monotonic = 11_000.9 // floors to elapsed 1000: equality is not due + await client.fetch() + expect(trace.recoveries()).toBe(1) + + clock.wallOffset = 60_000 + 3_600_000 // forward wall jump + await client.fetch() + clock.wallOffset = -3_600_000 // backward wall jump + await client.fetch() + expect(trace.recoveries()).toBe(1) + + // +1 is due. Hold the attempt: the anchor is its settlement, not its admission. + clock.monotonic = 11_001 + trace.holdRecovery() + const due = client.fetch() + await eventually(() => trace.recoveries() === 2, 'due recovery starts') + clock.monotonic = 11_500 + trace.releaseRecovery() + await due + + clock.monotonic = 12_500 + await client.fetch() + expect(trace.recoveries()).toBe(2) + + // A failed attempt also anchors at its settlement; the manual call rejects. + clock.monotonic = 12_501 + const injected = new Error('injected recovery failure') + trace.failRecovery(injected) + await expect(client.fetch()).rejects.toBe(injected) + expect(trace.recoveries()).toBe(3) + trace.failRecovery(null) + expect(events.filter((event) => event === 'fetch:start')).toHaveLength(5) + + // Past the one-pullInterval cooldown, the next turn claims without recovering. + clock.monotonic = 13_501 + await client.fetch() + expect(trace.recoveries()).toBe(3) + clock.monotonic = 13_502 + await client.fetch() + expect(trace.recoveries()).toBe(4) + } finally { + clock.restore() + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + + it.serial( + 'recovers on the first unanchored turn at process elapsed zero; interval 0 disables periodic recovery', + async () => { + for (const [recoverJobsInterval, first, later] of [ + [1_000, 1, 2], + [0, 0, 0], + ] as const) { + const instance = await factory.create() + let client: Client | null = null + const events: Event[] = [] + const clock = controlClocks() + try { + const action = defineAction()({ name: 'unanchored', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { unanchored: action }, + syncPattern: false, + recoverJobsOnStart: false, + recoverJobsInterval, + logger: 'silent', + }) + const trace = traceCalls(instance.adapter, events) + clock.monotonic = 0.4 + expect(await client.start()).toBe(true) + await client.fetch() + expect(trace.recoveries()).toBe(first) + clock.monotonic = 10_000_000 + await client.fetch() + expect(trace.recoveries()).toBe(later) + } finally { + clock.restore() + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + } + }, + TEST_MS, + ) + }) + }) +} From 617535ad51e07ddbc9705c28ff1fd07c65cb8ab2 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 01:11:31 -0300 Subject: [PATCH 021/100] docs: warn against awaiting client.fetch() inside a job handler While periodic recovery is due, fetch() waits for this Client's running jobs, including the calling handler, so it can wait until stop rejects it. Documentation only; no behavior change. --- packages/docs/content/docs/client-api.mdx | 2 ++ packages/docs/content/docs/multi-worker.mdx | 3 +++ 2 files changed, 5 insertions(+) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index ccedb9d..1e97634 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -293,6 +293,8 @@ Manually fetch and process jobs from the database. Each call keeps its own batch and returns the jobs it actually claimed, after its claim (not after the handlers finish). Calls are served one at a time together with automatic discovery, in arrival order, so a call can wait behind a running discovery, a due recovery (see `recoverJobsInterval`) or a failure cooldown. A failed call rejects with the original error and is not retried. Calls still waiting when `stop()` begins reject; a call whose claim was already issued returns its jobs, but no handler starts after `stop()`. Direct `client.database.fetch()` calls are outside this coordination. +**Warning:** Do not await `client.fetch()` inside a job handler. While periodic recovery is due, `fetch()` waits for this Client's running jobs to settle, including the handler that is waiting for it. The call can then wait until `client.stop()` rejects it. + ```ts const jobs = await client.fetch({ batchSize: 20, diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index cf0e9e9..3c11082 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -243,6 +243,9 @@ Each Client with actions coordinates its own job discovery: - **Safety in every mode.** With `syncPattern` `'push'`, `'hybrid'` or `'pull'`, the Client discovers work immediately after startup and then every `pullInterval`. Notifications only make discovery faster. Work whose notification was lost, work requeued by recovery, and work that becomes claimable after a group slot frees up or a job expires is found by the next periodic check. - **Automatic claim ceiling.** Automatic claims stop while this Client has `batchSize` claimed jobs outstanding (claimed, queued, running or finishing). See [`batchSize`](/docs/client-api#batchsize) for how this differs from `actionConcurrencyLimit` and SQL group limits. - **Recovery barrier.** When periodic recovery is due, the Client stops claiming and waits for its own claimed jobs to settle before it runs recovery. This keeps recovery from requeuing jobs that this Client is still running. It is not a database lock and does not coordinate with other workers. + + **Warning:** Do not await `client.fetch()` inside a job handler. While periodic recovery is due, `fetch()` waits for this Client's running jobs to settle, including the handler that is waiting for it. The call can then wait until `client.stop()` rejects it. + - **Failures.** After a failed discovery or recovery attempt, all discovery waits one `pullInterval`. Failed claims are never replayed. This coordination is local to one Client. Other Clients, and direct calls such as `client.database.fetch()` or `client.database.recoverJobs()`, are not coordinated with it. Cross-worker group limits rely on the claim admission described above, not on this local coordination. From dfb0611473ff229b6fef13ace520eed848b9dab5 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 12:46:18 -0300 Subject: [PATCH 022/100] fix(duron): suppress locally claimed jobs cancelled before their handler starts Cover the claim-reply-pending and queued/deferred windows of this Client's own claims. Each admitted non-running cancelJob call registers an intent synchronously, reseeds it with every issued fetch and issues its own Adapter.cancelJob; dispatch only suppresses. A suppressed claim keeps its one ledger unit until the overlapping writes settle. Return values, per-call errors, remote continuation and waitForJob semantics are unchanged; cancellation never waits for worker discovery or recovery. --- packages/docs/content/docs/client-api.mdx | 13 +- packages/docs/content/docs/jobs-and-steps.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/src/action-manager.ts | 40 +- packages/duron/src/client.ts | 67 +- packages/duron/src/local-cancellation.ts | 174 +++ packages/duron/src/worker-discovery.ts | 26 +- .../test/local-cancellation-registry.test.ts | 183 +++ .../duron/test/local-cancellation.test.ts | 1374 +++++++++++++++++ 9 files changed, 1846 insertions(+), 35 deletions(-) create mode 100644 packages/duron/src/local-cancellation.ts create mode 100644 packages/duron/test/local-cancellation-registry.test.ts create mode 100644 packages/duron/test/local-cancellation.test.ts diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 1e97634..cca6ac4 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -319,7 +319,16 @@ await client.cancelJob(jobId) - `jobId` - The ID of the job to cancel -**Returns:** Promise resolving to `true` if cancelled, `false` otherwise +**Returns:** Promise resolving to `true` if the job is running on this Client and was aborted, `false` otherwise + +What happens depends on where the job is: + +- **Running on this Client** (its handler has started, including while it finishes up after an abort): the handler is aborted in memory and the call returns `true`. The job writes its own cancellation when it settles. +- **Anything else**: the call issues its own `Adapter.cancelJob` and returns `false`, even when the database cancellation succeeds. If that write rejects, the rejection reaches this caller only. Concurrent calls each issue their own write and get their own result. +- **Claimed by this Client but not started**: the claim reply is still pending, or the job is queued behind `actionConcurrencyLimit`. Once a call is admitted, the job's handler never starts, even if the write rejects. Duron does not retry, replay or compensate the write. A job that a rejected write left active can later be recovered: requeued (and run again) if it has not expired, or archived as `failed` if it has. The suppressed claim keeps its slot in the automatic claim ceiling until the overlapping cancellation writes settle. +- **Running on another Client**: the database cancellation does not stop it. Its handler continues until a step write finds the job inactive, then follows the normal failed-job path. A job that another Client has claimed or queued is not suppressed by a cancellation made elsewhere. + +This is in-process handling for this Client's own claims, not a durable or fenced cancellation guarantee. Cancellation never waits for worker discovery or the recovery barrier. After `stop()`, new external calls reject; a call made from a running handler during shutdown is still admitted, starts no handler, and its write is observed (or reported as incomplete) by the drain. ### `retryJob(jobId)` @@ -357,6 +366,8 @@ console.log(result.output) // Typed based on action's output schema - `options.signal` - Optional AbortSignal to cancel the operation. If aborted, the job will be cancelled and the promise will reject. - `options.timeout` - Optional timeout in milliseconds. If the job doesn't complete within this time, the job will be cancelled and the promise will reject. +On abort or timeout the promise rejects immediately and `cancelJob(jobId)` runs in the background (its errors are logged), with the behavior described under [`cancelJob`](#canceljobjobid). `waitForJob` is different: its timeout or abort settles only that waiter and never cancels the job. + **Returns:** Promise resolving to the job result with typed input and output **Example:** diff --git a/packages/docs/content/docs/jobs-and-steps.mdx b/packages/docs/content/docs/jobs-and-steps.mdx index 322b5bd..a7db1f4 100644 --- a/packages/docs/content/docs/jobs-and-steps.mdx +++ b/packages/docs/content/docs/jobs-and-steps.mdx @@ -79,7 +79,7 @@ You can cancel a job: await client.cancelJob(jobId) ``` -A cancelled job is archived with every step marked `cancelled`. For how cancellation interacts with concurrent step writes, completion, claims and recovery on PostgreSQL, and its limits, see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps). +A cancelled job is archived with every step marked `cancelled`. `cancelJob` returns `true` only when the job is running on this Client and was aborted in memory; a job this Client has claimed but not started never starts its handler. See [`cancelJob`](/docs/client-api#canceljobjobid) for the local and remote guarantees. For how cancellation interacts with concurrent step writes, completion, claims and recovery on PostgreSQL, and its limits, see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps). ### Retrying Jobs diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 3c11082..2057951 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -270,7 +270,7 @@ Limits: - A call that waited checks expiry against its transaction's start time, not the time it acquired the lock. Archived `finishedAt` and `updatedAt` are the application time taken before any wait. - Lock waits have no deadline. A cancellation can wait for in-flight step creations, other terminators, recovery and claims (including claims holding candidate rows they did not select). `completeJob` and `failJob` can wait for step creations, cancellation and recovery. A step creation can wait for terminators and recovery. Step creations can keep overtaking a waiting cancellation, completion or failure, so a busy job can delay them. `client.stop()` observes such waits within its shutdown budgets but does not cut them short; an unfinished wait is reported as an incomplete drain. - Recovery's own step handling, including steps created while recovery runs, is described in [Recovery and concurrent steps](#recovery-and-concurrent-steps). -- This is storage behavior only. `client.cancelJob()` aborts a job that this Client is running in memory; otherwise it cancels in the database. A database cancellation does not stop a handler that is already running elsewhere, and a job this Client has claimed but not yet started (still being fetched or queued) also takes the database path: its handler can still start and then fail when step creation returns `null`. Either handler continues until a step write returns "not active". Local handling of claimed-but-not-started jobs is separate follow-up work. +- This is storage behavior only. `client.cancelJob()` aborts a job that this Client is running in memory; otherwise it cancels in the database. A database cancellation does not stop a handler that is already running elsewhere: it continues until a step write returns "not active". A job this Client has claimed but not yet started (claim reply pending or queued locally) never starts its handler once a `cancelJob()` call is admitted on this same Client; see [`cancelJob`](/docs/client-api#canceljobjobid). Cancellations made through another Client or directly on the adapter do not suppress this Client's claimed or queued jobs. - PGLite runs one statement at a time; it shows the same sequential results, not concurrent locking behavior. ## Job Recovery diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index 5f8a85e..19c3c4b 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -6,6 +6,7 @@ import { ActionJob } from './action-job.js' import type { Action } from './action.js' import type { Adapter, Job } from './adapters/adapter.js' import { lifecycleFor } from './lifecycle.js' +import type { LocalCancellation } from './local-cancellation.js' export interface QueuedJob { /** Execution outcome, as before: rejects when execution throws. */ @@ -26,6 +27,8 @@ export interface ActionManagerOptions> { variables: Record logger: Logger concurrencyLimit: number + /** The owning Client's local cancellation state (queued-window suppression). */ + cancellation: LocalCancellation } /** @@ -43,6 +46,7 @@ export class ActionManager> { #queue: fastq.queueAsPromised #unstarted = new Set() #concurrencyLimit: number + #cancellation: LocalCancellation #activeJobs = new Map>() #stopped: boolean = false @@ -62,24 +66,23 @@ export class ActionManager> { this.#variables = options.variables this.#logger = options.logger this.#concurrencyLimit = options.concurrencyLimit + this.#cancellation = options.cancellation // Create fastq queue with action concurrency limit this.#queue = fastq.promise(async (entry: QueueEntry) => { this.#unstarted.delete(entry) - if (this.#stopped || !lifecycleFor(this.#database).accepting) { - entry.settle(Promise.resolve()) - return - } - - let actionJob: ActionJob | undefined + let settlement: (() => Promise) | undefined try { + if (this.#stopped || !lifecycleFor(this.#database).accepting) return await lifecycleFor(this.#database).run(() => - this.#executeJob(entry.job, (created) => { - actionJob = created + this.#executeJob(entry.job, (settled) => { + settlement = settled }), ) } finally { - entry.settle(actionJob?.settled() ?? Promise.resolve()) + // Dequeued without reaching #executeJob (early return or rejected admission): release + // its queued state and any cancellation flag; settle once their writes settle. + entry.settle(settlement?.() ?? this.#cancellation.consumeQueued(entry.job.id)) } }, this.#concurrencyLimit) } @@ -162,8 +165,11 @@ export class ActionManager> { this.#stopped = true this.abortAll() const drained = this.#queue.killAndDrain() - // Killed queue entries never start a handler; their local accounting settles now. - for (const entry of this.#unstarted) entry.settle(Promise.resolve()) + // Killed queue entries never start a handler; their local accounting settles now, or once + // the cancellation writes of a suppressed entry settle. Killed push promises never settle. + for (const entry of this.#unstarted) { + entry.settle(this.#cancellation.consumeQueued(entry.job.id)) + } this.#unstarted.clear() await drained await Promise.all( @@ -180,7 +186,15 @@ export class ActionManager> { * * @param job - The job to execute */ - async #executeJob(job: Job, created: (actionJob: ActionJob) => void) { + async #executeJob(job: Job, track: (settled: () => Promise) => void) { + // Same synchronous segment as #activeJobs.set: a cancelled queued entry is suppressed here, + // without an ActionJob or another cancellation write. + const suppressed = this.#cancellation.startQueued(job.id) + if (suppressed) { + track(() => suppressed) + return + } + // Create ActionJob for this job const actionJob = new ActionJob({ job: { @@ -197,7 +211,7 @@ export class ActionManager> { logger: this.#logger, }) this.#activeJobs.set(job.id, actionJob) - created(actionJob) + track(() => actionJob.settled()) try { // Execute the job - all error handling is done inside ActionJob.execute() diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index b4e6619..59dbfaf 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -28,9 +28,10 @@ import type { import type { JobStatusResult, JobStepStatusResult } from './adapters/schemas.js' import { JOB_STATUS_CANCELLED, JOB_STATUS_FAILED, type JobStatus } from './constants.js' import { type Lifecycle, lifecycleFor } from './lifecycle.js' +import { type FetchToken, LocalCancellation } from './local-cancellation.js' import { validateSchema } from './standard-schema.js' import { WaitManager } from './wait-manager.js' -import { WorkerDiscovery } from './worker-discovery.js' +import { type ClaimedBatch, WorkerDiscovery } from './worker-discovery.js' /** * Extracts the inferred type from an action's input/output schema. @@ -371,6 +372,7 @@ export class Client< #stopping: Promise | null = null #heartbeatTimer: NodeJS.Timeout | null = null #discovery: WorkerDiscovery | null = null + #cancellation: LocalCancellation #actionManagers = new Map>>() #mockInputSchemas = new Map() #waits: WaitManager @@ -401,6 +403,7 @@ export class Client< this.#logger = this.#normalizeLogger(options?.logger) this.#database.setId(this.#id) this.#database.setLogger(this.#logger) + this.#cancellation = new LocalCancellation(this) if (this.#actions) { const actions = this.#actions this.#discovery = new WorkerDiscovery({ @@ -416,8 +419,7 @@ export class Client< checksums: Object.values(actions).map((action) => action.checksum), staleTimeoutMs: this.#options.heartbeatTimeout, }), - claim: (batch) => this.#database.fetch({ batch }), - dispatch: (job) => this.#executeJob(job), + claim: (batch) => this.#claim(batch), }) } this.#waits = new WaitManager( @@ -760,11 +762,19 @@ export class Client< /** * Cancel a job by its ID. - * If the job is currently being processed, it will be cancelled immediately. - * Otherwise, it will be cancelled in the database. + * + * - Running on this Client (handler started, including its finalization): aborts it in memory + * and returns `true`; the job writes its own cancellation when it settles. + * - Otherwise: issues this call's own `Adapter.cancelJob` and returns `false`, even when the + * database cancellation succeeds. Its rejection propagates to this caller only. + * + * A job this Client has claimed but not started (claim reply pending, or queued behind + * `actionConcurrencyLimit`) never starts its handler once such a call is admitted, even if the + * write is rejected; nothing retries or replays it, and the job can later be recovered. Jobs + * running on another Client keep running until their next write finds the job inactive. * * @param jobId - The ID of the job to cancel - * @returns Promise resolving to `true` if cancelled, `false` otherwise + * @returns Promise resolving to `true` if running here and aborted, `false` otherwise */ async cancelJob(jobId: string) { return this.#lifecycle.run(async () => { @@ -779,12 +789,16 @@ export class Client< } } - if (!cancelled) { - // If the job is not being processed, cancel it in the database + if (cancelled) return true + + // Not running: register the intent synchronously, before this call's own write. + const settle = this.#cancellation.beginCancel(jobId) + try { await this.#database.cancelJob({ jobId }) + } finally { + settle() } - - return cancelled + return false }) } @@ -1180,7 +1194,14 @@ export class Client< * @param job - The job to execute * @returns Actual local settlement (queued, running and finalizing work). Never rejects. */ - #executeJob(job: Job): Promise { + #executeJob(job: Job, token: FetchToken): Promise { + // Cancelled while this claim's reply was pending: suppress only, never write again. + const suppressed = this.#cancellation.suppressClaim(job.id, token) + if (suppressed) { + this.#logger.debug({ jobId: job.id }, `[Duron] Cancelled job ${job.id} not dispatched`) + return suppressed + } + if (!this.#actions || !this.#lifecycle.accepting) { return Promise.resolve() } @@ -1218,11 +1239,13 @@ export class Client< variables: this.#variables, logger: this.#logger, concurrencyLimit: this.#options.actionConcurrencyLimit, + cancellation: this.#cancellation, }) this.#actionManagers.set(action.name, actionManager) } - // Queue job execution + // Queue job execution; fastq may start the worker synchronously inside push. + this.#cancellation.markQueued(job.id) const queued = actionManager.push(job) queued.done.catch((err) => { // Only log unexpected errors (not cancellation/timeout which are handled elsewhere) @@ -1234,6 +1257,26 @@ export class Client< return queued.settled } + /** + * Issue one Adapter.fetch, bound to its own token from immediately before the call until its + * returned jobs were dispatched or dropped (or the call rejected). + */ + async #claim(batch: number): Promise { + const token = this.#cancellation.issueFetch() + let jobs: Job[] + try { + jobs = await this.#database.fetch({ batch }) + } catch (error) { + this.#cancellation.releaseFetch(token) + throw error + } + return { + jobs, + dispatch: (job) => this.#executeJob(job, token), + release: () => this.#cancellation.releaseFetch(token), + } + } + /** * Schedule the next heartbeat. Uses recursive setTimeout (not setInterval) * to avoid overlapping calls if a heartbeat is slow. diff --git a/packages/duron/src/local-cancellation.ts b/packages/duron/src/local-cancellation.ts new file mode 100644 index 0000000..9e5b857 --- /dev/null +++ b/packages/duron/src/local-cancellation.ts @@ -0,0 +1,174 @@ +/** One actual Client-originated Adapter.fetch call. Never persisted. */ +export type FetchToken = symbol + +interface Intent { + /** Admitted explicit cancelJob calls whose own Adapter call has not settled yet. */ + pendingWrites: number + /** Issued fetches that may return this job: suppress its claim if one of them does. */ + overlapping: Set + /** A queued entry for this job must not start its handler when dequeued. */ + queuedItemPending: boolean + /** Resolves when pendingWrites next reaches zero. */ + idle: PromiseWithResolvers | null +} + +export interface LocalCancellationSnapshot { + issuedFetches: number + queued: string[] + intents: Array<{ + jobId: string + pendingWrites: number + overlapping: number + queuedItemPending: boolean + }> +} + +const registries = new WeakMap() + +/** + * Test-only read of a Client's local cancellation state. Internal: not exported by the + * package and not part of any public type. + */ +export function inspectLocalCancellation(client: object): LocalCancellationSnapshot | undefined { + return registries.get(client)?.snapshot() +} + +/** + * Client-local cancellation of claimed jobs whose handler has not started (internal). + * + * Covers two local windows of this Client only: + * - claim-reply pending: an issued Adapter.fetch whose returned jobs are not yet dispatched; + * - queued/deferred: a job pushed to an ActionManager queue that has not created its ActionJob. + * + * Every admitted non-running cancelJob call registers an intent synchronously, before its own + * Adapter call, and reseeds the intent with every currently issued fetch. Calls share only the + * resulting suppression; each keeps its own Adapter call and result. Dispatch suppresses: it never + * writes a cancellation itself. Intents add no ledger units; a suppressed claim keeps its existing + * unit until the cancellation writes it overlaps have settled. No coordinator is involved, so + * cancellation never waits for worker discovery or recovery. + */ +export class LocalCancellation { + #issued = new Set() + #queued = new Set() + #intents = new Map() + + constructor(owner: object) { + registries.set(owner, this) + } + + /** Call synchronously immediately before each Client-originated Adapter.fetch. */ + issueFetch(): FetchToken { + const token = Symbol('fetch') + this.#issued.add(token) + // A fetch issued while a cancellation write is pending may return that job. + for (const intent of this.#intents.values()) { + if (intent.pendingWrites > 0) intent.overlapping.add(token) + } + return token + } + + /** Call once the fetch rejected, or after every returned job was dispatched or dropped. */ + releaseFetch(token: FetchToken): void { + this.#issued.delete(token) + for (const [jobId, intent] of this.#intents) { + if (intent.overlapping.delete(token)) this.#release(jobId, intent) + } + } + + /** + * Register one admitted explicit cancellation of a non-running job. Call synchronously before + * its Adapter call; call the returned function once that call settles. + */ + beginCancel(jobId: string): () => void { + let intent = this.#intents.get(jobId) + if (!intent) { + intent = { pendingWrites: 0, overlapping: new Set(), queuedItemPending: false, idle: null } + this.#intents.set(jobId, intent) + } + intent.pendingWrites++ + for (const token of this.#issued) intent.overlapping.add(token) + if (this.#queued.has(jobId)) intent.queuedItemPending = true + const registered = intent + let settled = false + return () => { + if (settled) return + settled = true + registered.pendingWrites-- + if (registered.pendingWrites === 0) { + registered.idle?.resolve() + registered.idle = null + } + this.#release(jobId, registered) + } + } + + /** + * Claim dispatch: null when the job may be queued. Otherwise the claim is suppressed and the + * result is its local settlement (the overlapping cancellation writes settling). + */ + suppressClaim(jobId: string, token: FetchToken): Promise | null { + const intent = this.#intents.get(jobId) + if (!intent?.overlapping.has(token)) return null + return this.#writesIdle(intent) + } + + /** Call immediately before pushing the job to its ActionManager queue. */ + markQueued(jobId: string): void { + this.#queued.add(jobId) + } + + /** + * Dequeued entry about to create its ActionJob (same synchronous segment). Null when it may + * run; otherwise it is suppressed and the result is its local settlement. + */ + startQueued(jobId: string): Promise | null { + this.#queued.delete(jobId) + const intent = this.#intents.get(jobId) + if (!intent?.queuedItemPending) return null + return this.#consume(jobId, intent) + } + + /** A queued entry left without starting (early return, rejected admission or kill). */ + consumeQueued(jobId: string): Promise { + if (!this.#queued.delete(jobId)) return Promise.resolve() + const intent = this.#intents.get(jobId) + return intent ? this.#consume(jobId, intent) : Promise.resolve() + } + + snapshot(): LocalCancellationSnapshot { + return { + issuedFetches: this.#issued.size, + queued: [...this.#queued], + intents: [...this.#intents].map(([jobId, intent]) => ({ + jobId, + pendingWrites: intent.pendingWrites, + overlapping: intent.overlapping.size, + queuedItemPending: intent.queuedItemPending, + })), + } + } + + #consume(jobId: string, intent: Intent): Promise { + intent.queuedItemPending = false + const idle = this.#writesIdle(intent) + this.#release(jobId, intent) + return idle + } + + #writesIdle(intent: Intent): Promise { + if (intent.pendingWrites === 0) return Promise.resolve() + intent.idle ??= Promise.withResolvers() + return intent.idle.promise + } + + #release(jobId: string, intent: Intent): void { + if ( + intent.pendingWrites === 0 && + intent.overlapping.size === 0 && + !intent.queuedItemPending && + this.#intents.get(jobId) === intent + ) { + this.#intents.delete(jobId) + } + } +} diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index a9fe89c..f61ec86 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -20,6 +20,15 @@ interface ManualRequest { type DiscoveryRequest = AutomaticRequest | ManualRequest +/** One actual Adapter.fetch result, bound to that call by the claim function. */ +export interface ClaimedBatch { + jobs: Job[] + /** Queue a claimed job locally; resolves (never rejects) at its actual local settlement. */ + dispatch: (job: Job) => Promise + /** Called once every returned job was dispatched or dropped after the gate. */ + release: () => void +} + export interface WorkerDiscoveryOptions { lifecycle: Lifecycle logger: Logger @@ -29,9 +38,8 @@ export interface WorkerDiscoveryOptions { batchSize: number recoverJobsInterval: number recover: () => Promise - claim: (batch: number) => Promise - /** Queue a claimed job locally; resolves (never rejects) at its actual local settlement. */ - dispatch: (job: Job) => Promise + /** Issue one Adapter.fetch; a rejection releases its own call-bound state. */ + claim: (batch: number) => Promise } /** Worker cadence: floor/clamp positive finite values to 1–2,147,483,647 ms; otherwise 5000. */ @@ -241,14 +249,18 @@ export class WorkerDiscovery { this.#reserved += reserved } this.#options.lifecycle.assertContinuation() - const jobs = await this.#options.claim(batch) + const claimed = await this.#options.claim(batch) // Transfer the reservation into local accounting without a gap or double count. this.#reserved -= reserved reserved = 0 - if (!this.#stopped && this.#options.lifecycle.accepting) { - for (const job of jobs) this.#track(this.#options.dispatch(job)) + try { + if (!this.#stopped && this.#options.lifecycle.accepting) { + for (const job of claimed.jobs) this.#track(claimed.dispatch(job)) + } + } finally { + claimed.release() } - if (request.kind === 'manual') request.resolve(jobs) + if (request.kind === 'manual') request.resolve(claimed.jobs) } catch (error) { this.#cooldownUntil = monotonicMs() + this.#interval if (request.kind === 'manual') { diff --git a/packages/duron/test/local-cancellation-registry.test.ts b/packages/duron/test/local-cancellation-registry.test.ts new file mode 100644 index 0000000..c7ed6ef --- /dev/null +++ b/packages/duron/test/local-cancellation-registry.test.ts @@ -0,0 +1,183 @@ +import { describe, expect, it } from 'bun:test' + +import pino from 'pino' + +import { ActionManager } from '../src/action-manager.js' +import { defineAction } from '../src/action.js' +import * as packageRoot from '../src/index.js' +import { lifecycleFor } from '../src/lifecycle.js' +import { inspectLocalCancellation, LocalCancellation } from '../src/local-cancellation.js' + +import { pgliteFactory } from './adapters.js' + +// Internal seams for issue 12b, labelled "internal": direct use of the non-exported +// LocalCancellation registry and of the internal ActionManager. Public outcomes for the same +// behaviour live in local-cancellation.test.ts; these cover paths the public Client cannot reach +// deterministically (single discovery chain, worker early return after the gate). + +async function settledWithin(promise: Promise, ms = 20): Promise { + let settled = false + void promise.then(() => (settled = true)) + await Bun.sleep(ms) + return settled +} + +describe('LocalCancellation registry (internal)', () => { + it('removes a fetch token from issued fetches and every intent, then releases them', () => { + const owner = {} + const registry = new LocalCancellation(owner) + const token = registry.issueFetch() + const settleA = registry.beginCancel('a') + const settleB = registry.beginCancel('b') + settleA() + settleB() + expect(inspectLocalCancellation(owner)?.intents).toEqual([ + { jobId: 'a', pendingWrites: 0, overlapping: 1, queuedItemPending: false }, + { jobId: 'b', pendingWrites: 0, overlapping: 1, queuedItemPending: false }, + ]) + expect(registry.suppressClaim('a', token)).not.toBeNull() + registry.releaseFetch(token) + expect(inspectLocalCancellation(owner)).toEqual({ issuedFetches: 0, queued: [], intents: [] }) + }) + + it('E3d: a later call on a retained intent reseeds fetches issued after earlier writes settled', () => { + const registry = new LocalCancellation({}) + registry.markQueued('j') + registry.beginCancel('j')() + // Retained by the queued item; a fetch issued now does not join (no write pending). + const late = registry.issueFetch() + expect(registry.suppressClaim('j', late)).toBeNull() + const settle = registry.beginCancel('j') + expect(registry.suppressClaim('j', late)).not.toBeNull() + settle() + registry.releaseFetch(late) + expect(registry.snapshot().intents).toEqual([ + { jobId: 'j', pendingWrites: 0, overlapping: 0, queuedItemPending: true }, + ]) + expect(registry.startQueued('j')).not.toBeNull() + expect(registry.snapshot()).toEqual({ issuedFetches: 0, queued: [], intents: [] }) + }) + + it('a fetch issued while a write is pending joins that intent only', () => { + const registry = new LocalCancellation({}) + const settle = registry.beginCancel('pending') + registry.beginCancel('settled')() + const token = registry.issueFetch() + expect(registry.suppressClaim('pending', token)).not.toBeNull() + expect(registry.suppressClaim('settled', token)).toBeNull() + expect(registry.suppressClaim('other', token)).toBeNull() + settle() + registry.releaseFetch(token) + expect(registry.snapshot().intents).toEqual([]) + }) + + it('a suppressed claim settles only when every overlapping write settled; settle is idempotent', async () => { + const registry = new LocalCancellation({}) + const token = registry.issueFetch() + const first = registry.beginCancel('j') + const second = registry.beginCancel('j') + const suppressed = registry.suppressClaim('j', token)! + first() + first() + expect(registry.snapshot().intents[0]?.pendingWrites).toBe(1) + expect(await settledWithin(suppressed)).toBe(false) + second() + expect(await settledWithin(suppressed)).toBe(true) + registry.releaseFetch(token) + expect(registry.snapshot().intents).toEqual([]) + }) + + it('queued consumption releases state once; a started entry is not consumed again', async () => { + const registry = new LocalCancellation({}) + registry.markQueued('run') + expect(registry.startQueued('run')).toBeNull() + expect(await registry.consumeQueued('run')).toBeUndefined() + registry.markQueued('killed') + const settle = registry.beginCancel('killed') + const consumed = registry.consumeQueued('killed') + expect(registry.snapshot().intents).toEqual([ + { jobId: 'killed', pendingWrites: 1, overlapping: 0, queuedItemPending: false }, + ]) + expect(await settledWithin(consumed)).toBe(false) + settle() + await consumed + expect(registry.snapshot()).toEqual({ issuedFetches: 0, queued: [], intents: [] }) + }) + + it('the inspection read is not part of the package root or a public Client member', () => { + expect('inspectLocalCancellation' in packageRoot).toBe(false) + expect('LocalCancellation' in packageRoot).toBe(false) + expect(inspectLocalCancellation({})).toBeUndefined() + }) +}) + +describe('ActionManager queued-window consumption (internal, real PGLite adapter)', () => { + it('E2d: an entry dequeued after the lifecycle gate releases its state and starts nothing', async () => { + const instance = await pgliteFactory.create() + try { + let started = 0 + const action = defineAction()({ + name: 'gated', + handler: async () => { + started++ + return {} + }, + }) + const adapter = instance.adapter + adapter.setId('internal-e2d') + expect(await adapter.start()).toBe(true) + const jobId = (await adapter.createJob({ + queue: action.name, + groupKey: '@default', + input: {}, + timeoutMs: 60_000, + checksum: action.checksum, + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }))! + const [job] = await adapter.fetch({ batch: 1 }) + expect(job!.id).toBe(jobId) + + const owner = {} + const cancellation = new LocalCancellation(owner) + const manager = new ActionManager({ + action, + database: adapter, + tracer: { startSpan: () => ({}) } as any, + variables: {}, + logger: pino({ level: 'silent' }), + concurrencyLimit: 1, + cancellation, + }) + // Close the lifecycle gate without stopping this manager (no Client quiesce hook). + lifecycleFor(adapter).quiesce() + expect(lifecycleFor(adapter).accepting).toBe(false) + + cancellation.markQueued(jobId) + const settle = cancellation.beginCancel(jobId) + // fastq invokes the worker synchronously; it returns early because the gate is closed. + const queued = manager.push(job!) + await Bun.sleep(10) + expect(inspectLocalCancellation(owner)).toEqual({ + issuedFetches: 0, + queued: [], + intents: [{ jobId, pendingWrites: 1, overlapping: 0, queuedItemPending: false }], + }) + // The entry keeps its one local settlement until the overlapping write settles. + expect(await settledWithin(queued.settled)).toBe(false) + settle() + await queued.settled + await queued.done + expect(inspectLocalCancellation(owner)).toEqual({ + issuedFetches: 0, + queued: [], + intents: [], + }) + expect(started).toBe(0) + } finally { + await instance.adapter.stop().catch(() => undefined) + await instance.deleteDb() + } + }) +}) diff --git a/packages/duron/test/local-cancellation.test.ts b/packages/duron/test/local-cancellation.test.ts new file mode 100644 index 0000000..ef4e475 --- /dev/null +++ b/packages/duron/test/local-cancellation.test.ts @@ -0,0 +1,1374 @@ +import { describe, expect, it } from 'bun:test' + +import pino from 'pino' + +import { defineAction } from '../src/action.js' +import type { Adapter, Job } from '../src/adapters/adapter.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' +import { + inspectLocalCancellation, + type LocalCancellationSnapshot, +} from '../src/local-cancellation.js' + +import { + type AdapterFactory, + type AdapterInstance, + pgliteFactory, + postgresFactory, +} from './adapters.js' + +// Local undispatched cancellation (issue 12b). Public Client outcomes are decisive. Control +// classes, labelled per test: +// - public-only: public Client/Adapter calls and public reads; held handler gates. +// - held: an instance-level pass-through wrapper on a public Adapter method (fetch/cancelJob/ +// recoverJobs) that pauses before or after the real call. Override dispatch is preserved. +// - fault-injected: a wrapper rejects before the real call (rejected) or after the real call +// committed (uncertain). +// - direct: a public Adapter call outside the Client (another Client's claim or cancellation). +// - inspected: the internal, non-exported inspectLocalCancellation() read, always alongside +// public outcomes. + +const OBSERVE_MS = 2_000 +const TEST_MS = 30_000 + +async function eventually(check: () => boolean | Promise, message: string) { + const end = performance.now() + OBSERVE_MS + while (!(await check())) { + if (performance.now() >= end) throw new Error(`Bounded observation exceeded: ${message}`) + await Bun.sleep(5) + } +} + +async function status(adapter: Adapter, jobId: string) { + return (await adapter.getJobById(jobId))?.status +} + +const QUIESCENT = { issuedFetches: 0, queued: [], intents: [] } + +// Old-code controls set LOCAL_CANCELLATION_PUBLIC_ONLY=true so the internal inspection (absent +// on Base) does not mask the public outcome that decides red/green. +const PUBLIC_ONLY = process.env['LOCAL_CANCELLATION_PUBLIC_ONLY'] === 'true' + +function expectState(client: Client, expected: unknown, part?: 'intents') { + if (PUBLIC_ONLY) return + const snapshot = inspectLocalCancellation(client) + expect(part ? snapshot?.[part] : snapshot).toEqual(expected as any) +} + +/** Bounded wait for an internal state; public-only controls wait a fixed 100 ms instead. */ +async function stateReached( + client: Client, + check: (snapshot: LocalCancellationSnapshot | undefined) => boolean, + message: string, +) { + if (PUBLIC_ONLY) return Bun.sleep(100) + await eventually(() => check(inspectLocalCancellation(client)), message) +} + +type Mode = 'quick' | 'hold' | 'ignore-abort' | 'step' | 'step-after-gate' | 'nested-cancel' +// 'ignore-abort' names the intent in finalization tests; both held modes ignore the abort. +type Input = { mode?: Mode; target?: string } + +// Held: pass-through wrapper on public Adapter.fetch. The real claim runs (and commits) first; +// a reply containing `jobId` is then held until released. +function holdReplyFor(adapter: Adapter, jobId: () => string | null) { + const real = adapter.fetch.bind(adapter) + const reached = Promise.withResolvers() + const gate = Promise.withResolvers() + let calls = 0 + adapter.fetch = async (options) => { + calls++ + const jobs = await real(options) + const target = jobId() + if (target && jobs.some((job) => job.id === target)) { + reached.resolve(jobs) + await gate.promise + } + return jobs + } + return { + reached: reached.promise, + release: () => gate.resolve(), + get calls() { + return calls + }, + } +} + +// Held: pass-through wrapper on public Adapter.fetch that pauses before the real claim. +function holdFetchBeforeClaim(adapter: Adapter) { + const real = adapter.fetch.bind(adapter) + const entered = Promise.withResolvers() + const gate = Promise.withResolvers() + adapter.fetch = async (options) => { + entered.resolve() + await gate.promise + return real(options) + } + return { entered: entered.promise, release: () => gate.resolve() } +} + +type CancelBehavior = 'pass' | 'hold' | 'reject' | 'uncertain' +type CancelCall = { + jobId: string + behavior: CancelBehavior + release: () => void + settled: Promise + result?: boolean + error?: unknown +} + +const injected = () => new Error('injected cancellation write failure') + +// Held / fault-injected: pass-through wrapper on public Adapter.cancelJob. Behaviours are taken in +// call order: hold before the real call, reject before it, or reject after it committed. +function controlCancel(adapter: Adapter) { + const real = adapter.cancelJob.bind(adapter) + const calls: CancelCall[] = [] + const plan: CancelBehavior[] = [] + const planned = new Map() + adapter.cancelJob = async (options) => { + const behavior = planned.get(options.jobId)?.shift() ?? plan.shift() ?? 'pass' + const gate = Promise.withResolvers() + const done = Promise.withResolvers() + const call: CancelCall = { + jobId: options.jobId, + behavior, + release: () => gate.resolve(), + settled: done.promise, + } + calls.push(call) + try { + if (behavior === 'hold') await gate.promise + if (behavior === 'reject') throw injected() + call.result = await real(options) + if (behavior === 'uncertain') throw injected() + return call.result + } catch (error) { + call.error = error + throw error + } finally { + done.resolve() + } + } + return { + calls, + plan: (...behaviors: CancelBehavior[]) => plan.push(...behaviors), + planFor: (jobId: string, ...behaviors: CancelBehavior[]) => { + planned.set(jobId, [...(planned.get(jobId) ?? []), ...behaviors]) + }, + for: (jobId: string) => calls.filter((call) => call.jobId === jobId), + releaseAll: () => { + for (const call of calls) call.release() + }, + } +} + +// Held: pass-through wrapper on public Adapter.recoverJobs, paused until released. +function holdRecovery(adapter: Adapter) { + const real = adapter.recoverJobs.bind(adapter) + const entered = Promise.withResolvers() + const gate = Promise.withResolvers() + adapter.recoverJobs = async (options) => { + entered.resolve() + await gate.promise + return real(options) + } + return { entered: entered.promise, release: () => gate.resolve() } +} + +function countCalls(adapter: Adapter, name: 'failJob' | 'completeJob') { + const target = adapter as any + const real = target[name].bind(adapter) + const calls: string[] = [] + target[name] = async (options: { jobId: string }) => { + calls.push(options.jobId) + return real(options) + } + return calls +} + +function captureLogs() { + const entries: Array> = [] + const logger = pino( + { level: 'warn' }, + { write: (line: string) => entries.push(JSON.parse(line)) }, + ) + return { logger, entries } +} + +interface HarnessOptions { + syncPattern?: 'pull' | false + pullInterval?: number + batchSize?: number + actionConcurrencyLimit?: number + recoverJobsInterval?: number + logger?: pino.Logger +} + +interface Harness { + instance: AdapterInstance + adapter: Adapter + client: Client + /** Job IDs whose handler started, in start order. */ + starts: string[] + /** Settled handler outcomes by job ID. */ + outcomes: Map + errors: Map + nested: Map> + /** Job the nested-cancel handler cancels when aborted. */ + nestedTarget: { value: string } + gate(jobId: string): PromiseWithResolvers + run(input?: Input, action?: string): Promise + /** Claim and run a quick sentinel to completion; FIFO-orders it after earlier pushes. */ + sentinel(): Promise + close(): Promise +} + +async function harness(factory: AdapterFactory, options: HarnessOptions = {}): Promise { + const instance = await factory.create() + const starts: string[] = [] + const outcomes = new Map() + const errors = new Map() + const nested = new Map>() + const nestedTarget = { value: '' } + const gates = new Map>() + const gate = (jobId: string) => { + let entry = gates.get(jobId) + if (!entry) { + entry = Promise.withResolvers() + gates.set(jobId, entry) + } + return entry + } + let client: Client | null = null + const handler = async (ctx: any) => { + const input = ctx.input as Input + starts.push(ctx.jobId) + try { + // Held handlers wait for their test gate; tests release gates explicitly (also after a + // stop, whose drain observes the raw handler promise). + switch (input.mode ?? 'quick') { + case 'hold': + case 'ignore-abort': + await gate(ctx.jobId).promise + break + case 'step': + await ctx.step('s1', async () => ({})) + break + case 'step-after-gate': + await gate(ctx.jobId).promise + await ctx.step('s1', async () => ({})) + break + case 'nested-cancel': { + await gate(ctx.jobId).promise + // Continues in the handler's operation context, inside the drain window. + const call = client!.cancelJob(input.target ?? nestedTarget.value) + nested.set(ctx.jobId, call) + await call.catch(() => undefined) + break + } + } + outcomes.set(ctx.jobId, 'fulfilled') + return {} + } catch (error) { + outcomes.set(ctx.jobId, 'rejected') + errors.set(ctx.jobId, error) + throw error + } + } + const work = defineAction()({ name: 'work', handler }) + const short = defineAction()({ name: 'short', expire: 300, handler }) + client = new Client({ + database: instance.adapter, + actions: { work, short }, + syncPattern: options.syncPattern ?? false, + pullInterval: options.pullInterval ?? 60_000, + batchSize: options.batchSize ?? 10, + actionConcurrencyLimit: options.actionConcurrencyLimit ?? 100, + recoverJobsOnStart: false, + recoverJobsInterval: options.recoverJobsInterval ?? 0, + logger: options.logger ?? 'silent', + }) + expect(await client.start()).toBe(true) + const c = client + return { + instance, + adapter: instance.adapter, + client: c, + starts, + outcomes, + errors, + nested, + nestedTarget, + gate, + run: (input = { mode: 'quick' }, action = 'work') => c.runAction(action, input), + async sentinel() { + const id = await c.runAction('work', { mode: 'quick' }) + if (options.syncPattern !== 'pull') { + await eventually(async () => { + if ((await status(instance.adapter, id)) === 'created') await c.fetch() + return (await status(instance.adapter, id)) !== 'created' + }, 'sentinel claimed') + } + await eventually( + async () => (await status(instance.adapter, id)) === 'completed', + 'sentinel completes', + ) + return id + }, + async close() { + for (const entry of gates.values()) entry.resolve() + await c.stop().catch(() => undefined) + await instance.deleteDb() + }, + } +} + +/** A held handler occupying the only action slot (actionConcurrencyLimit: 1). */ +async function occupySlot(h: Harness): Promise { + const blocker = await h.run({ mode: 'hold' }) + expect((await h.client.fetch()).map((job) => job.id)).toEqual([blocker]) + await eventually(() => h.starts.includes(blocker), 'blocker handler started') + return blocker +} + +const factories: AdapterFactory[] = [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +] + +for (const factory of factories) { + describe(`Local undispatched cancellation with ${factory.name}`, () => { + // ------------------------------------------------------------------------ + // Claim-reply-pending window + // ------------------------------------------------------------------------ + + it( + 'E3a: reply released after cancelJob returned never starts the handler (held, inspected)', + async () => { + const h = await harness(factory) + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const cancels = controlCancel(h.adapter) + target = await h.run() + const fetching = h.client.fetch() + await reply.reached + expect(await status(h.adapter, target)).toBe('active') + + expect(await h.client.cancelJob(target)).toBe(false) + expect(await status(h.adapter, target)).toBe('cancelled') + expect(cancels.for(target).map((call) => call.result)).toEqual([true]) + // The settled call still leaves suppression with the pending reply's token. + expectState( + h.client, + [{ jobId: target, pendingWrites: 0, overlapping: 1, queuedItemPending: false }], + 'intents', + ) + + reply.release() + // Manual fetch keeps returning its actual claimed jobs, including the suppressed one. + expect((await fetching).map((job) => job.id)).toEqual([target]) + // Released after the fetch's token was removed. + expectState(h.client, QUIESCENT) + + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('cancelled') + expect(cancels.for(target)).toHaveLength(1) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E3c: a fetch issued while the cancellation write is pending is suppressed (held, inspected)', + async () => { + const h = await harness(factory) + try { + const cancels = controlCancel(h.adapter) + const target = await h.run() + cancels.plan('hold') + const cancelling = h.client.cancelJob(target) + await eventually(() => cancels.for(target).length === 1, 'cancel write entered') + + // The claim commits and replies while the write has not been issued yet. + expect((await h.client.fetch()).map((job) => job.id)).toEqual([target]) + expect(await status(h.adapter, target)).toBe('active') + expectState( + h.client, + [{ jobId: target, pendingWrites: 1, overlapping: 0, queuedItemPending: false }], + 'intents', + ) + + cancels.releaseAll() + expect(await cancelling).toBe(false) + expect(cancels.for(target)[0]!.result).toBe(true) + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('cancelled') + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E3d: a later call on a retained intent reseeds issued fetches and adds its own write (held, fault-injected, inspected)', + async () => { + const h = await harness(factory) + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const cancels = controlCancel(h.adapter) + target = await h.run() + const fetching = h.client.fetch() + await reply.reached + + cancels.plan('reject') + await expect(h.client.cancelJob(target)).rejects.toThrow( + 'injected cancellation write failure', + ) + // Retained by the pending reply's token after its write rejected. + expectState( + h.client, + [{ jobId: target, pendingWrites: 0, overlapping: 1, queuedItemPending: false }], + 'intents', + ) + expect(await status(h.adapter, target)).toBe('active') + + cancels.plan('hold') + const second = h.client.cancelJob(target) + await eventually(() => cancels.for(target).length === 2, 'second write entered') + expectState( + h.client, + [{ jobId: target, pendingWrites: 1, overlapping: 1, queuedItemPending: false }], + 'intents', + ) + + reply.release() + expect((await fetching).map((job) => job.id)).toEqual([target]) + cancels.releaseAll() + expect(await second).toBe(false) + expect(cancels.for(target).map((call) => call.result)).toEqual([undefined, true]) + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('cancelled') + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E4: two explicit calls keep two Adapter dispatches and their own results; suppression is shared (held, fault-injected)', + async () => { + const h = await harness(factory) + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const cancels = controlCancel(h.adapter) + target = await h.run() + const fetching = h.client.fetch() + await reply.reached + + cancels.plan('hold', 'hold') + const first = h.client.cancelJob(target) + const second = h.client.cancelJob(target) + await eventually(() => cancels.for(target).length === 2, 'both writes entered') + reply.release() + await fetching + + cancels.calls[0]!.release() + expect(await first).toBe(false) + expectState( + h.client, + [{ jobId: target, pendingWrites: 1, overlapping: 0, queuedItemPending: false }], + 'intents', + ) + cancels.calls[1]!.release() + expect(await second).toBe(false) + // Each call reached the Adapter with its own result: the loser finds nothing to cancel. + expect(cancels.for(target).map((call) => call.result)).toEqual([true, false]) + + await h.sentinel() + expect(h.starts).not.toContain(target) + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E4: a per-call rejection reaches only its own caller (held, fault-injected)', + async () => { + const h = await harness(factory) + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const cancels = controlCancel(h.adapter) + target = await h.run() + const fetching = h.client.fetch() + await reply.reached + + cancels.plan('hold', 'reject') + const first = h.client.cancelJob(target) + const second = h.client.cancelJob(target) + await expect(second).rejects.toThrow('injected cancellation write failure') + reply.release() + await fetching + cancels.releaseAll() + expect(await first).toBe(false) + expect(cancels.for(target)).toHaveLength(2) + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('cancelled') + } finally { + await h.close() + } + }, + TEST_MS, + ) + + // ------------------------------------------------------------------------ + // Rejected / uncertain writes (E5) + // ------------------------------------------------------------------------ + + it( + 'E5: a rejected write suppresses without replay; recovery later requeues the unexpired job (fault-injected, direct recovery)', + async () => { + const h = await harness(factory) + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const cancels = controlCancel(h.adapter) + const fails = countCalls(h.adapter, 'failJob') + target = await h.run() + const fetching = h.client.fetch() + await reply.reached + + cancels.plan('reject') + await expect(h.client.cancelJob(target)).rejects.toThrow( + 'injected cancellation write failure', + ) + reply.release() + await fetching + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('active') + expectState(h.client, QUIESCENT) + // No replay or compensating mutation. + expect(cancels.for(target)).toHaveLength(1) + expect(fails).not.toContain(target) + + // Direct: this Client's own recovery requeues its remaining unexpired active job. + await h.adapter.recoverJobs({ + checksums: [h.client.getConfig().actions!['work'].checksum], + staleTimeoutMs: 15_000, + }) + expect(await status(h.adapter, target)).toBe('created') + // A later claim is not suppressed: the job may run again. + expect((await h.client.fetch()).map((job) => job.id)).toEqual([target]) + await eventually( + async () => (await status(h.adapter, target!)) === 'completed', + 'requeued job runs', + ) + expect(h.starts).toContain(target) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E5: an uncertain write (committed, then rejected) still suppresses (fault-injected)', + async () => { + const h = await harness(factory) + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const cancels = controlCancel(h.adapter) + target = await h.run() + const fetching = h.client.fetch() + await reply.reached + cancels.plan('uncertain') + await expect(h.client.cancelJob(target)).rejects.toThrow( + 'injected cancellation write failure', + ) + expect(cancels.for(target)[0]!.result).toBe(true) + reply.release() + await fetching + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('cancelled') + expect(cancels.for(target)).toHaveLength(1) + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E5: after a rejected write an expired job is archived failed by recovery (fault-injected, direct recovery)', + async () => { + const h = await harness(factory) + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const cancels = controlCancel(h.adapter) + target = await h.run({ mode: 'quick' }, 'short') + const fetching = h.client.fetch() + await reply.reached + cancels.plan('reject') + await expect(h.client.cancelJob(target)).rejects.toThrow() + reply.release() + await fetching + await h.sentinel() + expect(h.starts).not.toContain(target) + await Bun.sleep(400) + await h.adapter.recoverJobs({ + checksums: [h.client.getConfig().actions!['short'].checksum], + staleTimeoutMs: 15_000, + }) + expect(await status(h.adapter, target)).toBe('failed') + expect(cancels.for(target)).toHaveLength(1) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + // ------------------------------------------------------------------------ + // Queued window + // ------------------------------------------------------------------------ + + it( + 'E2a: a queued job cancelled while its write is pending at dequeue never starts (held, inspected)', + async () => { + const h = await harness(factory, { actionConcurrencyLimit: 1 }) + try { + const cancels = controlCancel(h.adapter) + const blocker = await occupySlot(h) + const target = await h.run() + expect((await h.client.fetch()).map((job) => job.id)).toEqual([target]) + + cancels.plan('hold') + const cancelling = h.client.cancelJob(target) + await eventually(() => cancels.for(target).length === 1, 'write entered') + expectState( + h.client, + [{ jobId: target, pendingWrites: 1, overlapping: 0, queuedItemPending: true }], + 'intents', + ) + + h.gate(blocker).resolve() + await stateReached( + h.client, + (state) => state?.intents[0]?.queuedItemPending === false, + 'queued item consumed', + ) + cancels.releaseAll() + expect(await cancelling).toBe(false) + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('cancelled') + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E2b: a queued job whose write settled before dequeue never starts (public-only, inspected)', + async () => { + const h = await harness(factory, { actionConcurrencyLimit: 1 }) + try { + const blocker = await occupySlot(h) + const target = await h.run() + expect((await h.client.fetch()).map((job) => job.id)).toEqual([target]) + expect(await h.client.cancelJob(target)).toBe(false) + expect(await status(h.adapter, target)).toBe('cancelled') + expectState( + h.client, + [{ jobId: target, pendingWrites: 0, overlapping: 0, queuedItemPending: true }], + 'intents', + ) + + h.gate(blocker).resolve() + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('cancelled') + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E2c: stop kills queued work without compensating writes and observes the pending write (held, inspected)', + async () => { + const h = await harness(factory, { actionConcurrencyLimit: 1 }) + try { + const cancels = controlCancel(h.adapter) + const fails = countCalls(h.adapter, 'failJob') + const blocker = await occupySlot(h) + const target = await h.run() + const other = await h.run() + expect((await h.client.fetch()).map((job) => job.id).toSorted()).toEqual( + [target, other].toSorted(), + ) + cancels.plan('hold') + const cancelling = h.client.cancelJob(target) + await eventually(() => cancels.for(target).length === 1, 'write entered') + + expect(await status(h.adapter, other)).toBe('active') + let stopped = false + const stopping = h.client.stop().then((result) => { + stopped = true + return result + }) + // The aborted blocker's raw handler settles; the pending write still holds the drain. + h.gate(blocker).resolve() + await stateReached( + h.client, + (state) => state?.queued.length === 0, + 'queued state released at kill', + ) + expectState( + h.client, + [{ jobId: target, pendingWrites: 1, overlapping: 0, queuedItemPending: false }], + 'intents', + ) + await Bun.sleep(100) + expect(stopped).toBe(false) + + cancels.for(target)[0]!.release() + expect(await cancelling).toBe(false) + expect(await stopping).toBe(true) + expect(h.starts).toEqual([blocker]) + // The pending write cancelled the killed job; the killed item without an intent was + // left claimed for recovery (no cancel/fail call for it): nothing compensates. + expect(cancels.for(target)[0]!.result).toBe(true) + expect(cancels.calls.map((call) => call.jobId).toSorted()).toEqual( + [blocker, target].toSorted(), + ) + expect(fails).toEqual([]) + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'runActionAndWait timeout cancels a queued job through the local path (public-only, held)', + async () => { + const h = await harness(factory, { actionConcurrencyLimit: 1 }) + try { + const cancels = controlCancel(h.adapter) + const blocker = await occupySlot(h) + const waiting = h.client.runActionAndWait('work', { mode: 'quick' }, { timeout: 500 }) + let target: string | undefined + await eventually(async () => { + target ??= (await h.client.fetch())[0]?.id + return target !== undefined + }, 'waited job claimed behind the blocker') + await expect(waiting).rejects.toThrow('Operation timed out') + await eventually(() => cancels.for(target!).length === 1, 'fire-and-forget cancel') + await cancels.for(target!)[0]!.settled + + h.gate(blocker).resolve() + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target!)).toBe('cancelled') + expect(cancels.for(target!)).toHaveLength(1) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'waitForJob timeout and abort settle only the waiter and never cancel (public-only, held)', + async () => { + const h = await harness(factory) + try { + const cancels = controlCancel(h.adapter) + const target = await h.run() + expect(await h.client.waitForJob(target, { timeout: 50 })).toBeNull() + const controller = new AbortController() + const waiting = h.client.waitForJob(target, { signal: controller.signal }) + controller.abort() + expect(await waiting).toBeNull() + expect(cancels.calls).toEqual([]) + expect(await status(h.adapter, target)).toBe('created') + } finally { + await h.close() + } + }, + TEST_MS, + ) + + // ------------------------------------------------------------------------ + // Ledger, automatic ceiling and coordinator independence + // ------------------------------------------------------------------------ + + it( + 'a suppressed claim keeps exactly one automatic unit until all its writes settle (held, inspected)', + async () => { + const h = await harness(factory, { syncPattern: 'pull', pullInterval: 20, batchSize: 1 }) + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const cancels = controlCancel(h.adapter) + target = await h.run() + await reply.reached + cancels.plan('hold', 'hold') + const first = h.client.cancelJob(target) + await eventually(() => cancels.for(target!).length === 1, 'first write entered') + reply.release() + await stateReached( + h.client, + (state) => state?.issuedFetches === 0, + 'suppressed reply processed', + ) + + const next = await h.run() + const claimsBefore = reply.calls + await Bun.sleep(200) + // Ceiling B=1 is still held by the suppressed claim: no automatic claim is issued. + expect(reply.calls).toBe(claimsBefore) + expect(await status(h.adapter, next)).toBe('created') + + // A later call joins the same suppression without a new unit. + const second = h.client.cancelJob(target) + await eventually(() => cancels.for(target!).length === 2, 'second write entered') + cancels.calls[0]!.release() + expect(await first).toBe(false) + await Bun.sleep(100) + expect(reply.calls).toBe(claimsBefore) + expect(await status(h.adapter, next)).toBe('created') + + cancels.calls[1]!.release() + expect(await second).toBe(false) + await eventually( + async () => (await status(h.adapter, next)) === 'completed', + 'unit released after both writes settled', + ) + expect(h.starts).toEqual([next]) + // Automatic discovery may have its next (empty) fetch in flight: check intents only. + expectState(h.client, [], 'intents') + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E6: an unknown job ID consumes no unit and returns false (held, inspected)', + async () => { + const h = await harness(factory, { syncPattern: 'pull', pullInterval: 20, batchSize: 1 }) + try { + const cancels = controlCancel(h.adapter) + const unknown = globalThis.crypto.randomUUID() + cancels.plan('hold') + const cancelling = h.client.cancelJob(unknown) + await eventually(() => cancels.for(unknown).length === 1, 'write entered') + const next = await h.run() + await eventually( + async () => (await status(h.adapter, next)) === 'completed', + 'automatic claim proceeds while the unknown-ID write is pending', + ) + cancels.releaseAll() + expect(await cancelling).toBe(false) + expect(cancels.for(unknown)[0]!.result).toBe(false) + // Automatic discovery may have its next (empty) fetch in flight: check intents only. + expectState(h.client, [], 'intents') + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E6: a job claimed outside this Client takes the database branch and returns false (direct, inspected)', + async () => { + const h = await harness(factory) + try { + const cancels = controlCancel(h.adapter) + const target = await h.run() + // Direct claim outside the Client coordinator (models another worker's claim). + expect((await h.adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([target]) + expect(await h.client.cancelJob(target)).toBe(false) + expect(cancels.for(target)[0]!.result).toBe(true) + expect(await status(h.adapter, target)).toBe('cancelled') + expect(h.starts).toEqual([]) + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'cancelJob does not wait for a held claim chain (held)', + async () => { + const h = await harness(factory) + try { + const target = await h.run() + const held = holdFetchBeforeClaim(h.adapter) + const fetching = h.client.fetch() + await held.entered + expect(await h.client.cancelJob(target)).toBe(false) + expect(await status(h.adapter, target)).toBe('cancelled') + held.release() + expect(await fetching).toEqual([]) + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'cancelJob does not wait for a held due recovery barrier (held)', + async () => { + const h = await harness(factory, { recoverJobsInterval: 1 }) + try { + const target = await h.run() + const recovery = holdRecovery(h.adapter) + await Bun.sleep(5) + const fetching = h.client.fetch() + await recovery.entered + expect(await h.client.cancelJob(target)).toBe(false) + expect(await status(h.adapter, target)).toBe('cancelled') + recovery.release() + expect(await fetching).toEqual([]) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + // ------------------------------------------------------------------------ + // Return values (RV) and remote continuation (F) + // ------------------------------------------------------------------------ + + it( + 'RV: running stays true through finalization; the database branch stays false (public-only, held)', + async () => { + const h = await harness(factory) + try { + const cancels = controlCancel(h.adapter) + const running = await h.run({ mode: 'ignore-abort' }) + await h.client.fetch() + await eventually(() => h.starts.includes(running), 'handler started') + expect(await h.client.cancelJob(running)).toBe(true) + // Finalizing: the abort no longer has an effect, the result is still true. + expect(await h.client.cancelJob(running)).toBe(true) + h.gate(running).resolve() + await eventually( + async () => (await status(h.adapter, running)) === 'cancelled', + 'ActionJob finalizes the cancellation', + ) + // Only the ActionJob wrote its cancellation. + expect(cancels.for(running)).toHaveLength(1) + + // Successful database cancellation of an unclaimed job still returns false. + const unclaimed = await h.run() + expect(await h.client.cancelJob(unclaimed)).toBe(false) + expect(cancels.for(unclaimed)[0]!.result).toBe(true) + expect(await status(h.adapter, unclaimed)).toBe('cancelled') + expectState(h.client, QUIESCENT) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + it( + 'F: a cancellation from elsewhere does not abort the running handler (direct, preserve)', + async () => { + const logs = captureLogs() + const h = await harness(factory, { logger: logs.logger }) + try { + const fails = countCalls(h.adapter, 'failJob') + const target = await h.run({ mode: 'step-after-gate' }) + await h.client.fetch() + await eventually(() => h.starts.includes(target), 'handler started') + // Direct database-branch cancellation (models another Client). + expect(await h.adapter.cancelJob({ jobId: target })).toBe(true) + await Bun.sleep(50) + expect(h.outcomes.has(target)).toBe(false) + h.gate(target).resolve() + await eventually(() => fails.includes(target), 'existing failed-job path') + expect(h.outcomes.get(target)).toBe('rejected') + expect(String(h.errors.get(target))).toContain('Failed to create step') + expect(logs.entries.some((entry) => entry['msg'] === '[ActionJob] Job failed')).toBe(true) + expect(await status(h.adapter, target)).toBe('cancelled') + } finally { + await h.close() + } + }, + TEST_MS, + ) + + // ------------------------------------------------------------------------ + // Lifecycle (Q) + // ------------------------------------------------------------------------ + + it( + 'Q: an external cancelJob after stop rejects without an Adapter call (public-only)', + async () => { + const h = await harness(factory) + try { + const cancels = controlCancel(h.adapter) + const target = await h.run() + expect(await h.client.stop()).toBe(true) + await expect(h.client.cancelJob(target)).rejects.toThrow() + expect(cancels.calls).toEqual([]) + } finally { + await h.close() + } + }, + TEST_MS, + ) + + for (const variant of ['observed', 'incomplete'] as const) { + it( + `Q: a nested cancelJob during drain is admitted, starts no handler and its pending write is ${variant} (held, inspected)`, + async () => { + const h = await harness(factory, { actionConcurrencyLimit: 1 }) + try { + const cancels = controlCancel(h.adapter) + const runner = await h.run({ mode: 'nested-cancel' }) + expect((await h.client.fetch()).map((job) => job.id)).toEqual([runner]) + await eventually(() => h.starts.includes(runner), 'runner started') + const queued = await h.run() + h.nestedTarget.value = queued + expect((await h.client.fetch()).map((job) => job.id)).toEqual([queued]) + + cancels.planFor(queued, 'hold') + let stopped: { ok: boolean; error?: unknown } | null = null + const stopping = h.client.stop().then( + () => (stopped = { ok: true }), + (error: unknown) => (stopped = { ok: false, error }), + ) + // The runner continues after the gate closed and cancels the killed queued job. + h.gate(runner).resolve() + await eventually(() => cancels.for(queued).length === 1, 'nested write entered') + expect(h.nested.has(runner)).toBe(true) + if (variant === 'observed') { + await Bun.sleep(100) + expect(stopped).toBeNull() + } else { + // The shared drain budget reports the still-pending write as incomplete work. + await stopping + expect(stopped!.ok).toBe(false) + expect(String((stopped as any).error)).toContain('admitted-work drain') + } + cancels.for(queued)[0]!.release() + const outcome = await h.nested.get(runner)!.then( + (value) => value, + (error: unknown) => error, + ) + await stopping + if (variant === 'observed') { + expect((stopped as any).error).toBeUndefined() + expect(outcome).toBe(false) + expect(cancels.for(queued)[0]!.result).toBe(true) + } else { + // Held before its real call, the write is issued after the drain closed: the + // Adapter refuses it and the rejection reaches only this nested caller. + expect(String(outcome)).toContain('Lifecycle is not accepting work') + expect(cancels.for(queued)[0]!.result).toBeUndefined() + } + expect(h.starts).toEqual([runner]) + expectState(h.client, [], 'intents') + } finally { + await h.close() + } + }, + TEST_MS, + ) + } + }) +} + +// ---------------------------------------------------------------------------- +// Native PostgreSQL only: in-transaction cancellation barrier and two Clients +// ---------------------------------------------------------------------------- + +type Gate = { reached: Promise; release: () => void; fail: (error: Error) => void } +type StatementStarter = 'select' | 'insert' | 'update' | 'delete' | 'execute' +type StatementPause = { beforeStatement: number; starter: StatementStarter } + +// Statement roles inside _cancelJob; statement 1 is the job-row lock (T). +const CANCEL_AFTER_LOCK: StatementPause = { beforeStatement: 2, starter: 'update' } + +// Test-only barrier, copied from the approved 12a control (cancel-storage.test.ts): pauses the +// adapter's next transaction before the given statement (checked by builder kind) or before +// COMMIT. fail() rejects inside the callback, so the transaction really rolls back. `reached` +// rejects if the transaction ends without reaching the barrier. Callers release in finally. +function gateNextTransaction(adapter: PostgresAdapter, pause: StatementPause | 'commit'): Gate { + const db = (adapter as unknown as { db: { transaction: (...args: any[]) => Promise } }) + .db + const guarded = db.transaction + const reached = Promise.withResolvers() + const open = Promise.withResolvers() + open.promise.catch(() => undefined) + reached.promise.catch(() => undefined) + const hold = async () => { + reached.resolve() + await open.promise + } + db.transaction = (work: (tx: unknown) => Promise, config: unknown) => { + db.transaction = guarded + const transaction = guarded.call( + db, + async (tx: object) => { + if (pause === 'commit') { + const result = await work(tx) + await hold() + return result + } + return work(pauseBeforeStatement(tx, pause, hold, (error) => reached.reject(error))) + }, + config, + ) + const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) + transaction.then(endedEarly, endedEarly) + return transaction + } + return { + reached: reached.promise, + release: () => { + db.transaction = guarded + open.resolve() + }, + fail: (error) => { + db.transaction = guarded + open.reject(error) + }, + } +} + +const STATEMENT_STARTERS = new Set(['select', 'insert', 'update', 'delete', 'execute']) + +function pauseBeforeStatement( + tx: object, + pause: StatementPause, + hold: () => Promise, + mismatch: (error: Error) => void, +): object { + let count = 0 + const chain = (builder: object, index: number, starter: string): object => + new Proxy(builder, { + get(object, property) { + if (property === 'then') { + return (onFulfilled: never, onRejected: never) => + (async () => { + if (index === pause.beforeStatement) { + if (starter === pause.starter) await hold() + else mismatch(new Error(`Statement ${index} is ${starter}, not ${pause.starter}`)) + } + return await (object as PromiseLike) + })().then(onFulfilled, onRejected) + } + const value = Reflect.get(object, property, object) + if (typeof value !== 'function') return value + return (...args: unknown[]) => { + const next = value.apply(object, args) + return next && typeof next === 'object' ? chain(next, index, starter) : next + } + }, + }) + return new Proxy(tx, { + get(object, property) { + const value = Reflect.get(object, property, object) + if (typeof property === 'string' && STATEMENT_STARTERS.has(property)) { + return (...args: unknown[]) => chain(value.apply(object, args), ++count, property) + } + return typeof value === 'function' ? value.bind(object) : value + }, + }) +} + +/** A second Client on the same owned database (no actions): another worker's API calls. */ +async function otherClient(instance: AdapterInstance) { + const adapter = new PostgresAdapter({ connection: instance.connectionUrl, migrateOnStart: false }) + const client = new Client({ + database: adapter, + syncPattern: false, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + return client +} + +if (process.env['POSTGRES_TEST'] === 'true') { + describe('Local undispatched cancellation, native PostgreSQL controls', () => { + for (const [label, pause] of [ + ['E3b: reply released after DELETE, before COMMIT (original controlled E)', 'commit'], + ['E3b′: reply released just after the job-row lock (T)', CANCEL_AFTER_LOCK], + ] as const) { + it( + `${label}: the handler never starts (held, in-transaction barrier, inspected)`, + async () => { + const logs = captureLogs() + const h = await harness(postgresFactory, { logger: logs.logger }) + let gate: Gate | null = null + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + target = await h.run({ mode: 'step' }) + const fetching = h.client.fetch() + await reply.reached + expect(await status(h.adapter, target)).toBe('active') + + gate = gateNextTransaction(h.adapter as PostgresAdapter, pause) + const cancelling = h.client.cancelJob(target) + await gate.reached + // The claim reply is released while the cancellation is still uncommitted. + reply.release() + expect((await fetching).map((job) => job.id)).toEqual([target]) + expectState( + h.client, + [{ jobId: target, pendingWrites: 1, overlapping: 0, queuedItemPending: false }], + 'intents', + ) + + gate.release() + expect(await cancelling).toBe(false) + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('cancelled') + expect(logs.entries.filter((entry) => JSON.stringify(entry).includes('23503'))).toEqual( + [], + ) + expectState(h.client, QUIESCENT) + } finally { + gate?.release() + await h.close() + } + }, + TEST_MS, + ) + } + + it( + 'E5: a rolled-back cancellation still suppresses; the job stays active for recovery (held, in-transaction fault)', + async () => { + const h = await harness(postgresFactory) + let gate: Gate | null = null + try { + let target: string | null = null + const reply = holdReplyFor(h.adapter, () => target) + const fails = countCalls(h.adapter, 'failJob') + target = await h.run({ mode: 'step' }) + const fetching = h.client.fetch() + await reply.reached + + gate = gateNextTransaction(h.adapter as PostgresAdapter, 'commit') + const cancelling = h.client.cancelJob(target) + await gate.reached + reply.release() + await fetching + gate.fail(new Error('injected rollback before COMMIT')) + await expect(cancelling).rejects.toThrow('injected rollback before COMMIT') + await h.sentinel() + expect(h.starts).not.toContain(target) + expect(await status(h.adapter, target)).toBe('active') + expect(fails).not.toContain(target) + expectState(h.client, QUIESCENT) + } finally { + gate?.release() + await h.close() + } + }, + TEST_MS, + ) + + it( + 'F: another Client cancelling a running job does not abort its handler (two Clients, preserve)', + async () => { + const logs = captureLogs() + const h = await harness(postgresFactory, { logger: logs.logger }) + let other: Client | null = null + try { + const fails = countCalls(h.adapter, 'failJob') + const target = await h.run({ mode: 'step-after-gate' }) + await h.client.fetch() + await eventually(() => h.starts.includes(target), 'handler started') + other = await otherClient(h.instance) + expect(await other.cancelJob(target)).toBe(false) + expect(await status(h.adapter, target)).toBe('cancelled') + expectState(other, QUIESCENT) + await Bun.sleep(50) + expect(h.outcomes.has(target)).toBe(false) + h.gate(target).resolve() + await eventually(() => fails.includes(target), 'existing failed-job path') + expect(String(h.errors.get(target))).toContain('Failed to create step') + expect(logs.entries.some((entry) => entry['msg'] === '[ActionJob] Job failed')).toBe(true) + expect(await status(h.adapter, target)).toBe('cancelled') + } finally { + await other?.stop().catch(() => undefined) + await h.close() + } + }, + TEST_MS, + ) + + it( + 'E6: a job claimed by another Client is cancelled through the database branch and consumes no local state (two Clients)', + async () => { + const h = await harness(postgresFactory, { actionConcurrencyLimit: 1 }) + let other: Client | null = null + try { + const blocker = await occupySlot(h) + const target = await h.run() + expect((await h.client.fetch()).map((job) => job.id)).toEqual([target]) + other = await otherClient(h.instance) + // Queued on the worker Client, unknown to the other Client: database branch, false. + expect(await other.cancelJob(target)).toBe(false) + expect(await status(h.adapter, target)).toBe('cancelled') + expectState(other, QUIESCENT) + // The worker Client was not told: its queued handler still starts (remote limit). + h.gate(blocker).resolve() + await eventually(() => h.starts.includes(target), 'remote-cancelled queued job starts') + } finally { + await other?.stop().catch(() => undefined) + await h.close() + } + }, + TEST_MS, + ) + }) +} From 8f896a49b10fa9810bf61f8dd9140fda3de130ae Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 12:58:32 -0300 Subject: [PATCH 023/100] test(duron): release every local-cancellation test hold on close Register claim-reply, fetch, recovery and cancel-write holds per adapter and release them before stopping the Client, and bound single held-event awaits. Replace Promise.withResolvers in the internal registry with a local deferred (Node.js < 22), log queued-window suppression at debug level, document the one-entry-per-job assumption and restore the remote-cancellation consequence in the docs. --- packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/src/action-manager.ts | 4 + packages/duron/src/local-cancellation.ts | 21 ++++- .../duron/test/local-cancellation.test.ts | 78 +++++++++++++++---- 5 files changed, 87 insertions(+), 20 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index cca6ac4..77028fd 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -326,7 +326,7 @@ What happens depends on where the job is: - **Running on this Client** (its handler has started, including while it finishes up after an abort): the handler is aborted in memory and the call returns `true`. The job writes its own cancellation when it settles. - **Anything else**: the call issues its own `Adapter.cancelJob` and returns `false`, even when the database cancellation succeeds. If that write rejects, the rejection reaches this caller only. Concurrent calls each issue their own write and get their own result. - **Claimed by this Client but not started**: the claim reply is still pending, or the job is queued behind `actionConcurrencyLimit`. Once a call is admitted, the job's handler never starts, even if the write rejects. Duron does not retry, replay or compensate the write. A job that a rejected write left active can later be recovered: requeued (and run again) if it has not expired, or archived as `failed` if it has. The suppressed claim keeps its slot in the automatic claim ceiling until the overlapping cancellation writes settle. -- **Running on another Client**: the database cancellation does not stop it. Its handler continues until a step write finds the job inactive, then follows the normal failed-job path. A job that another Client has claimed or queued is not suppressed by a cancellation made elsewhere. +- **Running on another Client**: the database cancellation does not stop it. Its handler continues until a step write finds the job inactive, then follows the normal failed-job path. A job that another Client has claimed or queued is not suppressed by a cancellation made elsewhere: its handler can still start and then fail when step creation returns `null`. This is in-process handling for this Client's own claims, not a durable or fenced cancellation guarantee. Cancellation never waits for worker discovery or the recovery barrier. After `stop()`, new external calls reject; a call made from a running handler during shutdown is still admitted, starts no handler, and its write is observed (or reported as incomplete) by the drain. diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 2057951..8a9f276 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -270,7 +270,7 @@ Limits: - A call that waited checks expiry against its transaction's start time, not the time it acquired the lock. Archived `finishedAt` and `updatedAt` are the application time taken before any wait. - Lock waits have no deadline. A cancellation can wait for in-flight step creations, other terminators, recovery and claims (including claims holding candidate rows they did not select). `completeJob` and `failJob` can wait for step creations, cancellation and recovery. A step creation can wait for terminators and recovery. Step creations can keep overtaking a waiting cancellation, completion or failure, so a busy job can delay them. `client.stop()` observes such waits within its shutdown budgets but does not cut them short; an unfinished wait is reported as an incomplete drain. - Recovery's own step handling, including steps created while recovery runs, is described in [Recovery and concurrent steps](#recovery-and-concurrent-steps). -- This is storage behavior only. `client.cancelJob()` aborts a job that this Client is running in memory; otherwise it cancels in the database. A database cancellation does not stop a handler that is already running elsewhere: it continues until a step write returns "not active". A job this Client has claimed but not yet started (claim reply pending or queued locally) never starts its handler once a `cancelJob()` call is admitted on this same Client; see [`cancelJob`](/docs/client-api#canceljobjobid). Cancellations made through another Client or directly on the adapter do not suppress this Client's claimed or queued jobs. +- This is storage behavior only. `client.cancelJob()` aborts a job that this Client is running in memory; otherwise it cancels in the database. A database cancellation does not stop a handler that is already running elsewhere: it continues until a step write returns "not active". A job this Client has claimed but not yet started (claim reply pending or queued locally) never starts its handler once a `cancelJob()` call is admitted on this same Client; see [`cancelJob`](/docs/client-api#canceljobjobid). Cancellations made through another Client or directly on the adapter do not suppress this Client's claimed or queued jobs: such a handler can still start and then fail when step creation returns `null`. - PGLite runs one statement at a time; it shows the same sequential results, not concurrent locking behavior. ## Job Recovery diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index 19c3c4b..4ab0e08 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -191,6 +191,10 @@ export class ActionManager> { // without an ActionJob or another cancellation write. const suppressed = this.#cancellation.startQueued(job.id) if (suppressed) { + this.#logger.debug( + { jobId: job.id }, + `[ActionManager] Cancelled queued job ${job.id} not started`, + ) track(() => suppressed) return } diff --git a/packages/duron/src/local-cancellation.ts b/packages/duron/src/local-cancellation.ts index 9e5b857..0dc4f57 100644 --- a/packages/duron/src/local-cancellation.ts +++ b/packages/duron/src/local-cancellation.ts @@ -9,7 +9,21 @@ interface Intent { /** A queued entry for this job must not start its handler when dequeued. */ queuedItemPending: boolean /** Resolves when pendingWrites next reaches zero. */ - idle: PromiseWithResolvers | null + idle: Deferred | null +} + +interface Deferred { + promise: Promise + resolve: () => void +} + +// Local deferred instead of Promise.withResolvers, which needs Node.js 22. +function deferred(): Deferred { + let resolve!: () => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } } export interface LocalCancellationSnapshot { @@ -46,6 +60,9 @@ export function inspectLocalCancellation(client: object): LocalCancellationSnaps * writes a cancellation itself. Intents add no ledger units; a suppressed claim keeps its existing * unit until the cancellation writes it overlaps have settled. No coordinator is involved, so * cancellation never waits for worker discovery or recovery. + * + * State is keyed by job ID and assumes at most one local queued entry per job, as the + * ActionManager's active-job map already does. */ export class LocalCancellation { #issued = new Set() @@ -157,7 +174,7 @@ export class LocalCancellation { #writesIdle(intent: Intent): Promise { if (intent.pendingWrites === 0) return Promise.resolve() - intent.idle ??= Promise.withResolvers() + intent.idle ??= deferred() return intent.idle.promise } diff --git a/packages/duron/test/local-cancellation.test.ts b/packages/duron/test/local-cancellation.test.ts index ef4e475..6c8003c 100644 --- a/packages/duron/test/local-cancellation.test.ts +++ b/packages/duron/test/local-cancellation.test.ts @@ -40,6 +40,42 @@ async function eventually(check: () => boolean | Promise, message: stri } } +/** Bounded wait for a single held event (claim reply, wrapper entry, barrier). */ +async function within(promise: Promise, message: string): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`Bounded observation exceeded: ${message}`)), + OBSERVE_MS, + ) + }), + ]) + } finally { + clearTimeout(timer) + } +} + +// Every hold installed on an adapter registers its release here; the harness close() releases +// them all before stopping the Client, so a failed assertion never leaves admitted work held. +const holds = new WeakMap void>>() + +function registerHold(adapter: Adapter, release: () => void) { + let set = holds.get(adapter) + if (!set) { + set = new Set() + holds.set(adapter, set) + } + set.add(release) +} + +function releaseHolds(adapter: Adapter) { + for (const release of holds.get(adapter) ?? []) release() + holds.delete(adapter) +} + async function status(adapter: Adapter, jobId: string) { return (await adapter.getJobById(jobId))?.status } @@ -87,6 +123,7 @@ function holdReplyFor(adapter: Adapter, jobId: () => string | null) { } return jobs } + registerHold(adapter, () => gate.resolve()) return { reached: reached.promise, release: () => gate.resolve(), @@ -106,6 +143,7 @@ function holdFetchBeforeClaim(adapter: Adapter) { await gate.promise return real(options) } + registerHold(adapter, () => gate.resolve()) return { entered: entered.promise, release: () => gate.resolve() } } @@ -128,6 +166,7 @@ function controlCancel(adapter: Adapter) { const calls: CancelCall[] = [] const plan: CancelBehavior[] = [] const planned = new Map() + let released = false adapter.cancelJob = async (options) => { const behavior = planned.get(options.jobId)?.shift() ?? plan.shift() ?? 'pass' const gate = Promise.withResolvers() @@ -139,8 +178,9 @@ function controlCancel(adapter: Adapter) { settled: done.promise, } calls.push(call) + if (released) call.release() try { - if (behavior === 'hold') await gate.promise + if (behavior === 'hold' && !released) await gate.promise if (behavior === 'reject') throw injected() call.result = await real(options) if (behavior === 'uncertain') throw injected() @@ -152,6 +192,10 @@ function controlCancel(adapter: Adapter) { done.resolve() } } + registerHold(adapter, () => { + released = true + for (const call of calls) call.release() + }) return { calls, plan: (...behaviors: CancelBehavior[]) => plan.push(...behaviors), @@ -175,6 +219,7 @@ function holdRecovery(adapter: Adapter) { await gate.promise return real(options) } + registerHold(adapter, () => gate.resolve()) return { entered: entered.promise, release: () => gate.resolve() } } @@ -319,6 +364,7 @@ async function harness(factory: AdapterFactory, options: HarnessOptions = {}): P return id }, async close() { + releaseHolds(instance.adapter) for (const entry of gates.values()) entry.resolve() await c.stop().catch(() => undefined) await instance.deleteDb() @@ -355,7 +401,7 @@ for (const factory of factories) { const cancels = controlCancel(h.adapter) target = await h.run() const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') expect(await status(h.adapter, target)).toBe('active') expect(await h.client.cancelJob(target)).toBe(false) @@ -429,7 +475,7 @@ for (const factory of factories) { const cancels = controlCancel(h.adapter) target = await h.run() const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') cancels.plan('reject') await expect(h.client.cancelJob(target)).rejects.toThrow( @@ -478,7 +524,7 @@ for (const factory of factories) { const cancels = controlCancel(h.adapter) target = await h.run() const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') cancels.plan('hold', 'hold') const first = h.client.cancelJob(target) @@ -519,7 +565,7 @@ for (const factory of factories) { const cancels = controlCancel(h.adapter) target = await h.run() const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') cancels.plan('hold', 'reject') const first = h.client.cancelJob(target) @@ -555,7 +601,7 @@ for (const factory of factories) { const fails = countCalls(h.adapter, 'failJob') target = await h.run() const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') cancels.plan('reject') await expect(h.client.cancelJob(target)).rejects.toThrow( @@ -601,7 +647,7 @@ for (const factory of factories) { const cancels = controlCancel(h.adapter) target = await h.run() const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') cancels.plan('uncertain') await expect(h.client.cancelJob(target)).rejects.toThrow( 'injected cancellation write failure', @@ -631,7 +677,7 @@ for (const factory of factories) { const cancels = controlCancel(h.adapter) target = await h.run({ mode: 'quick' }, 'short') const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') cancels.plan('reject') await expect(h.client.cancelJob(target)).rejects.toThrow() reply.release() @@ -794,7 +840,7 @@ for (const factory of factories) { }, 'waited job claimed behind the blocker') await expect(waiting).rejects.toThrow('Operation timed out') await eventually(() => cancels.for(target!).length === 1, 'fire-and-forget cancel') - await cancels.for(target!)[0]!.settled + await within(cancels.for(target!)[0]!.settled, 'background cancel settled') h.gate(blocker).resolve() await h.sentinel() @@ -842,7 +888,7 @@ for (const factory of factories) { const reply = holdReplyFor(h.adapter, () => target) const cancels = controlCancel(h.adapter) target = await h.run() - await reply.reached + await within(reply.reached, 'claim reply held') cancels.plan('hold', 'hold') const first = h.client.cancelJob(target) await eventually(() => cancels.for(target!).length === 1, 'first write entered') @@ -941,7 +987,7 @@ for (const factory of factories) { const target = await h.run() const held = holdFetchBeforeClaim(h.adapter) const fetching = h.client.fetch() - await held.entered + await within(held.entered, 'claim held') expect(await h.client.cancelJob(target)).toBe(false) expect(await status(h.adapter, target)).toBe('cancelled') held.release() @@ -963,7 +1009,7 @@ for (const factory of factories) { const recovery = holdRecovery(h.adapter) await Bun.sleep(5) const fetching = h.client.fetch() - await recovery.entered + await within(recovery.entered, 'recovery held') expect(await h.client.cancelJob(target)).toBe(false) expect(await status(h.adapter, target)).toBe('cancelled') recovery.release() @@ -1250,12 +1296,12 @@ if (process.env['POSTGRES_TEST'] === 'true') { const reply = holdReplyFor(h.adapter, () => target) target = await h.run({ mode: 'step' }) const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') expect(await status(h.adapter, target)).toBe('active') gate = gateNextTransaction(h.adapter as PostgresAdapter, pause) const cancelling = h.client.cancelJob(target) - await gate.reached + await within(gate.reached, 'transaction barrier reached') // The claim reply is released while the cancellation is still uncommitted. reply.release() expect((await fetching).map((job) => job.id)).toEqual([target]) @@ -1294,11 +1340,11 @@ if (process.env['POSTGRES_TEST'] === 'true') { const fails = countCalls(h.adapter, 'failJob') target = await h.run({ mode: 'step' }) const fetching = h.client.fetch() - await reply.reached + await within(reply.reached, 'claim reply held') gate = gateNextTransaction(h.adapter as PostgresAdapter, 'commit') const cancelling = h.client.cancelJob(target) - await gate.reached + await within(gate.reached, 'transaction barrier reached') reply.release() await fetching gate.fail(new Error('injected rollback before COMMIT')) From edfd9a71ae676cee8b0aaa62cefe589482df58f3 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 13:24:17 -0300 Subject: [PATCH 024/100] test(duron): wait for intents to drain after in-flight automatic fetches In pull-mode local-cancellation tests a periodic fetch issued while a write was pending legitimately joins the intent and can still be in flight; assert that the intent drains within the bounded observation instead of an instantaneous check. --- packages/duron/test/local-cancellation.test.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/duron/test/local-cancellation.test.ts b/packages/duron/test/local-cancellation.test.ts index 6c8003c..ae14f84 100644 --- a/packages/duron/test/local-cancellation.test.ts +++ b/packages/duron/test/local-cancellation.test.ts @@ -922,8 +922,9 @@ for (const factory of factories) { 'unit released after both writes settled', ) expect(h.starts).toEqual([next]) - // Automatic discovery may have its next (empty) fetch in flight: check intents only. - expectState(h.client, [], 'intents') + // A periodic fetch issued while a write was pending joins the intent and may still be in + // flight here: the intent must drain once that fetch's token is removed. + await stateReached(h.client, (state) => state?.intents.length === 0, 'intents drain') } finally { await h.close() } @@ -949,8 +950,9 @@ for (const factory of factories) { cancels.releaseAll() expect(await cancelling).toBe(false) expect(cancels.for(unknown)[0]!.result).toBe(false) - // Automatic discovery may have its next (empty) fetch in flight: check intents only. - expectState(h.client, [], 'intents') + // A periodic fetch issued while a write was pending joins the intent and may still be in + // flight here: the intent must drain once that fetch's token is removed. + await stateReached(h.client, (state) => state?.intents.length === 0, 'intents drain') } finally { await h.close() } From a14ce5a12c81a71b90aa5b7084ffd235aeaad753 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 14:31:39 -0300 Subject: [PATCH 025/100] test: add cross-mechanism acceptance and finish residual docs (ticket 11) - cross-mechanism.test.ts: wait reconciliation while a due recovery barrier blocks discovery; job completion and waits with every notification dropped (one Client and producer/worker Clients); stop with a running handler, an in-flight wait read and a held prune pass inside the phase budgets. Acceptance tests of merged behavior, each shown able to fail under a temporary control mutation. - client.test.ts: the two Concurrency Limits tests drop their own database after a successful stop (no more auxiliary leftovers per run). - notifications/claim-isolation: cleanup failures no longer replace the test body's failure; checks and swallowing unchanged. - docker.ts: one database name per provisioning call, so a retried partial provisioning cannot orphan an unnamed database. - Docs: CONTEXT statuses/archive/group key/concurrency/advisory lock/ recovery; group limits are per action name and group key; driver limitation now tested with postgres.js 4.1.1 (3.x keeps F1/F2). --- CONTEXT.md | 16 +- packages/docs/content/docs/actions.mdx | 2 +- packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 7 +- packages/duron/src/adapters/postgres/base.ts | 2 +- packages/duron/src/constants.ts | 2 + packages/duron/test/claim-isolation.test.ts | 56 ++- packages/duron/test/client.test.ts | 4 + packages/duron/test/cross-mechanism.test.ts | 441 +++++++++++++++++++ packages/duron/test/docker.ts | 27 +- packages/duron/test/notifications.test.ts | 19 +- 11 files changed, 557 insertions(+), 21 deletions(-) create mode 100644 packages/duron/test/cross-mechanism.test.ts diff --git a/CONTEXT.md b/CONTEXT.md index 303fe2f..fa265b3 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -2,7 +2,7 @@ ## Core Concepts -**Job** — A unit of work to be executed. Has a status (`created`, `active`, `completed`, `failed`, `expired`, `archived`), a timeout, optional expiry, and optional variables. Jobs are created via the client and processed by workers. +**Job** — A unit of work to be executed. Has a status (`created`, `active`, `completed`, `failed`, `cancelled`), a timeout, optional expiry, and optional variables. Jobs are created via the client and processed by workers. Expiry is not a status: recovery archives an expired job as `failed`. Archive is storage membership, not a status (see Archive). **Step** — A discrete unit of work within a job's execution. Steps are created by action handlers via `ctx.step()`. Steps can be sequential, parallel, or nested. Each step has its own status and timing. @@ -14,13 +14,13 @@ ## Execution Model -**Sync Pattern** — How a client fetches jobs: `'push'` (listen for NOTIFY), `'pull'` (poll), or `'hybrid'` (both). Configured per-client. +**Sync Pattern** — How a client discovers jobs: `'pull'`, `'push'` or `'hybrid'`. Every mode runs periodic discovery every `pullInterval`; in `'push'` and `'hybrid'`, NOTIFY hints only make discovery faster. `false` makes no automatic claims. Configured per-client. -**Concurrency** — Maximum number of jobs a client processes simultaneously. +**Concurrency** — Several separate limits. A group's limit (see Group Key) applies across all workers at claim time. Per client, `actionConcurrencyLimit` or an action's `concurrency` caps running jobs per action, and `batchSize` caps the client's outstanding automatic claims. -**Heartbeat** — A periodic upsert to the `clients` table (`last_seen_at`) proving an instance is alive. Used for dead-client detection in recovery. +**Heartbeat** — A periodic upsert to the `clients` table (`last_seen_at`, written with SQL `now()`) proving an instance is alive. Used for dead-client detection in recovery. -**Recovery** — The process of detecting and requeuing jobs owned by dead clients (heartbeat older than `heartbeatTimeout`). Runs periodically and on startup. +**Recovery** — The process of detecting jobs owned by dead clients (heartbeat older than `heartbeatTimeout`): expired jobs are archived as `failed`, others are requeued as `created`. Runs on startup and during a worker discovery turn once `recoverJobsInterval` has elapsed; there is no separate recovery timer. ## Telemetry @@ -30,16 +30,16 @@ ## Data Model -**Archive** — Completed/failed/expired jobs are moved from `jobs_active` to `jobs_archive`. Steps follow their parent job. +**Archive** — Completed, failed and cancelled jobs are moved from `jobs_active` to `jobs_archive`. Steps follow their parent job. Time travel can restore an archived job to active storage, so a job with a terminal status can be in either table. **Variables** — Key-value data attached to a job, accessible to action handlers via `ctx.variables`. -**Group Key** — A string used for rate limiting and deduplication. Jobs with the same group key are serialized. +**Group Key** — A string that groups jobs of one action for concurrency control. A group is an action name plus a group key; its limit comes from the latest unexpired job in the group and applies across workers when jobs are claimed. Jobs in a group run one at a time only when that limit is 1. It does not deduplicate enqueued jobs. ## Infrastructure **Adapter** — Database abstraction layer. Implementations: `PostgresAdapter` (PostgreSQL), `PGLiteAdapter` (embedded PG). -**Advisory Lock** — PostgreSQL mechanism for coordinating workers. Used for serializing jobs with the same group key. +**Advisory Lock** — PostgreSQL session lock. Used only to coordinate scheduled archive pruning (key `42`, shared by all schemas in one database). Job claims do not use advisory locks: they row-lock candidates with `SKIP LOCKED` inside a `SERIALIZABLE` transaction. **Client Liveness Table** — A `clients` table storing `client_id` and `last_seen_at`. Updated by heartbeat, queried by recovery to detect dead instances. diff --git a/packages/docs/content/docs/actions.mdx b/packages/docs/content/docs/actions.mdx index 71f4eff..b809b2f 100644 --- a/packages/docs/content/docs/actions.mdx +++ b/packages/docs/content/docs/actions.mdx @@ -317,7 +317,7 @@ The function receives the same context as `groupKey` with `ctx.input` and `ctx.v #### `groups.groupKey` -A function that determines the group key for a job. Jobs with the same group key will respect the group concurrency limit. +A function that determines the group key for a job. Jobs of this action with the same group key share the group concurrency limit. The key does not deduplicate jobs, and jobs run one at a time only when the limit is `1`. ```ts { diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 77028fd..8c25630 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -148,7 +148,7 @@ B is not the number of handlers that run at once. That is `actionConcurrencyLimi ### `groupConcurrencyLimit` -**Optional.** Maximum number of jobs that can run concurrently per group key. Defaults to `10`. +**Optional.** Maximum number of jobs that can run concurrently per action name and group key. Defaults to `10`. ```ts { diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 8a9f276..5a27bd0 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -232,7 +232,12 @@ Limits of this protection: - SQL `now()` in a claim is the claim transaction's start time, not the claim statement's. It determines which latest jobs supply limits, which active jobs count, and the claimed jobs' `startedAt` and `expiresAt`. - The limit governs admission under the existing latest-job and expiry rules. It is not a lease or fence on running work; expiry, recovery and limit changes keep their existing behavior. - If a claim's commit reply is lost, the outcome is uncertain. Duron does not run or replay that claim; existing liveness and recovery handle a job that was committed. -- Known driver limitation, observed with postgres.js 3.4.9: if the database connection closes while any built-in transaction is open, including a claim, the driver can throw an uncaught exception from its own rollback attempt and keep that pooled connection unusable until the adapter closes. Under Node.js's default handling, an uncaught exception terminates the process. The uncommitted claim is not returned. +- Driver version: Duron is tested with postgres.js 4.1.1. Two driver failures reproduced with postgres.js 3.4.9 do not occur with 4.1.1 for the reproduced triggers. Applications that pin postgres.js 3.x keep both: + - If the database connection closes while any built-in transaction is open, including a claim, the driver can throw an uncaught exception from its own rollback attempt and keep that pooled connection unusable until the adapter closes. Under Node.js's default handling, an uncaught exception terminates the process. The uncommitted claim is not returned. + - After `stop()`, work still waiting for a pooled connection can open a new connection that the stopped adapter does not close. That session stays open until the process exits. + + With 4.1.1, work queued while the adapter closes after a lost connection has not been verified. + - PGLite is a single-engine test backend; it runs claims one at a time and is not evidence of multi-process isolation. ## Worker Discovery diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index f367129..069e5d2 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1132,7 +1132,7 @@ export abstract class PostgresBaseAdapter< /** * Internal method to fetch jobs from the database respecting concurrency limits per group. - * Uses the concurrency limit from the latest job created for each groupKey. + * Uses the concurrency limit from the latest job created for each action name and group key. * * Each claim runs the unchanged row-locking claim query in its own SERIALIZABLE * transaction, so concurrent claimants cannot both commit admissions from a stale diff --git a/packages/duron/src/constants.ts b/packages/duron/src/constants.ts index 02d43ed..293356c 100644 --- a/packages/duron/src/constants.ts +++ b/packages/duron/src/constants.ts @@ -8,6 +8,8 @@ export const JOB_STATUS_COMPLETED = 'completed' as const export const JOB_STATUS_FAILED = 'failed' as const export const JOB_STATUS_CANCELLED = 'cancelled' as const +// Expiry is not a status (recovery archives an expired job as failed), and archive is storage +// membership, not a status: a restored job can keep a terminal status in active storage. export const JOB_STATUSES = [ JOB_STATUS_CREATED, JOB_STATUS_ACTIVE, diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 47900d1..2670599 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -95,6 +95,7 @@ async function claimDatabase() { const admin = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 5_000 } }) const barrier = postgres(CONNECTION_URL, { max: 1, connection: { statement_timeout: 5_000 } }) const adapters: PostgresAdapter[] = [] + let primary: { error: unknown } | undefined // relayPort routes this adapter's owned sessions through the diagnostic relay. const adapter = (name: string, max?: number, relayPort?: number) => { const instance = new PostgresAdapter({ connection: options(name, max, relayPort) }) @@ -192,9 +193,23 @@ async function claimDatabase() { return rows[0]!['count'] === 1 }) }, + // Records the test body's failure so a cleanup failure cannot replace it. + recordFailure(error: unknown): void { + primary = { error } + }, + // Runs releaseDatabase(); a cleanup failure after a body failure keeps the body failure first. + async cleanup(): Promise { + try { + await this.releaseDatabase() + } catch (cleanupError) { + if (!primary) throw cleanupError + // oxlint-disable-next-line preserve-caught-error + throw new AggregateError([primary.error, cleanupError], 'Test failed and cleanup failed') + } + }, // Drop the owned database only after fresh evidence of zero other sessions. // Otherwise retain it for separately verified cleanup and fail with its name. - async cleanup(): Promise { + async releaseDatabase(): Promise { try { await barrier`SELECT pg_advisory_unlock_all()`.catch(() => undefined) for (const instance of adapters) await instance.stop().catch(() => undefined) @@ -295,6 +310,9 @@ suite('Native PostgreSQL claim admission', () => { const result = await stale expect(await db.activeCount()).toBe(schedule.limit) expect(sqlState(rejection(result))).toBe('40001') + } catch (error) { + db.recordFailure(error) + throw error } finally { await db.cleanup() } @@ -312,6 +330,9 @@ suite('Native PostgreSQL claim admission', () => { await a.fetch({ batch: schedule.batch }) expect(await b.fetch({ batch: schedule.batch })).toEqual([]) expect(await db.activeCount()).toBe(schedule.limit) + } catch (error) { + db.recordFailure(error) + throw error } finally { await db.cleanup() } @@ -349,6 +370,9 @@ suite('Native PostgreSQL claim admission', () => { expect((await claim).map((job) => job.id)).toEqual([ids[0]!]) expect(await db.activeCount()).toBe(1) expect((await b.fetch({ batch: 1 })).map((job) => job.id)).toEqual([ids[1]!]) + } catch (error) { + db.recordFailure(error) + throw error } finally { await db.cleanup() } @@ -375,6 +399,9 @@ suite('Native PostgreSQL claim admission', () => { expect((await driver`SHOW transaction_isolation`)[0]!['transaction_isolation']).toBe( 'read committed', ) + } catch (error) { + db.recordFailure(error) + throw error } finally { await db.cleanup() } @@ -429,6 +456,9 @@ suite('Native PostgreSQL claim admission', () => { expect(started).toEqual([]) expect(await db.activeCount()).toBe(1) expect(relay.errors).toEqual([]) + } catch (error) { + db.recordFailure(error) + throw error } finally { relay.flush() await stopping?.catch(() => undefined) @@ -477,6 +507,9 @@ suite('Native PostgreSQL claim admission', () => { expect(await stopping).toBe(true) expect(await db.activeCount()).toBe(0) expect(relay.errors).toEqual([]) + } catch (error) { + db.recordFailure(error) + throw error } finally { relay.flush() await stopping?.catch(() => undefined) @@ -505,6 +538,9 @@ suite('Native PostgreSQL claim admission', () => { expect(statements.filter(isClaim)).toHaveLength(1) expect(await db.activeCount()).toBe(0) expect((rejection(await stopping) as Error).message).toContain('admitted-work drain') + } catch (error) { + db.recordFailure(error) + throw error } finally { await db.cleanup() } @@ -537,6 +573,9 @@ suite('Native PostgreSQL claim admission', () => { const stopped = rejection(await stopping) as Error expect(stopped.message).toContain('admitted-work drain') expect(relay.errors).toEqual([]) + } catch (error) { + db.recordFailure(error) + throw error } finally { relay.flush() await a.stop().catch(() => undefined) @@ -580,6 +619,9 @@ suite('Native PostgreSQL claim admission', () => { expect(clock!['timeout']).toBe('00:01:00') expect(await b.stop()).toBe(true) expect(relay.errors).toEqual([]) + } catch (error) { + db.recordFailure(error) + throw error } finally { relay.flush() await b.stop().catch(() => undefined) @@ -639,6 +681,9 @@ suite('Native PostgreSQL claim admission', () => { expect((await driver`SHOW transaction_isolation`)[0]!['transaction_isolation']).toBe( 'read committed', ) + } catch (error) { + db.recordFailure(error) + throw error } finally { // Release every owned gate before awaiting work or ending sessions. unlock.resolve() @@ -722,6 +767,9 @@ suite('Native PostgreSQL claim admission', () => { } else { expect(resultB.status).toBe('fulfilled') } + } catch (error) { + db.recordFailure(error) + throw error } finally { // Release every owned gate before awaiting replay work or ending sessions. unlock.resolve() @@ -763,6 +811,9 @@ suite('Native PostgreSQL claim admission', () => { await db.release() expect((await stale).status).toBe('fulfilled') expect(await db.activeCount()).toBe(3) + } catch (error) { + db.recordFailure(error) + throw error } finally { // Release the barrier before awaiting the legacy claim or ending its session. await db.release().catch(() => undefined) @@ -818,6 +869,9 @@ suite('Native PostgreSQL claim admission', () => { expect(sqlState(rejection(result))).toBe('40001') handlers.resolve() await eventually(async () => (await db.activeCount()) === 0) + } catch (error) { + db.recordFailure(error) + throw error } finally { handlers.resolve() await a.stop().catch(() => undefined) diff --git a/packages/duron/test/client.test.ts b/packages/duron/test/client.test.ts index 8decd72..f7f202b 100644 --- a/packages/duron/test/client.test.ts +++ b/packages/duron/test/client.test.ts @@ -1052,6 +1052,8 @@ function runClientTests(adapterFactory: AdapterFactory) { expect(group1Jobs.length).toEqual(2) await concurrencyClient.stop() + // Drop this test's own database only after a successful stop; retain it otherwise. + await databaseInstance.deleteDb() }) it('should recover expired orphan jobs from dead processes and allow new jobs to proceed', async () => { @@ -1147,6 +1149,8 @@ function runClientTests(adapterFactory: AdapterFactory) { expect(expiredJob.error).toBeTruthy() await concurrencyClient.stop() + // Drop this test's own database only after a successful stop; retain it otherwise. + await databaseInstance.deleteDb() }) }) diff --git a/packages/duron/test/cross-mechanism.test.ts b/packages/duron/test/cross-mechanism.test.ts new file mode 100644 index 0000000..96ea88c --- /dev/null +++ b/packages/duron/test/cross-mechanism.test.ts @@ -0,0 +1,441 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { defineAction } from '../src/action.js' +import type { Adapter } from '../src/adapters/adapter.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' + +// Cross-mechanism acceptance for the integrated PostgreSQL reliability work (ticket 11). +// Each mechanism has its own owning suite; these cases run several of them at once. +// They pass on the integration tip they were written against: they are acceptance tests of +// merged behavior, not reproductions of an open bug. +// +// Control classes used below: +// - public-only: public Client/Adapter calls and public reads. +// - held: an instance-level pass-through wrapper that pauses before or after the real method. +// - fault-injected: notifications dropped at the adapter's `_notify` boundary, before transport. + +const OBSERVE_MS = 10_000 +const TEST_MS = 40_000 + +async function eventually(check: () => boolean | Promise, message: string) { + const end = performance.now() + OBSERVE_MS + while (!(await check())) { + if (performance.now() >= end) throw new Error(`Bounded observation exceeded: ${message}`) + await Bun.sleep(5) + } +} + +// Resolves with the promise's value, or with `fallback` once `ms` elapse first. +async function within(promise: Promise, ms: number, fallback: F): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + promise, + new Promise((resolve) => { + timer = setTimeout(() => resolve(fallback), ms) + }), + ]) + } finally { + clearTimeout(timer) + } +} + +async function status(adapter: Adapter, jobId: string) { + return (await adapter.getJobById(jobId))?.status +} + +// Fault-injected: drop the named notification events (all events when none are named). +function dropNotifications(adapter: Adapter, ...events: string[]) { + const target = adapter as unknown as { _notify: (event: string, data: unknown) => Promise } + const notify = target._notify.bind(adapter) + const dropped: Record = {} + target._notify = async (event, data) => { + if (events.length && !events.includes(event)) return notify(event, data) + dropped[event] = (dropped[event] ?? 0) + 1 + } + return dropped +} + +// Pass-through call counter on a public Adapter instance method. +function countCalls(adapter: Adapter, name: 'fetch' | 'recoverJobs') { + const target = adapter as any + const real = target[name].bind(adapter) + let calls = 0 + target[name] = (...args: unknown[]) => { + calls++ + return real(...args) + } + return () => calls +} + +// Pass-through wrapper on the public Adapter.fetch that counts settled claims. +function countSettledClaims(adapter: Adapter) { + const real = adapter.fetch.bind(adapter) + let settled = 0 + adapter.fetch = async (options) => { + try { + return await real(options) + } finally { + settled++ + } + } + return () => settled +} + +// Runs the body, then stops what it registered (in order) and drops the owned database only +// when every stop succeeded. The body's failure stays first; cleanup failures follow it. +async function withOwnedDatabase( + instance: { deleteDb(): Promise }, + body: (owned: Array<{ stop(): Promise }>) => Promise, +): Promise { + const owned: Array<{ stop(): Promise }> = [] + const failures: unknown[] = [] + try { + await body(owned) + } catch (error) { + failures.push(error) + } + let stopped = true + for (const resource of owned) { + try { + await resource.stop() + } catch (error) { + stopped = false + failures.push(error) + } + } + if (stopped) await instance.deleteDb().catch((error: unknown) => failures.push(error)) + if (failures.length === 1) throw failures[0] + if (failures.length > 1) throw new AggregateError(failures, 'Test or cleanup failed') +} + +const jobOptions = { + queue: 'cross-direct', + groupKey: 'cross-direct', + input: { direct: true }, + timeoutMs: 30_000, + checksum: 'cross-direct', + concurrencyLimit: 1, + concurrencyStepLimit: 1, +} + +const factories: AdapterFactory[] = [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +] + +for (const factory of factories) { + describe(`Cross-mechanism acceptance with ${factory.name}`, () => { + it( + 'settles a wait through wait reconciliation while a due recovery barrier blocks worker discovery (held, fault-injected)', + async () => { + const instance = await factory.create() + const adapter = instance.adapter + const release = Promise.withResolvers() + await withOwnedDatabase(instance, async (owned) => { + try { + let runs = 0 + const action = defineAction()({ + name: 'held', + handler: async () => { + runs++ + await release.promise + return {} + }, + }) + const client = new Client({ + database: adapter, + actions: { held: action }, + syncPattern: 'push', + pullInterval: 20, + batchSize: 1, + recoverJobsOnStart: true, + recoverJobsInterval: 150, + logger: 'silent', + }) + owned.push(client) + const dropped = dropNotifications(adapter, 'job-status-changed') + // The fixture claim below bypasses the Client's discovery chain and its counter. + const directClaim = adapter.fetch.bind(adapter) + const discoveries = countCalls(adapter, 'fetch') + const recoveries = countCalls(adapter, 'recoverJobs') + expect(await client.start()).toBe(true) + const heldId = await client.runAction('held', {}) + await eventually(() => runs === 1, 'the held handler occupies the only automatic slot') + // Recovery is now due. It waits for the held handler, and so does all discovery. + await Bun.sleep(300) + let manualSettled = false + const manual = client.fetch({ batchSize: 1 }).finally(() => { + manualSettled = true + }) + // Observed so an early body failure cannot leave it as an unhandled rejection. + void manual.catch(() => undefined) + const discoveriesBlocked = discoveries() + const recoveriesBlocked = recoveries() + + const id = (await adapter.createJob(jobOptions))! + expect((await directClaim({ batch: 1 })).map((job) => job.id)).toEqual([id]) + const initialRead = Promise.withResolvers() + const readStatus = adapter.getJobStatus.bind(adapter) + adapter.getJobStatus = async (jobId) => { + const result = await readStatus(jobId) + initialRead.resolve() + return result + } + const waiting = client.waitForJob(id, { timeout: 5_000 }) + expect(await within(initialRead.promise, 2_000, 'no initial read')).toBeUndefined() + expect(await adapter.completeJob({ jobId: id, output: { saved: true } })).toBe(true) + expect(await waiting).toEqual({ + id, + actionName: 'cross-direct', + groupKey: 'cross-direct', + description: null, + status: 'completed', + input: { direct: true }, + output: { saved: true }, + error: null, + }) + expect(dropped['job-status-changed']).toBeGreaterThan(0) + + // Worker discovery stayed blocked behind the barrier the whole time. + expect(manualSettled).toBe(false) + expect(discoveries()).toBe(discoveriesBlocked) + expect(recoveries()).toBe(recoveriesBlocked) + expect(runs).toBe(1) + expect(await status(adapter, heldId)).toBe('active') + + release.resolve() + await manual + await eventually( + async () => (await status(adapter, heldId)) === 'completed', + 'the held job completes after release', + ) + expect(recoveries()).toBeGreaterThan(recoveriesBlocked) + } finally { + release.resolve() + } + }) + }, + TEST_MS, + ) + + it( + 'runs a job and settles runActionAndWait with every notification dropped (fault-injected)', + async () => { + const instance = await factory.create() + const adapter = instance.adapter + await withOwnedDatabase(instance, async (owned) => { + let runs = 0 + const action = defineAction()({ + name: 'unhinted', + handler: async () => { + runs++ + return { ran: true } + }, + }) + const client = new Client({ + id: 'cross-unhinted', + database: adapter, + actions: { unhinted: action }, + syncPattern: 'push', + pullInterval: 20, + recoverJobsOnStart: false, + logger: 'silent', + }) + owned.push(client) + const settledClaims = countSettledClaims(adapter) + expect(await client.start()).toBe(true) + // The startup pass must not be the one that finds the job. + await eventually(() => settledClaims() >= 1, 'the startup discovery pass settled') + const dropped = dropNotifications(adapter) + // Periodic worker discovery claims the job; wait reconciliation reads the result. + const result = await client.runActionAndWait('unhinted', {}, { timeout: 5_000 }) + expect(result).toMatchObject({ status: 'completed', output: { ran: true } }) + expect(dropped['job-available']).toBe(1) + expect(dropped['job-status-changed']).toBeGreaterThan(0) + expect(runs).toBe(1) + }) + }, + TEST_MS, + ) + + it( + 'stops within the phase budgets with a running handler, an in-flight wait read and a held prune pass (held)', + async () => { + const instance = await factory.create({ pruneArchive: { olderThan: '1d', intervalMs: 20 } }) + const adapter = instance.adapter as Adapter & { + _acquirePruneLock: () => Promise + db: { $client: { closed?: boolean } } + } + const observer = + factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null + const releaseHandler = Promise.withResolvers() + const releaseRead = Promise.withResolvers() + const releasePrune = Promise.withResolvers() + const readEntered = Promise.withResolvers() + const pruneEntered = Promise.withResolvers() + let stopping: Promise | undefined + await withOwnedDatabase(instance, async (owned) => { + try { + // Held after the real prune lock query settled; the pass then continues normally. + const acquire = adapter._acquirePruneLock.bind(adapter) + let lockCalls = 0 + adapter._acquirePruneLock = async () => { + const acquired = await acquire() + if (++lockCalls === 1) { + pruneEntered.resolve() + await releasePrune.promise + } + return acquired + } + let runs = 0 + const action = defineAction()({ + name: 'draining', + handler: async () => { + runs++ + await releaseHandler.promise + return {} + }, + }) + const client = new Client({ + id: 'cross-stop', + database: adapter, + actions: { draining: action }, + syncPattern: 'push', + pullInterval: 20, + batchSize: 1, + recoverJobsOnStart: false, + logger: 'silent', + }) + owned.push(client) + if (observer) owned.push({ stop: () => observer.end({ timeout: 5 }) }) + expect(await client.start()).toBe(true) + await client.runAction('draining', {}) + await eventually(() => runs === 1, 'the handler is running') + // Ceiling 1: this job stays unclaimed while the first handler runs. + const queued = await client.runAction('draining', {}) + // Held before the real status read, so the wait has a read in flight. + const readStatus = adapter.getJobStatus.bind(adapter) + adapter.getJobStatus = async (jobId) => { + readEntered.resolve() + await releaseRead.promise + return readStatus(jobId) + } + const waiting = client.waitForJob(crypto.randomUUID()) + expect(await within(readEntered.promise, 2_000, 'no read')).toBeUndefined() + expect(await within(pruneEntered.promise, 2_000, 'no prune pass')).toBeUndefined() + + const started = performance.now() + stopping = client.stop() + void stopping.catch(() => undefined) + // The waiter settles at stop; the read, handler and prune pass still drain. + expect(await within(waiting, 1_000, 'pending')).toBeNull() + expect(await within(stopping, 100, 'draining')).toBe('draining') + releaseHandler.resolve() + releaseRead.resolve() + releasePrune.resolve() + expect(await stopping).toBe(true) + // An observation threshold inside one five-second phase budget, not a wall-clock SLA. + expect(performance.now() - started).toBeLessThan(5_000) + + const lockCallsAtStop = lockCalls + await Bun.sleep(100) + // No handler started after stop, and the prune timer did not fire again. + expect(runs).toBe(1) + expect(lockCalls).toBe(lockCallsAtStop) + if (observer) { + const queuedRows = + await observer`SELECT status FROM duron.jobs_active WHERE id = ${queued}` + expect(queuedRows.map((row) => row['status'])).toEqual(['created']) + const liveness = + await observer`SELECT count(*)::int AS count FROM duron.clients WHERE client_id = 'cross-stop'` + expect(liveness[0]!['count']).toBe(0) + // This test's own contract: every session the adapter opened (query pool, LISTEN + // pool and prune reservation) has left the database within a bounded 2s observation + // after stop resolves. It cannot see a reconnect that opens and closes in between + // samples, or one that starts after the last sample. + const deadline = performance.now() + 2_000 + let sessions = -1 + while (sessions !== 0 && performance.now() < deadline) { + const rows = + await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + sessions = rows[0]!['count'] as number + if (sessions !== 0) await Bun.sleep(20) + } + expect(sessions).toBe(0) + } else { + expect(adapter.db.$client.closed).toBe(true) + } + } finally { + releaseHandler.resolve() + releaseRead.resolve() + releasePrune.resolve() + await stopping?.catch(() => undefined) + } + }) + }, + TEST_MS, + ) + }) +} + +const nativeSuite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip +nativeSuite('Cross-mechanism acceptance across PostgreSQL clients', () => { + it( + 'a worker runs a producer job and the producer wait settles with every notification dropped (fault-injected)', + async () => { + const instance = await postgresFactory.create() + const workerAdapter = new PostgresAdapter({ connection: instance.connectionUrl }) + await withOwnedDatabase(instance, async (owned) => { + let runs = 0 + const action = defineAction()({ + name: 'remote', + handler: async () => { + runs++ + return { ran: true } + }, + }) + // The producer has the action for runAction but never claims automatically. + const producer = new Client({ + id: 'cross-producer', + database: instance.adapter, + actions: { remote: action }, + syncPattern: false, + pullInterval: 20, + recoverJobsOnStart: false, + logger: 'silent', + }) + const worker = new Client({ + id: 'cross-worker', + database: workerAdapter, + actions: { remote: action }, + syncPattern: 'push', + pullInterval: 20, + recoverJobsOnStart: false, + logger: 'silent', + }) + // Stopping a Client also stops the adapter it was given. + owned.push(worker, producer) + const settledClaims = countSettledClaims(workerAdapter) + expect(await producer.start()).toBe(true) + expect(await worker.start()).toBe(true) + // The worker's startup pass must not be the one that finds the job. + await eventually(() => settledClaims() >= 1, 'the worker startup discovery pass settled') + const producerDropped = dropNotifications(instance.adapter) + const workerDropped = dropNotifications(workerAdapter) + const result = await producer.runActionAndWait('remote', {}, { timeout: 5_000 }) + expect(result).toMatchObject({ status: 'completed', output: { ran: true } }) + expect((await instance.adapter.getJobById(result.id))?.clientId).toBe('cross-worker') + expect(producerDropped['job-available']).toBe(1) + expect(workerDropped['job-status-changed']).toBeGreaterThan(0) + expect(runs).toBe(1) + }) + }, + TEST_MS, + ) +}) diff --git a/packages/duron/test/docker.ts b/packages/duron/test/docker.ts index 251667c..6335ccb 100644 --- a/packages/duron/test/docker.ts +++ b/packages/duron/test/docker.ts @@ -133,11 +133,24 @@ export const getPostgresConnection = async ({ await waitForContainer(containerName, 'PostgreSQL init process complete') - let name: string + // One name per provisioning call: retries reuse it, so a partly provisioned database is never + // orphaned under a forgotten name. Nothing is dropped here; a final failure names the database. + const name = crypto.randomUUID().split('-').at(-1)! + let createIssued = false + let created = false await pRetry( async () => { - name = crypto.randomUUID().split('-').at(-1)! - await execFile('docker', ['exec', containerName, 'createdb', '-U', 'duron', name]) + if (!created) { + const retry = createIssued + createIssued = true + await execFile('docker', ['exec', containerName, 'createdb', '-U', 'duron', name]).catch( + (error: Error) => { + // Only a retry may adopt the database its own earlier attempt created. + if (!retry || !error.message.includes('already exists')) throw error + }, + ) + created = true + } await execFile('docker', [ 'exec', containerName, @@ -156,10 +169,14 @@ export const getPostgresConnection = async ({ minTimeout: 100, maxTimeout: 100, }, - ) + ).catch((error: unknown) => { + throw new Error(`Failed to provision test database ${name}; it is retained if it exists`, { + cause: error, + }) + }) return { - CONNECTION_URL: `postgres://duron:duron@localhost:${port}/${name!}`, + CONNECTION_URL: `postgres://duron:duron@localhost:${port}/${name}`, deleteDb: async () => { await execFile('docker', ['exec', containerName, 'dropdb', '-U', 'duron', name]) }, diff --git a/packages/duron/test/notifications.test.ts b/packages/duron/test/notifications.test.ts index 3458829..9566984 100644 --- a/packages/duron/test/notifications.test.ts +++ b/packages/duron/test/notifications.test.ts @@ -414,6 +414,8 @@ for (const factory of [ const second: string[] = [] const unrelated: string[] = [] const handles: { unlisten: () => void | Promise }[] = [] + let primary: { error: unknown } | undefined + let released = false const delivery = async (data: unknown, event = 'Exact.Event') => { const received = Promise.withResolvers() const barrier = await adapter._listen(event, () => received.resolve()) @@ -482,17 +484,28 @@ for (const factory of [ expect(rows.map((row) => row.channel)).not.toContain(`${schema}.Exact.Event`) expect(rows.map((row) => row.channel)).toContain(`${schema}.exact.event`) } - } finally { + } catch (error) { + primary = { error } + } + // Same immediate post-stop session check; the observer is always closed, the database is + // dropped only after that check passes, and no cleanup failure replaces the body failure. + const failures: unknown[] = primary ? [primary.error] : [] + try { for (const handle of handles) await handle.unlisten() await adapter.stop() if (observer) { expect( await observer`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()`, ).toHaveLength(0) - await observer.end({ timeout: 5 }) } - await instance.deleteDb() + released = true + } catch (error) { + failures.push(error) } + await observer?.end({ timeout: 5 }).catch((error: unknown) => failures.push(error)) + if (released) await instance.deleteDb().catch((error: unknown) => failures.push(error)) + if (failures.length === 1) throw failures[0] + if (failures.length > 1) throw new AggregateError(failures, 'Test or cleanup failed') }) it.each(['a'.repeat(57), `${'λ'.repeat(28)}a`])( From 806417641fe7900c2c5dd6651abd5165884fd48c Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 14:41:48 -0300 Subject: [PATCH 026/100] docs: correct F2 session lifetime and group-limit JSDoc (ticket 11 review) - multi-worker.mdx: a leaked idle session on postgres.js 3.x lasts until the driver's max_lifetime (random 30-60 min by default) or process exit. - client.ts groupConcurrencyLimit and action.ts groups.groupKey JSDoc: limits apply per action name and group key. --- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/src/action.ts | 2 +- packages/duron/src/client.ts | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 5a27bd0..8f1644e 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -234,7 +234,7 @@ Limits of this protection: - If a claim's commit reply is lost, the outcome is uncertain. Duron does not run or replay that claim; existing liveness and recovery handle a job that was committed. - Driver version: Duron is tested with postgres.js 4.1.1. Two driver failures reproduced with postgres.js 3.4.9 do not occur with 4.1.1 for the reproduced triggers. Applications that pin postgres.js 3.x keep both: - If the database connection closes while any built-in transaction is open, including a claim, the driver can throw an uncaught exception from its own rollback attempt and keep that pooled connection unusable until the adapter closes. Under Node.js's default handling, an uncaught exception terminates the process. The uncommitted claim is not returned. - - After `stop()`, work still waiting for a pooled connection can open a new connection that the stopped adapter does not close. That session stays open until the process exits. + - After `stop()`, work still waiting for a pooled connection can open a new connection that the stopped adapter does not close. That idle session stays open until the driver's `max_lifetime` closes it (a random 30 to 60 minutes by default) or the process exits. With 4.1.1, work queued while the adapter closes after a lost connection has not been verified. diff --git a/packages/duron/src/action.ts b/packages/duron/src/action.ts index bc20a53..4f7e33d 100644 --- a/packages/duron/src/action.ts +++ b/packages/duron/src/action.ts @@ -320,7 +320,7 @@ export interface GroupsConfigInput< > { /** * Function to determine the group key for a job. - * Jobs with the same group key will respect the group concurrency limit. + * Jobs of this action with the same group key share the group concurrency limit. * Use this to limit concurrent processing of related jobs (e.g., per user, per tenant). * * If not provided, all jobs for this action will use the '@default' group key. diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 59dbfaf..1c14726 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -201,8 +201,8 @@ export interface BaseOptionsInput { actionConcurrencyLimit?: number /** - * Maximum number of jobs that can run concurrently per group key. - * Jobs with the same group key will respect this limit. + * Maximum number of jobs that can run concurrently per action name and group key. + * Jobs of one action with the same group key share this limit. * This is the default value; it can be overridden per-job using `action.groups.concurrency`. * * @default 10 From c8c81a2d4e2b52494eaa5f691cd487ab1db1edf0 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 18:38:54 -0300 Subject: [PATCH 027/100] fix: recover without pausing claims; own id only on first recovery Postgres/PGLite recovery includes the adapter's own id only until one recovery succeeds after start, so later recoveries never requeue this worker's running jobs. Worker discovery no longer waits for local work to settle before a due recovery: the recovery runs in the next chain and that chain claims as usual (nothing when the automatic ceiling is full). Docs drop the recovery barrier and the fetch-in-handler warning and describe the startup-only own-id rescue and its trade-off. --- packages/docs/content/docs/client-api.mdx | 8 +- packages/docs/content/docs/multi-worker.mdx | 14 +- packages/duron/src/adapters/postgres/base.ts | 17 +- packages/duron/src/client.ts | 9 +- packages/duron/src/worker-discovery.ts | 21 +- packages/duron/test/cross-mechanism.test.ts | 43 +++- packages/duron/test/heartbeat-clock.test.ts | 7 +- .../duron/test/local-cancellation.test.ts | 2 +- packages/duron/test/recover-own-jobs.test.ts | 211 ++++++++++++++++++ packages/duron/test/recover-snapshot.test.ts | 7 +- packages/duron/test/worker-discovery.test.ts | 71 +----- packages/duron/test/worker-recovery.test.ts | 157 ++++++++++--- 12 files changed, 437 insertions(+), 130 deletions(-) create mode 100644 packages/duron/test/recover-own-jobs.test.ts diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 8c25630..1423f42 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -170,6 +170,8 @@ B is not the number of handlers that run at once. That is `actionConcurrencyLimi **Optional.** Whether to recover stuck jobs on startup. Defaults to `true`. +Startup recovery also rescues jobs that a previous process with the same Client `id` left active. Only the first successful recovery after start does this; when `recoverJobsOnStart` is `false`, the first periodic recovery does it instead. + ```ts { recoverJobsOnStart: true, @@ -182,7 +184,7 @@ B is not the number of handlers that run at once. That is `actionConcurrencyLimi Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Without startup recovery, the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies. -Before recovery runs, the Client stops making new claims, including `fetch()` calls, and waits until all of its locally claimed jobs have settled, so recovery does not requeue jobs this Client is still running. A slow or stuck handler therefore also delays recovery and `fetch()`. One recovery call can affect any number of jobs and has no time limit. +Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs. As a trade-off, if one of this Client's own jobs is lost locally while the process keeps running, periodic recovery does not rescue it; its own timeout and expiry handling still applies. One recovery call can affect any number of jobs and has no time limit. Recovery checks for: @@ -293,8 +295,6 @@ Manually fetch and process jobs from the database. Each call keeps its own batch and returns the jobs it actually claimed, after its claim (not after the handlers finish). Calls are served one at a time together with automatic discovery, in arrival order, so a call can wait behind a running discovery, a due recovery (see `recoverJobsInterval`) or a failure cooldown. A failed call rejects with the original error and is not retried. Calls still waiting when `stop()` begins reject; a call whose claim was already issued returns its jobs, but no handler starts after `stop()`. Direct `client.database.fetch()` calls are outside this coordination. -**Warning:** Do not await `client.fetch()` inside a job handler. While periodic recovery is due, `fetch()` waits for this Client's running jobs to settle, including the handler that is waiting for it. The call can then wait until `client.stop()` rejects it. - ```ts const jobs = await client.fetch({ batchSize: 20, @@ -328,7 +328,7 @@ What happens depends on where the job is: - **Claimed by this Client but not started**: the claim reply is still pending, or the job is queued behind `actionConcurrencyLimit`. Once a call is admitted, the job's handler never starts, even if the write rejects. Duron does not retry, replay or compensate the write. A job that a rejected write left active can later be recovered: requeued (and run again) if it has not expired, or archived as `failed` if it has. The suppressed claim keeps its slot in the automatic claim ceiling until the overlapping cancellation writes settle. - **Running on another Client**: the database cancellation does not stop it. Its handler continues until a step write finds the job inactive, then follows the normal failed-job path. A job that another Client has claimed or queued is not suppressed by a cancellation made elsewhere: its handler can still start and then fail when step creation returns `null`. -This is in-process handling for this Client's own claims, not a durable or fenced cancellation guarantee. Cancellation never waits for worker discovery or the recovery barrier. After `stop()`, new external calls reject; a call made from a running handler during shutdown is still admitted, starts no handler, and its write is observed (or reported as incomplete) by the drain. +This is in-process handling for this Client's own claims, not a durable or fenced cancellation guarantee. Cancellation never waits for worker discovery or recovery. After `stop()`, new external calls reject; a call made from a running handler during shutdown is still admitted, starts no handler, and its write is observed (or reported as incomplete) by the drain. ### `retryJob(jobId)` diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 8f1644e..0e9591d 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -247,10 +247,7 @@ Each Client with actions coordinates its own job discovery: - **One discovery at a time.** The startup pass, periodic checks, notifications and `client.fetch()` calls share one queue and are served one at a time in arrival order. Notifications and periodic checks that arrive while a discovery is running are merged into one pending request. - **Safety in every mode.** With `syncPattern` `'push'`, `'hybrid'` or `'pull'`, the Client discovers work immediately after startup and then every `pullInterval`. Notifications only make discovery faster. Work whose notification was lost, work requeued by recovery, and work that becomes claimable after a group slot frees up or a job expires is found by the next periodic check. - **Automatic claim ceiling.** Automatic claims stop while this Client has `batchSize` claimed jobs outstanding (claimed, queued, running or finishing). See [`batchSize`](/docs/client-api#batchsize) for how this differs from `actionConcurrencyLimit` and SQL group limits. -- **Recovery barrier.** When periodic recovery is due, the Client stops claiming and waits for its own claimed jobs to settle before it runs recovery. This keeps recovery from requeuing jobs that this Client is still running. It is not a database lock and does not coordinate with other workers. - - **Warning:** Do not await `client.fetch()` inside a job handler. While periodic recovery is due, `fetch()` waits for this Client's running jobs to settle, including the handler that is waiting for it. The call can then wait until `client.stop()` rejects it. - +- **Recovery does not pause claiming.** When periodic recovery is due, it runs in the next discovery turn, also while this Client's jobs are running or the automatic claim ceiling is full, and that turn then claims as usual. Recovery and a claim never run at the same time in one Client. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs (see [Job Recovery](#job-recovery)). - **Failures.** After a failed discovery or recovery attempt, all discovery waits one `pullInterval`. Failed claims are never replayed. This coordination is local to one Client. Other Clients, and direct calls such as `client.database.fetch()` or `client.database.recoverJobs()`, are not coordinated with it. Cross-worker group limits rely on the claim admission described above, not on this local coordination. @@ -283,13 +280,16 @@ Limits: Duron uses heartbeat-based liveness detection for crashed-instance recovery: 1. **Heartbeat**: Each instance periodically upserts a liveness record in the `clients` table (every `heartbeatInterval`). PostgreSQL and PGLite use SQL `now()` for both the first write and subsequent updates. -2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery waits until this Client's own claimed jobs have settled (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. +2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. 3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. -4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery includes the current client ID regardless of its heartbeat and does not newly include null owners. +4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery does not newly include null owners. + - **Own jobs**: Only the first successful recovery after the adapter starts (startup recovery, or the first periodic recovery when `recoverJobsOnStart` is `false`) also includes the current client ID, regardless of its heartbeat. This rescues jobs that a previous process with the same ID left active. Later recoveries, including direct `client.database.recoverJobs()` calls, never touch this client's own jobs. A failed first attempt does not count; the next attempt includes the client ID again. 5. **Recovery behavior**: - **Expired jobs** (exceeded timeout): Archived as failed with error information - **Stuck jobs** (not expired): Reset to `created` status and can be picked up by any worker +Trade-off: a job of this client that is lost locally while the process keeps running (for example, its handler promise never settles) is not rescued by periodic recovery. Its own timeout and expiry handling still applies, and another process that later starts with the same ID rescues it once at startup. + ### Recovery and concurrent steps On PostgreSQL, each recovery phase (expired archival, then requeue) runs in its own transaction. It first locks the eligible jobs, skipping jobs another transaction holds, and then archives or requeues only those jobs in a second statement. That statement sees every step committed before the job was locked: @@ -397,7 +397,7 @@ If jobs aren't being processed: 1. **Check worker status**: Verify workers are running and connected to the database 2. **Check sync pattern**: Ensure workers have `syncPattern` `'hybrid'`, `'push'` or `'pull'` (not `false`), and that `pullInterval` is not larger than the delay you can accept for work whose notification was lost -3. **Check outstanding work**: Automatic claims pause while `batchSize` claimed jobs are still outstanding, and a due recovery waits for them to settle; a stuck handler delays both +3. **Check outstanding work**: Automatic claims pause while `batchSize` claimed jobs are still outstanding; a stuck handler keeps its slot until it settles 4. **Check database connection**: Verify all processes can connect to the database 5. **Check logs**: Look for errors in worker logs diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 069e5d2..9a45752 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -108,6 +108,8 @@ export abstract class PostgresBaseAdapter< private pruneConfig: PruneSchedulerConfig | null = null private lastPrunedAt: Date | null = null private initialized = false + // Set by the first successful recovery after start; later recoveries skip own jobs. + private ownJobsRecovered = false protected ownedClosed = false private listenerObligations: Array<{ done: boolean }> = [] private readonly waitReadContext = new AsyncLocalStorage<{ @@ -223,6 +225,7 @@ export abstract class PostgresBaseAdapter< * @returns Promise resolving to `true` if started successfully, `false` otherwise */ protected async _start() { + this.ownJobsRecovered = false if (!lifecycleFor(this).accepting) return // Prune ancient client liveness rows (garbage collection for instances // that died long ago without a graceful release). The threshold is @@ -1261,6 +1264,8 @@ export abstract class PostgresBaseAdapter< /** * Internal method to recover stuck jobs (jobs that were active but the process that owned them is no longer running). * Uses the clients liveness table to detect dead owners: a client whose heartbeat is older than staleTimeoutMs (or missing) is considered dead. + * This adapter's own id is included only until one call succeeds after start, to rescue jobs left + * by a previous process with the same id. Later calls never touch this adapter's own jobs. * Expired archival and then requeue each run in their own transaction (see `_recoverLockedJobs`). * * @returns Promise resolving to the number of jobs recovered @@ -1269,8 +1274,9 @@ export abstract class PostgresBaseAdapter< const { checksums, staleTimeoutMs = 15_000 } = options // Find owners of active jobs that are dead: no liveness row or stale heartbeat. - // This instance's own id is always included to recover jobs left behind - // by a previous run of the same client. + // This instance's own id is included until the first successful recovery after start, + // to recover jobs left behind by a previous run of the same client. + const includeOwn = !this.ownJobsRecovered const deadOwners: { client_id: string }[] = this._map( await this.db.execute<{ client_id: string }>(sql` SELECT DISTINCT j.client_id @@ -1286,7 +1292,11 @@ export abstract class PostgresBaseAdapter< `), ) - const unresponsiveClientIds: string[] = [this.id, ...deadOwners.map((row) => row.client_id)] + const unresponsiveClientIds: string[] = [ + ...(includeOwn ? [this.id] : []), + ...deadOwners.map((row) => row.client_id), + ] + if (unresponsiveClientIds.length === 0) return 0 let recoveredCount = 0 @@ -1396,6 +1406,7 @@ export abstract class PostgresBaseAdapter< ) } + if (includeOwn) this.ownJobsRecovered = true return recoveredCount } diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 1c14726..a235a4e 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -229,6 +229,8 @@ export interface BaseOptionsInput { * Stuck jobs are jobs that were marked as active but the process that owned them * is no longer running (e.g., after a crash or restart). * These jobs will be reset to 'created' status so they can be picked up again. + * The first successful recovery after start (this one, or the first periodic recovery when + * disabled) also rescues jobs a previous process with this Client's id left active. * * @default true */ @@ -257,8 +259,9 @@ export interface BaseOptionsInput { * Recovery checks for expired or stuck jobs and handles them appropriately. * Set to `0` to disable periodic recovery (only runs on startup). * Runs inside worker discovery once strictly more than this many monotonic milliseconds - * have elapsed since startup recovery success or the last attempt's settlement; new claims - * pause until this Client's local work settles first. + * have elapsed since startup recovery success or the last attempt's settlement. It runs + * while this Client's jobs are running and does not pause claiming: it rescues other + * workers' abandoned jobs and never touches this Client's own running jobs. * * @default 60000 */ @@ -742,7 +745,7 @@ export class Client< * Fetch and process jobs from the database. * Concurrency limits are determined from the latest job created for each groupKey. * Calls are served one at a time with automatic discovery; a call may wait behind an - * admitted chain, a due recovery barrier or a failure cooldown. It returns after its claim, + * admitted chain (including a due recovery) or a failure cooldown. It returns after its claim, * not after the claimed handlers finish. Without actions it returns [] without claiming. * * @param [options.batchSize] - Maximum number of jobs to fetch in this batch (defaults to `batchSize` from client options) diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index f61ec86..415af0c 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -69,12 +69,14 @@ const notAccepting = () => new Error('Lifecycle is not accepting work') * - One actual discovery chain at a time across startup, periodic safety, hints and manual * fetch calls. A chain is: optional due recovery, then at most one Adapter.fetch claim. * - At most one coalesced automatic request. Requests are served FIFO among eligible ones; - * cooldown, automatic claim room and the recovery barrier decide eligibility. + * cooldown and automatic claim room decide eligibility. * - Automatic claims use only the room left under a Client-wide ceiling of B outstanding * local claims (claimed, queued, running and finalizing work, plus reservations). Manual * calls keep their own batch and returned jobs and may exceed B. - * - Due recovery pauses every new claim until local work actually settles. Its interval is - * measured monotonically from startup recovery success or any attempt's settlement. + * - Due recovery runs in the next chain even while local jobs are running (the adapter never + * requeues this worker's own jobs after its first successful recovery), then that chain + * claims as usual. Its interval is measured monotonically from startup recovery success or + * any attempt's settlement. * - Any chain failure applies one effective pullInterval cooldown to all triggers. * - Direct Adapter calls (including via client.database) are outside this coordinator. */ @@ -191,13 +193,12 @@ export class WorkerDiscovery { }, this.#cooldownUntil - now) return } - if (this.#recoveryDue(now)) { - // Quiescent barrier: no new claim (manual included) until local work actually settles. - if (this.#local.size === 0) this.#serve(this.#queue[0]!, true) - return - } - const request = this.#queue.find((item) => item.kind === 'manual' || this.#room > 0) - if (request) this.#serve(request, false) + const recover = this.#recoveryDue(now) + // A due recovery does not wait for claim room: without room the chain only recovers. + const request = + this.#queue.find((item) => item.kind === 'manual' || this.#room > 0) ?? + (recover ? this.#queue[0] : undefined) + if (request) this.#serve(request, recover) } #serve(request: DiscoveryRequest, recover: boolean): void { diff --git a/packages/duron/test/cross-mechanism.test.ts b/packages/duron/test/cross-mechanism.test.ts index 96ea88c..43332e8 100644 --- a/packages/duron/test/cross-mechanism.test.ts +++ b/packages/duron/test/cross-mechanism.test.ts @@ -73,6 +73,25 @@ function countCalls(adapter: Adapter, name: 'fetch' | 'recoverJobs') { return () => calls } +// Held: pass-through wrapper on the public Adapter.recoverJobs; every call after install +// waits for release before the real recovery runs. +function holdRecovery(adapter: Adapter) { + const real = adapter.recoverJobs.bind(adapter) + const gate = Promise.withResolvers() + let entered = 0 + adapter.recoverJobs = async (options) => { + entered++ + await gate.promise + return real(options) + } + return { + get entered() { + return entered + }, + release: () => gate.resolve(), + } +} + // Pass-through wrapper on the public Adapter.fetch that counts settled claims. function countSettledClaims(adapter: Adapter) { const real = adapter.fetch.bind(adapter) @@ -132,12 +151,13 @@ const factories: AdapterFactory[] = [ for (const factory of factories) { describe(`Cross-mechanism acceptance with ${factory.name}`, () => { it( - 'settles a wait through wait reconciliation while a due recovery barrier blocks worker discovery (held, fault-injected)', + 'settles a wait through wait reconciliation while a held due recovery blocks worker discovery (held, fault-injected)', async () => { const instance = await factory.create() const adapter = instance.adapter const release = Promise.withResolvers() await withOwnedDatabase(instance, async (owned) => { + let recovery: ReturnType | null = null try { let runs = 0 const action = defineAction()({ @@ -163,12 +183,14 @@ for (const factory of factories) { // The fixture claim below bypasses the Client's discovery chain and its counter. const directClaim = adapter.fetch.bind(adapter) const discoveries = countCalls(adapter, 'fetch') - const recoveries = countCalls(adapter, 'recoverJobs') expect(await client.start()).toBe(true) const heldId = await client.runAction('held', {}) await eventually(() => runs === 1, 'the held handler occupies the only automatic slot') - // Recovery is now due. It waits for the held handler, and so does all discovery. - await Bun.sleep(300) + // The next periodic recovery comes due while the handler runs and is held there. + // Worker discovery runs one chain at a time, so all discovery waits behind it. + recovery = holdRecovery(adapter) + const held = recovery + await eventually(() => held.entered === 1, 'a due periodic recovery is held') let manualSettled = false const manual = client.fetch({ batchSize: 1 }).finally(() => { manualSettled = true @@ -176,7 +198,6 @@ for (const factory of factories) { // Observed so an early body failure cannot leave it as an unhandled rejection. void manual.catch(() => undefined) const discoveriesBlocked = discoveries() - const recoveriesBlocked = recoveries() const id = (await adapter.createJob(jobOptions))! expect((await directClaim({ batch: 1 })).map((job) => job.id)).toEqual([id]) @@ -202,21 +223,25 @@ for (const factory of factories) { }) expect(dropped['job-status-changed']).toBeGreaterThan(0) - // Worker discovery stayed blocked behind the barrier the whole time. + // Worker discovery stayed blocked behind the held recovery the whole time. expect(manualSettled).toBe(false) expect(discoveries()).toBe(discoveriesBlocked) - expect(recoveries()).toBe(recoveriesBlocked) + expect(held.entered).toBe(1) expect(runs).toBe(1) expect(await status(adapter, heldId)).toBe('active') - release.resolve() + held.release() await manual + // The released recovery left this worker's own running job alone. + expect(await status(adapter, heldId)).toBe('active') + release.resolve() await eventually( async () => (await status(adapter, heldId)) === 'completed', 'the held job completes after release', ) - expect(recoveries()).toBeGreaterThan(recoveriesBlocked) + expect(runs).toBe(1) } finally { + recovery?.release() release.resolve() } }) diff --git a/packages/duron/test/heartbeat-clock.test.ts b/packages/duron/test/heartbeat-clock.test.ts index 494581f..f5fdbeb 100644 --- a/packages/duron/test/heartbeat-clock.test.ts +++ b/packages/duron/test/heartbeat-clock.test.ts @@ -203,12 +203,15 @@ for (const factory of [ { client_id: 'clock-minus', delta: '-1' }, { client_id: 'clock-plus', delta: '1' }, ]) + // Only the first successful recovery after start includes the own id, + // regardless of its liveness; later passes leave own jobs active. + const ownIncluded = timeout === undefined expect( await adapter.recoverJobs({ checksums: ['clock-boundary'], staleTimeoutMs: timeout, }), - ).toBe(4) + ).toBe(ownIncluded ? 4 : 3) const states = await rows<{ id: string; status: string }>( tx, sql` @@ -221,7 +224,7 @@ for (const factory of [ 'created', 'active', 'created', - 'created', + ownIncluded ? 'created' : 'active', 'active', ]) } finally { diff --git a/packages/duron/test/local-cancellation.test.ts b/packages/duron/test/local-cancellation.test.ts index ae14f84..be825c0 100644 --- a/packages/duron/test/local-cancellation.test.ts +++ b/packages/duron/test/local-cancellation.test.ts @@ -1003,7 +1003,7 @@ for (const factory of factories) { ) it( - 'cancelJob does not wait for a held due recovery barrier (held)', + 'cancelJob does not wait for a held due recovery (held)', async () => { const h = await harness(factory, { recoverJobsInterval: 1 }) try { diff --git a/packages/duron/test/recover-own-jobs.test.ts b/packages/duron/test/recover-own-jobs.test.ts new file mode 100644 index 0000000..7be7bd2 --- /dev/null +++ b/packages/duron/test/recover-own-jobs.test.ts @@ -0,0 +1,211 @@ +import { describe, expect, it } from 'bun:test' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import type { Adapter } from '../src/adapters/adapter.js' +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +// Own-id recovery scope (adapter level). The adapter's own id is an unresponsive owner +// only until one recovery call succeeds after start; later calls rescue only other owners +// whose liveness is missing or stale. Controls: public Adapter calls and reads; setId to +// claim as another owner (no liveness row); one fault-injected recovery transaction. + +const TEST_MS = 30_000 +const OWN = 'own-worker' +const DEAD = 'dead-worker' +const CHECKSUM = 'own-checksum' + +interface Store { + /** A new adapter instance on the same database (a restarted process). */ + open: () => Adapter + cleanup: () => Promise +} + +interface Engine { + name: 'pglite' | 'postgres' + store: () => Promise +} + +const pglite: Engine = { + name: 'pglite', + store: async () => { + const dir = await mkdtemp(join(tmpdir(), 'duron-own-recovery-')) + return { + open: () => new PGLiteAdapter({ connection: dir, migrateOnStart: true }), + cleanup: () => rm(dir, { recursive: true, force: true }), + } + }, +} + +const postgres: Engine = { + name: 'postgres', + store: async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ + containerName: 'duron-postgres-test', + port: 5440, + }) + return { + open: () => new PostgresAdapter({ connection: CONNECTION_URL, migrateOnStart: true }), + cleanup: deleteDb, + } + }, +} + +const engines: Engine[] = [pglite, ...(process.env['POSTGRES_TEST'] === 'true' ? [postgres] : [])] + +let jobCounter = 0 + +async function createJob(adapter: Adapter, timeoutMs = 60_000): Promise { + const index = ++jobCounter + return (await adapter.createJob({ + queue: 'own-recovery', + groupKey: `own-recovery-${index}-${crypto.randomUUID()}`, + input: { index }, + timeoutMs, + checksum: CHECKSUM, + concurrencyLimit: 100, + concurrencyStepLimit: 10, + }))! +} + +// Claim one new job as `owner`, then switch the adapter back to its own id. +async function claimAs(adapter: Adapter, owner: string, timeoutMs = 60_000): Promise { + adapter.setId(owner) + try { + const jobId = await createJob(adapter, timeoutMs) + expect((await adapter.fetch({ batch: 1 })).map((claimed) => claimed.id)).toEqual([jobId]) + return jobId + } finally { + adapter.setId(OWN) + } +} + +async function job(adapter: Adapter, jobId: string) { + const value = await adapter.getJobById(jobId) + return { status: value?.status, clientId: value?.clientId, startedAt: value?.startedAt } +} + +// Fault-injected: the next recovery transaction rejects before it runs. +function failNextTransaction(adapter: Adapter, error: Error): void { + const db = (adapter as unknown as { db: { transaction: (...args: unknown[]) => unknown } }).db + const guarded = db.transaction + db.transaction = () => { + db.transaction = guarded + return Promise.reject(error) + } +} + +for (const engine of engines) { + describe(`Own-id recovery scope with ${engine.name}`, () => { + // Each test owns its store and adapters (tests in a file may run concurrently). + async function withStore(test: (start: () => Promise) => Promise) { + const store = await engine.store() + const adapters: Adapter[] = [] + try { + await test(async () => { + const adapter = store.open() + adapter.setId(OWN) + adapters.push(adapter) + expect(await adapter.start()).toBe(true) + return adapter + }) + } finally { + for (const adapter of adapters) await adapter.stop() + await store.cleanup() + } + } + + it( + 'the first recovery after start requeues own running jobs and archives own expired jobs', + () => + withStore(async (start) => { + const adapter = await start() + const running = await claimAs(adapter, OWN) + const expired = await claimAs(adapter, OWN, 300) + await Bun.sleep(400) + + expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(2) + expect(await job(adapter, running)).toMatchObject({ status: 'created', startedAt: null }) + expect(await job(adapter, expired)).toMatchObject({ status: 'failed', clientId: OWN }) + }), + TEST_MS, + ) + + it( + 'later recoveries leave own jobs untouched and still rescue owners without liveness', + () => + withStore(async (start) => { + const adapter = await start() + expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) + + const ownRunning = await claimAs(adapter, OWN) + const ownExpired = await claimAs(adapter, OWN, 300) + const deadRunning = await claimAs(adapter, DEAD) + const deadExpired = await claimAs(adapter, DEAD, 300) + const before = await job(adapter, ownRunning) + await Bun.sleep(400) + + expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(2) + expect(await job(adapter, ownRunning)).toEqual({ ...before, status: 'active' }) + expect(await job(adapter, ownExpired)).toMatchObject({ status: 'active', clientId: OWN }) + expect(await job(adapter, deadRunning)).toMatchObject({ + status: 'created', + clientId: DEAD, + }) + expect(await job(adapter, deadExpired)).toMatchObject({ + status: 'failed', + clientId: DEAD, + }) + // With only own jobs left, a later recovery has nothing to rescue. + expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) + expect(await job(adapter, ownRunning)).toEqual({ ...before, status: 'active' }) + }), + TEST_MS, + ) + + it( + 'a restarted adapter with the same id rescues its own leftovers once again', + () => + withStore(async (start) => { + const first = await start() + expect(await first.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) + const leftover = await claimAs(first, OWN) + expect(await first.stop()).toBe(true) + + const restarted = await start() + expect(await restarted.recoverJobs({ checksums: [CHECKSUM] })).toBe(1) + expect(await job(restarted, leftover)).toMatchObject({ status: 'created' }) + + expect((await restarted.fetch({ batch: 1 })).map((value) => value.id)).toEqual([leftover]) + expect(await restarted.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) + expect(await job(restarted, leftover)).toMatchObject({ status: 'active', clientId: OWN }) + }), + TEST_MS, + ) + + it( + 'a failed first recovery still includes own jobs in the next attempt', + () => + withStore(async (start) => { + const adapter = await start() + const leftover = await claimAs(adapter, OWN) + const injected = new Error('injected recovery failure') + failNextTransaction(adapter, injected) + await expect(adapter.recoverJobs({ checksums: [CHECKSUM] })).rejects.toBe(injected) + expect(await job(adapter, leftover)).toMatchObject({ status: 'active' }) + + expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(1) + expect(await job(adapter, leftover)).toMatchObject({ status: 'created' }) + + expect((await adapter.fetch({ batch: 1 })).map((value) => value.id)).toEqual([leftover]) + expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) + expect(await job(adapter, leftover)).toMatchObject({ status: 'active', clientId: OWN }) + }), + TEST_MS, + ) + }) +} diff --git a/packages/duron/test/recover-snapshot.test.ts b/packages/duron/test/recover-snapshot.test.ts index c3dfd5e..9b2a834 100644 --- a/packages/duron/test/recover-snapshot.test.ts +++ b/packages/duron/test/recover-snapshot.test.ts @@ -1202,8 +1202,11 @@ for (const factory of engines) { expect(statement.sql).not.toContain('ANY(') } + // The first successful recovery above was this adapter's only own-id pass, so the + // jobs below are claimed by a dead owner (no liveness row). // One requeued job. - const one = await claimAs(adapter, 'r', 60_000, OLD_CHECKSUM) + const one = await claimAs(adapter, 'dead', 60_000, OLD_CHECKSUM) + adapter.setId('r') const single = await recordTransactions(adapter, () => adapter.recoverJobs({ checksums: [NEW_CHECKSUM] }), ) @@ -1221,7 +1224,9 @@ for (const factory of engines) { } for (let index = 0; index < 30; index++) running.push(await createJob(adapter)) // The earlier requeued job is claimable again too. + adapter.setId('dead') expect(await adapter.fetch({ batch: 100 })).toHaveLength(34) + adapter.setId('r') await Bun.sleep(400) const many = await recordTransactions(adapter, () => adapter.recoverJobs({ checksums: [NEW_CHECKSUM] }), diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index 6f90648..275ff2e 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'bun:test' +import { type SQL, sql } from 'drizzle-orm' import pino from 'pino' import { defineAction } from '../src/action.js' @@ -114,6 +115,12 @@ function count(values: T[], value: T) { return values.filter((item) => item === value).length } +// Fixture: reassign an active job to another owner that has no liveness row. +async function abandonTo(adapter: Adapter, jobId: string, owner: string) { + const db = (adapter as unknown as { db: { execute: (query: SQL) => Promise } }).db + await db.execute(sql`UPDATE duron.jobs_active SET client_id = ${owner} WHERE id = ${jobId}`) +} + // Held: pass-through wrapper on a public Adapter instance method, paused until released. function holdMethod( adapter: Adapter, @@ -336,6 +343,9 @@ for (const factory of factories) { // Direct Adapter claim is outside the Client coordinator: SQL-active, never executed. const claimed = await instance.adapter.fetch({ batch: 1 }) expect(claimed.map((job) => job.id)).toEqual([jobId]) + // Fixture: hand the claim to another owner without liveness. Periodic recovery + // rescues other owners' work, never this worker's own claims. + await abandonTo(instance.adapter, jobId, 'gone-worker') await eventually( async () => (await status(instance.adapter, jobId)) === 'completed', 'periodic recovery requeues and the worker completes the same job', @@ -1019,67 +1029,6 @@ for (const factory of factories) { TEST_MS, ) - it( - 'stop during the recovery barrier rejects waiting calls and starts no recovery (held)', - async () => { - const instance = await factory.create() - let client: Client | null = null - const release = Promise.withResolvers() - try { - let started = 0 - let aborted = false - const action = defineAction()({ - name: 'stop-barrier', - handler: async (ctx) => { - started++ - await ctx.step('hold', async ({ signal }) => { - signal.addEventListener('abort', () => { - aborted = true - }) - await release.promise - return {} - }) - return {} - }, - }) - client = new Client({ - database: instance.adapter, - actions: { 'stop-barrier': action }, - syncPattern: false, - recoverJobsOnStart: true, - recoverJobsInterval: 100, - logger: 'silent', - }) - const realRecover = instance.adapter.recoverJobs.bind(instance.adapter) - let recoveries = 0 - instance.adapter.recoverJobs = async (options) => { - recoveries++ - return realRecover(options) - } - await client.runAction('stop-barrier', {}) - expect(await client.fetch()).toHaveLength(1) - await eventually(() => started === 1, 'handler holds local work') - await Bun.sleep(150) // recovery is now due - const waiting = client.fetch().then( - () => 'resolved', - (error: Error) => error.message, - ) - await Bun.sleep(50) - const before = recoveries - const stopped = client.stop() - expect(await waiting).toBe('Lifecycle is not accepting work') - expect(aborted).toBe(true) - release.resolve() - expect(await stopped).toBe(true) - expect(recoveries).toBe(before) - } finally { - release.resolve() - await closeInstance(client, instance) - } - }, - TEST_MS, - ) - it( 'stop after admitted recovery issues no new claim and rejects the admitted manual call (held)', async () => { diff --git a/packages/duron/test/worker-recovery.test.ts b/packages/duron/test/worker-recovery.test.ts index b1f8a46..2b83e66 100644 --- a/packages/duron/test/worker-recovery.test.ts +++ b/packages/duron/test/worker-recovery.test.ts @@ -15,16 +15,38 @@ import { type AdapterFactory, pgliteFactory, postgresFactory } from './adapters. // both spies are restored before stop so lifecycle budgets observe the real clock. const OBSERVE_MS = 10_000 +const SHORT_MS = 2_000 const TEST_MS = 40_000 -async function eventually(check: () => boolean | Promise, message: string) { - const end = performance.now() + OBSERVE_MS +async function eventually( + check: () => boolean | Promise, + message: string, + bound = OBSERVE_MS, +) { + const end = performance.now() + bound while (!(await check())) { if (performance.now() >= end) throw new Error(`Bounded observation exceeded: ${message}`) await Bun.sleep(5) } } +async function within(promise: Promise, message: string): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`Bounded observation exceeded: ${message}`)), + SHORT_MS, + ) + }), + ]) + } finally { + clearTimeout(timer) + } +} + async function status(adapter: Adapter, jobId: string) { return (await adapter.getJobById(jobId))?.status } @@ -92,7 +114,94 @@ const factories: AdapterFactory[] = [ for (const factory of factories) { describe(`Worker recovery with ${factory.name}`, () => { it( - 'due recovery under a full ceiling waits for actual local settlement and precedes the next claim (held)', + 'due recovery runs while a long local job holds; claiming continues and the own running job is untouched (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const release = Promise.withResolvers() + const events: Event[] = [] + try { + let longRuns = 0 + let shortRuns = 0 + const long = defineAction()({ + name: 'long', + handler: async () => { + longRuns++ + await release.promise + return {} + }, + }) + const short = defineAction()({ + name: 'short', + handler: async () => { + shortRuns++ + return {} + }, + }) + client = new Client({ + id: 'no-pause-worker', + database: instance.adapter, + actions: { long, short }, + syncPattern: 'pull', + pullInterval: 20, + batchSize: 5, + recoverJobsOnStart: true, + recoverJobsInterval: 150, + logger: 'silent', + }) + const trace = traceCalls(instance.adapter, events) + expect(await client.start()).toBe(true) + const longId = await client.runAction('long', {}) + await eventually(() => longRuns === 1, 'the long handler holds local work', SHORT_MS) + const claimed = await instance.adapter.getJobById(longId) + expect(claimed).toMatchObject({ status: 'active', clientId: 'no-pause-worker' }) + + // Recovery comes due while the long job runs; it is not deferred behind it. + const recoveriesWhileHeld = trace.recoveries() + await eventually( + () => trace.recoveries() > recoveriesWhileHeld + 1, + 'periodic recovery runs while local work holds', + SHORT_MS, + ) + // Claiming continues: automatic discovery and a manual call both run new work. + const shortId = await client.runAction('short', {}) + await eventually( + async () => (await status(instance.adapter, shortId)) === 'completed', + 'automatic discovery claims and runs new work', + SHORT_MS, + ) + const manualId = await client.runAction('short', {}) + await within(client.fetch({ batchSize: 5 }), 'manual fetch while local work holds') + await eventually( + async () => (await status(instance.adapter, manualId)) === 'completed', + 'new work completes while the long job holds', + SHORT_MS, + ) + expect(shortRuns).toBe(2) + + // Periodic recovery never requeued this worker's own running job. + const held = await instance.adapter.getJobById(longId) + expect(held).toMatchObject({ status: 'active', clientId: 'no-pause-worker' }) + expect(held?.startedAt?.getTime()).toBe(claimed?.startedAt?.getTime()) + release.resolve() + await eventually( + async () => (await status(instance.adapter, longId)) === 'completed', + 'the long job completes once', + SHORT_MS, + ) + expect(longRuns).toBe(1) + expect(trace.overlap).toBe(0) + } finally { + release.resolve() + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + + it( + 'under a full automatic ceiling a due recovery still runs and issues no automatic claim (held)', async () => { const instance = await factory.create() let client: Client | null = null @@ -101,18 +210,16 @@ for (const factory of factories) { try { let runs = 0 const action = defineAction()({ - name: 'barrier', + name: 'full', handler: async () => { runs++ - events.push('handler:start') await release.promise - events.push('handler:end') return {} }, }) client = new Client({ database: instance.adapter, - actions: { barrier: action }, + actions: { full: action }, syncPattern: 'pull', pullInterval: 20, batchSize: 1, @@ -122,35 +229,27 @@ for (const factory of factories) { }) const trace = traceCalls(instance.adapter, events) expect(await client.start()).toBe(true) - const first = await client.runAction('barrier', {}) - await eventually(() => runs === 1, 'first handler holds the only automatic slot') - const recoveriesWhileHeld = trace.recoveries() - // A manual call issued while recovery is due must wait behind the barrier. - await Bun.sleep(300) - let manualSettled = false - const manual = client.fetch({ batchSize: 5 }).finally(() => { - manualSettled = true - }) - await Bun.sleep(100) - expect(trace.recoveries()).toBe(recoveriesWhileHeld) - expect(manualSettled).toBe(false) - const second = await client.runAction('barrier', {}) - await Bun.sleep(100) + const first = await client.runAction('full', {}) + await eventually(() => runs === 1, 'the first handler holds the only slot', SHORT_MS) + const second = await client.runAction('full', {}) + const claims = () => events.filter((event) => event === 'fetch:start').length + const claimsWhileFull = claims() + const recoveriesWhileFull = trace.recoveries() + await eventually( + () => trace.recoveries() > recoveriesWhileFull + 1, + 'periodic recovery runs under a full ceiling', + SHORT_MS, + ) + expect(claims()).toBe(claimsWhileFull) expect(await status(instance.adapter, second)).toBe('created') - // Still-live local work was not requeued by a recovery pass. expect(await status(instance.adapter, first)).toBe('active') release.resolve() - await manual await eventually( async () => (await status(instance.adapter, second)) === 'completed', - 'claiming resumes after recovery', + 'claiming resumes when the slot frees', + SHORT_MS, ) - expect(await status(instance.adapter, first)).toBe('completed') expect(runs).toBe(2) - const firstEnd = events.indexOf('handler:end') - const nextRecovery = events.indexOf('recover:start', firstEnd) - expect(nextRecovery).toBeGreaterThan(firstEnd) - expect(events.indexOf('fetch:start', firstEnd)).toBeGreaterThan(nextRecovery) expect(trace.overlap).toBe(0) } finally { release.resolve() From 1560c4a85197523896df98fb2a1868e98851b69e Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 18:47:24 -0300 Subject: [PATCH 028/100] fix: claim nothing until a recovery has succeeded once While periodic recovery is enabled, worker discovery treats recovery as due in every chain until one recovery (startup or periodic) succeeds. A failed recovery still skips that chain's claim and applies the cooldown, so no job is claimed while the adapter still includes its own id and a live job is never requeued. Normal cadence applies after the first success; recoverJobsInterval 0 is unchanged. --- packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/src/client.ts | 7 +- packages/duron/src/worker-discovery.ts | 8 +- packages/duron/test/worker-discovery.test.ts | 15 +++- packages/duron/test/worker-recovery.test.ts | 78 ++++++++++++++++++++ 6 files changed, 103 insertions(+), 9 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 1423f42..1ed46a0 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -182,7 +182,7 @@ Startup recovery also rescues jobs that a previous process with the same Client **Optional.** Interval in milliseconds between periodic job recovery runs. Defaults to `60000` (1 minute). Set to `0` to disable periodic recovery (only runs on startup). -Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Without startup recovery, the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies. +Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Until one recovery has succeeded (startup or periodic), every discovery turn recovers first, so without startup recovery the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies; the Client therefore claims no job before a recovery succeeds. Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs. As a trade-off, if one of this Client's own jobs is lost locally while the process keeps running, periodic recovery does not rescue it; its own timeout and expiry handling still applies. One recovery call can affect any number of jobs and has no time limit. diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 0e9591d..1e86c11 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -280,7 +280,7 @@ Limits: Duron uses heartbeat-based liveness detection for crashed-instance recovery: 1. **Heartbeat**: Each instance periodically upserts a liveness record in the `clients` table (every `heartbeatInterval`). PostgreSQL and PGLite use SQL `now()` for both the first write and subsequent updates. -2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. +2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). Until one recovery has succeeded, every discovery turn recovers first, and a failed recovery skips that turn's claim, so the worker claims no job while recovery still includes its own client ID. There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. 3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. 4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery does not newly include null owners. - **Own jobs**: Only the first successful recovery after the adapter starts (startup recovery, or the first periodic recovery when `recoverJobsOnStart` is `false`) also includes the current client ID, regardless of its heartbeat. This rescues jobs that a previous process with the same ID left active. Later recoveries, including direct `client.database.recoverJobs()` calls, never touch this client's own jobs. A failed first attempt does not count; the next attempt includes the client ID again. diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index a235a4e..21b3a2a 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -259,9 +259,10 @@ export interface BaseOptionsInput { * Recovery checks for expired or stuck jobs and handles them appropriately. * Set to `0` to disable periodic recovery (only runs on startup). * Runs inside worker discovery once strictly more than this many monotonic milliseconds - * have elapsed since startup recovery success or the last attempt's settlement. It runs - * while this Client's jobs are running and does not pause claiming: it rescues other - * workers' abandoned jobs and never touches this Client's own running jobs. + * have elapsed since startup recovery success or the last attempt's settlement. Until one + * recovery has succeeded, every discovery turn recovers first and claims only after success. + * It runs while this Client's jobs are running and does not pause claiming: it rescues + * other workers' abandoned jobs and never touches this Client's own running jobs. * * @default 60000 */ diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index 415af0c..c865af9 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -76,7 +76,8 @@ const notAccepting = () => new Error('Lifecycle is not accepting work') * - Due recovery runs in the next chain even while local jobs are running (the adapter never * requeues this worker's own jobs after its first successful recovery), then that chain * claims as usual. Its interval is measured monotonically from startup recovery success or - * any attempt's settlement. + * any attempt's settlement. Until one recovery has succeeded (startup or periodic), every + * chain recovers first, so nothing is claimed while the adapter still includes its own id. * - Any chain failure applies one effective pullInterval cooldown to all triggers. * - Direct Adapter calls (including via client.database) are outside this coordinator. */ @@ -91,6 +92,7 @@ export class WorkerDiscovery { #stopped = false #cooldownUntil = -Infinity #recoveredAt = -Infinity + #recoverySucceeded = false #reserved = 0 #local = new Set>() #tick: ReturnType | null = null @@ -105,6 +107,7 @@ export class WorkerDiscovery { /** Successful startup recovery anchors the next periodic recovery interval. */ anchorRecovery(): void { this.#recoveredAt = monotonicMs() + this.#recoverySucceeded = true } /** Admit discovery after the Client is running: one immediate pass, then periodic safety. */ @@ -180,7 +183,7 @@ export class WorkerDiscovery { #recoveryDue(now: number): boolean { const interval = this.#options.recoverJobsInterval - return interval > 0 && now - this.#recoveredAt > interval + return interval > 0 && (!this.#recoverySucceeded || now - this.#recoveredAt > interval) } #pump(): void { @@ -229,6 +232,7 @@ export class WorkerDiscovery { if (recover) { try { await this.#options.recover() + this.#recoverySucceeded = true } finally { this.#recoveredAt = monotonicMs() } diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index 275ff2e..36a55c3 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -950,7 +950,7 @@ for (const factory of factories) { ) it( - 'skips the claim after a background recovery failure and claims after cooldown without rerunning recovery (fault-injected)', + 'skips the claim after a background recovery failure and recovers again before the first claim (fault-injected)', async () => { const instance = await factory.create() let client: Client | null = null @@ -974,12 +974,23 @@ for (const factory of factories) { return realRecover(options) } const calls = failFetch(instance.adapter, 0, new Error('unused')) + const observedFetch = instance.adapter.fetch.bind(instance.adapter) + const firstClaim: { recoveries: number | null } = { recoveries: null } + instance.adapter.fetch = async (options) => { + firstClaim.recoveries ??= recoveries + return observedFetch(options) + } expect(await client.start()).toBe(true) await eventually(() => recoveries === 1, 'unanchored first turn recovers') await Bun.sleep(50) expect(calls).toHaveLength(0) + // Until a recovery succeeds, every turn recovers first; only then does it claim. await eventually(() => calls.length >= 1, 'a later turn claims') - expect(recoveries).toBe(1) + expect(firstClaim.recoveries).toBe(2) + // After that success the normal cadence applies: later turns do not recover. + await Bun.sleep(250) + expect(calls.length).toBeGreaterThan(1) + expect(recoveries).toBe(2) const failures = logs.discovery() expect(failures).toHaveLength(1) expect(failures[0]!['stage']).toBe('recovery') diff --git a/packages/duron/test/worker-recovery.test.ts b/packages/duron/test/worker-recovery.test.ts index 2b83e66..0b0d271 100644 --- a/packages/duron/test/worker-recovery.test.ts +++ b/packages/duron/test/worker-recovery.test.ts @@ -260,6 +260,84 @@ for (const factory of factories) { TEST_MS, ) + it( + 'without startup recovery no job is claimed until a recovery succeeds; a live job is never requeued (fault-injected)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const release = Promise.withResolvers() + const events: Event[] = [] + try { + let runs = 0 + const action = defineAction()({ + name: 'gated', + handler: async () => { + runs++ + await release.promise + return {} + }, + }) + client = new Client({ + id: 'gated-worker', + database: instance.adapter, + actions: { gated: action }, + syncPattern: 'pull', + pullInterval: 20, + recoverJobsOnStart: false, + recoverJobsInterval: 150, + logger: 'silent', + }) + const trace = traceCalls(instance.adapter, events) + const injected = new Error('injected recovery failure') + trace.failRecovery(injected) + const claims = () => events.filter((event) => event === 'fetch:start').length + expect(await client.start()).toBe(true) + const jobId = await client.runAction('gated', {}) + + // Every chain retries recovery after the cooldown and claims nothing. + await eventually(() => trace.recoveries() >= 3, 'failed recovery is retried', SHORT_MS) + await expect(client.fetch()).rejects.toBe(injected) + expect(claims()).toBe(0) + expect(runs).toBe(0) + expect(await status(instance.adapter, jobId)).toBe('created') + + // Once one recovery succeeds, claiming proceeds. + trace.failRecovery(null) + await eventually( + () => runs === 1, + 'the job is claimed after a successful recovery', + SHORT_MS, + ) + const claimed = await instance.adapter.getJobById(jobId) + expect(claimed).toMatchObject({ status: 'active', clientId: 'gated-worker' }) + + // Normal cadence: periodic recovery runs while the job is live and leaves it alone. + const recoveriesWhileLive = trace.recoveries() + await eventually( + () => trace.recoveries() > recoveriesWhileLive + 1, + 'periodic recovery runs while the job is live', + SHORT_MS, + ) + const live = await instance.adapter.getJobById(jobId) + expect(live).toMatchObject({ status: 'active', clientId: 'gated-worker' }) + expect(live?.startedAt?.getTime()).toBe(claimed?.startedAt?.getTime()) + release.resolve() + await eventually( + async () => (await status(instance.adapter, jobId)) === 'completed', + 'the job completes once', + SHORT_MS, + ) + expect(runs).toBe(1) + expect(trace.overlap).toBe(0) + } finally { + release.resolve() + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + describe('monotonic recovery cadence (controlled clock)', () => { let restore: Array<() => void> = [] afterEach(() => { From cfbeb18cb26c90040fb2b7a9465525eb2fe8cd79 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 18:53:49 -0300 Subject: [PATCH 029/100] docs: qualify the own-jobs recovery guarantee for direct recoverJobs calls The guarantee covers Duron's startup and periodic recovery. With recoverJobsOnStart false and recoverJobsInterval 0 no recovery runs, own leftovers are not rescued automatically, and the first successful direct database.recoverJobs() call still includes the own id and can requeue running jobs. A direct call overlapping the first recovery can requeue a fresh claim. Docs and JSDoc only. --- packages/docs/content/docs/client-api.mdx | 6 +++--- packages/docs/content/docs/multi-worker.mdx | 5 +++-- packages/duron/src/client.ts | 9 ++++++++- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 1ed46a0..df1bdbc 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -170,7 +170,7 @@ B is not the number of handlers that run at once. That is `actionConcurrencyLimi **Optional.** Whether to recover stuck jobs on startup. Defaults to `true`. -Startup recovery also rescues jobs that a previous process with the same Client `id` left active. Only the first successful recovery after start does this; when `recoverJobsOnStart` is `false`, the first periodic recovery does it instead. +Startup recovery also rescues jobs that a previous process with the same Client `id` left active. Only the first successful recovery after start does this. When `recoverJobsOnStart` is `false`, the first periodic recovery does it instead. When `recoverJobsOnStart` is `false` and `recoverJobsInterval` is `0`, Duron runs no recovery, so these leftovers are never rescued automatically. In that configuration, the first successful direct `client.database.recoverJobs()` call after start includes this Client's own `id`, and it can requeue jobs this Client is running. Call it before the Client claims jobs, or keep startup recovery on. ```ts { @@ -182,9 +182,9 @@ Startup recovery also rescues jobs that a previous process with the same Client **Optional.** Interval in milliseconds between periodic job recovery runs. Defaults to `60000` (1 minute). Set to `0` to disable periodic recovery (only runs on startup). -Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Until one recovery has succeeded (startup or periodic), every discovery turn recovers first, so without startup recovery the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies; the Client therefore claims no job before a recovery succeeds. +Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Until one recovery has succeeded (startup or periodic), every discovery turn recovers first, so without startup recovery the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies. So, while periodic recovery is enabled, the Client claims no job before a recovery succeeds. -Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs. As a trade-off, if one of this Client's own jobs is lost locally while the process keeps running, periodic recovery does not rescue it; its own timeout and expiry handling still applies. One recovery call can affect any number of jobs and has no time limit. +Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs. This guarantee covers Duron's own startup and periodic recovery. It does not cover direct `client.database.recoverJobs()` calls: the first successful recovery after start includes this Client's own `id` (see [`recoverJobsOnStart`](#recoverjobsonstart)). A direct call that starts before that first success, and that is still running when the Client begins to claim, can also requeue a job this Client just claimed. As a trade-off, if one of this Client's own jobs is lost locally while the process keeps running, periodic recovery does not rescue it; its own timeout and expiry handling still applies. One recovery call can affect any number of jobs and has no time limit. Recovery checks for: diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 1e86c11..5fb42c3 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -280,10 +280,11 @@ Limits: Duron uses heartbeat-based liveness detection for crashed-instance recovery: 1. **Heartbeat**: Each instance periodically upserts a liveness record in the `clients` table (every `heartbeatInterval`). PostgreSQL and PGLite use SQL `now()` for both the first write and subsequent updates. -2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). Until one recovery has succeeded, every discovery turn recovers first, and a failed recovery skips that turn's claim, so the worker claims no job while recovery still includes its own client ID. There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. +2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). Until one recovery has succeeded, every discovery turn recovers first, and a failed recovery skips that turn's claim, so while periodic recovery is enabled the worker claims no job while recovery still includes its own client ID. There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. 3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. 4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery does not newly include null owners. - - **Own jobs**: Only the first successful recovery after the adapter starts (startup recovery, or the first periodic recovery when `recoverJobsOnStart` is `false`) also includes the current client ID, regardless of its heartbeat. This rescues jobs that a previous process with the same ID left active. Later recoveries, including direct `client.database.recoverJobs()` calls, never touch this client's own jobs. A failed first attempt does not count; the next attempt includes the client ID again. + - **Own jobs**: Only the first successful recovery after the adapter starts also includes the current client ID, regardless of its heartbeat. That is startup recovery, or the first periodic recovery when `recoverJobsOnStart` is `false`. This rescues jobs that a previous process with the same ID left active. After that first success, later recoveries never touch this client's own jobs, and this includes direct `client.database.recoverJobs()` calls. A failed first attempt does not count; the next attempt includes the client ID again. + - **Direct calls**: The guarantee that recovery never touches this worker's running jobs covers Duron's own startup and periodic recovery. With `recoverJobsOnStart: false` and `recoverJobsInterval: 0`, Duron runs no recovery. Leftovers from a previous process with the same ID are then never rescued automatically. The first successful direct `client.database.recoverJobs()` call after start still includes this worker's own ID and can requeue jobs it is running. Call it before the worker claims jobs, or keep startup recovery on. A direct call that starts before the first success and is still running when the worker begins to claim can also requeue a job the worker just claimed. 5. **Recovery behavior**: - **Expired jobs** (exceeded timeout): Archived as failed with error information - **Stuck jobs** (not expired): Reset to `created` status and can be picked up by any worker diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 21b3a2a..8181538 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -231,6 +231,10 @@ export interface BaseOptionsInput { * These jobs will be reset to 'created' status so they can be picked up again. * The first successful recovery after start (this one, or the first periodic recovery when * disabled) also rescues jobs a previous process with this Client's id left active. + * With this option false and `recoverJobsInterval` 0, Duron runs no recovery: such jobs are + * never rescued automatically, and the first successful direct `database.recoverJobs()` + * call after start includes this Client's id and can requeue its running jobs. Call it + * before claiming, or keep startup recovery on. * * @default true */ @@ -262,7 +266,10 @@ export interface BaseOptionsInput { * have elapsed since startup recovery success or the last attempt's settlement. Until one * recovery has succeeded, every discovery turn recovers first and claims only after success. * It runs while this Client's jobs are running and does not pause claiming: it rescues - * other workers' abandoned jobs and never touches this Client's own running jobs. + * other workers' abandoned jobs and never touches this Client's own running jobs. That + * guarantee covers Duron's own startup and periodic recovery, not a first direct + * `database.recoverJobs()` call (see `recoverJobsOnStart`) or a direct call that overlaps + * the first recovery. * * @default 60000 */ From 53acf57c241f96c656933bbfea831c35f257a3e7 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 21:46:37 -0300 Subject: [PATCH 030/100] chore: bump drizzle-orm and drizzle-kit to 1.0.0-rc.6; type JSON params as text rc.6 no longer sets the transparent json (114) and jsonb (3802) serializers on the postgres-js client (rc.4 postgres-js/driver.js:29-30). postgres.js then applies its own JSON.stringify serializer (postgres src/types.js:24,251-252) to a string parameter that the server types as jsonb. The value is stored as a JSON string. Cast the JSON.stringify parameters to text before jsonb. This does not depend on the driver: rc.4 and rc.6, postgres.js 3 and 4, and PGlite. - _delayJobStep: the error entry in history_failed_attempts - #buildJsonbWhereConditions: the array containment filter (@>) for non-string values - adapter.test.ts: 3 listing seed fixtures Red -> green (native PostgreSQL, Bun 1.4.6-canary.1): - red before the fix: adapter "should delay a job step" (ZodError: the error is a string), "global page payload", "listing filters" active/archive; create-step "should retry step definition before failing action" - red after only the fixture fix: listing filters active/archive (the @> filter matched nothing) - green: typecheck, lint, fmt, build; root 520 pass/75 skip/0 fail; native per-file 59/59 files; native full 1000 pass/0 fail --- bun.lock | 72 ++------------------ packages/duron/package.json | 4 +- packages/duron/src/adapters/postgres/base.ts | 8 ++- packages/duron/test/adapter.test.ts | 7 +- 4 files changed, 15 insertions(+), 76 deletions(-) diff --git a/bun.lock b/bun.lock index 9190aa5..691ede9 100644 --- a/bun.lock +++ b/bun.lock @@ -66,8 +66,8 @@ "@opentelemetry/core": "^2.4.0", "@types/bun": "latest", "@types/node": "^24.0.15", - "drizzle-kit": "^1.0.0-rc.4", - "drizzle-orm": "^1.0.0-rc.4", + "drizzle-kit": "1.0.0-rc.6", + "drizzle-orm": "1.0.0-rc.6", "postgres": "^4.1.1", "typescript": "^7", }, @@ -220,8 +220,6 @@ "@dnd-kit/utilities": ["@dnd-kit/utilities@3.2.2", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="], - "@drizzle-team/brocli": ["@drizzle-team/brocli@0.12.0", "", {}, "sha512-mlUE+rZ8CatQekLhnaiN91Iemdd+e2gFKooGlnRB3oPTL3VghLfX24dx7HrzMNeC1JrIB/0kpsfyty3f5HNfxQ=="], - "@electric-sql/pglite": ["@electric-sql/pglite@0.3.16", "", {}, "sha512-mZkZfOd9OqTMHsK+1cje8OSzfAQcpD7JmILXTl5ahdempjUDdmg4euf1biDex5/LfQIDJ3gvCu6qDgdnDxfJmA=="], "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="], @@ -296,8 +294,6 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], - "@js-temporal/polyfill": ["@js-temporal/polyfill@0.5.1", "", { "dependencies": { "jsbi": "^4.3.0" } }, "sha512-hloP58zRVCRSpgDxmqCWJNlizAlUgJFqG2ypq79DCvyv9tHjRYMDOcPFjzfl/A1/YxDvRCZz8wvZvmapQnKwFQ=="], - "@maskito/core": ["@maskito/core@4.0.1", "", {}, "sha512-0ewYXnr8X7as/n57duk1DDqjAKF0m32XbFiAhKdd9OX83eMBzO2+4xgUFxh6WZJ18oSw6y2nWjCTDFAFc5JbhA=="], "@maskito/kit": ["@maskito/kit@4.0.1", "", { "peerDependencies": { "@maskito/core": "^4.0.1" } }, "sha512-GHxK65y5sBwCO0Retl80NvB37uDaIY9g5hezyOe9EG7+zjGRUqDjYc3b04ofJHlGgPtpreOiBDq5bqEr0I/OMw=="], @@ -950,9 +946,9 @@ "dompurify": ["dompurify@3.2.7", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-WhL/YuveyGXJaerVlMYGWhvQswa7myDG17P7Vu65EWC05o8vfeNbvNf4d/BOvH99+ZW+LlQsc1GDKMa1vNK6dw=="], - "drizzle-kit": ["drizzle-kit@1.0.0-rc.4", "", { "dependencies": { "@drizzle-team/brocli": "^0.12.0", "@js-temporal/polyfill": "^0.5.1", "esbuild": "^0.25.10", "get-tsconfig": "^4.13.6", "jiti": "^2.6.1" }, "bin": { "drizzle-kit": "bin.cjs" } }, "sha512-KZCpjRyu+oYHLj/UJogfFlOkWhHVkaEI2EOT1U3NDVXUzLoTyPjqwFxwOrlQxsY6jzRyxcz4EacqboGfhEeYrA=="], + "drizzle-kit": ["drizzle-kit@1.0.0-rc.6", "", { "peerDependencies": { "drizzle-orm": ">=1.0.0-rc.5", "oxc-parser": "^0.157.0" }, "optionalPeers": ["drizzle-orm", "oxc-parser"], "bin": { "drizzle-kit": "bin.js" } }, "sha512-UNwJcuwG8Iw/5M/aKmmzaX61OQgX+gj87MIEZE4J/2pSDCnQJHjhFhmPq8YNHAHnY81bbGsqiWxlyiybDD1E/g=="], - "drizzle-orm": ["drizzle-orm@1.0.0-rc.4", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@effect/sql-d1": ">=4.0.0-beta.83 || >=4.0.0", "@effect/sql-libsql": ">=4.0.0-beta.83 || >=4.0.0", "@effect/sql-mysql2": ">=4.0.0-beta.83 || >=4.0.0", "@effect/sql-pg": ">=4.0.0-beta.83 || >=4.0.0", "@effect/sql-pglite": ">=4.0.0-beta.83 || >=4.0.0", "@effect/sql-sqlite-bun": ">=4.0.0-beta.83 || >=4.0.0", "@effect/sql-sqlite-do": ">=4.0.0-beta.83 || >=4.0.0", "@effect/sql-sqlite-node": ">=4.0.0-beta.83 || >=4.0.0", "@effect/sql-sqlite-wasm": ">=4.0.0-beta.83 || >=4.0.0", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@sinclair/typebox": ">=0.34.8", "@sqlitecloud/drivers": ">=1.0.653", "@tidbcloud/serverless": "*", "@tursodatabase/database": ">=0.6.0-pre.28 || >=0.6.0", "@tursodatabase/database-common": ">=0.6.0-pre.28 || >=0.6.0", "@tursodatabase/database-wasm": ">=0.6.0-pre.28 || >=0.6.0", "@tursodatabase/serverless": ">=1.1.3", "@tursodatabase/sync": ">=0.6.0-pre.28 || >=0.6.0", "@types/better-sqlite3": "*", "@types/mssql": "^9.1.4", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "arktype": ">=2.0.0", "better-sqlite3": ">=9.3.0", "bun-types": "*", "effect": ">=4.0.0-beta.83 || >=4.0.0", "expo-sqlite": ">=14.0.0", "mssql": "^11.0.1", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5", "typebox": ">=1.0.0", "valibot": ">=1.0.0-beta.7", "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@effect/sql-d1", "@effect/sql-libsql", "@effect/sql-mysql2", "@effect/sql-pg", "@effect/sql-pglite", "@effect/sql-sqlite-bun", "@effect/sql-sqlite-do", "@effect/sql-sqlite-node", "@effect/sql-sqlite-wasm", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@sinclair/typebox", "@sqlitecloud/drivers", "@tidbcloud/serverless", "@tursodatabase/database", "@tursodatabase/database-common", "@tursodatabase/database-wasm", "@tursodatabase/serverless", "@tursodatabase/sync", "@types/better-sqlite3", "@types/mssql", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "arktype", "better-sqlite3", "bun-types", "effect", "expo-sqlite", "mssql", "mysql2", "pg", "postgres", "sql.js", "sqlite3", "typebox", "valibot", "zod"] }, "sha512-BT+pf+qoiYHqltoA88Jmf6ilGMXPlpfE0hEJKc2adRtMCAl25Swk/t5gXcWxZNAwdtf3F5gCd2FpeOyP/pT0Hw=="], + "drizzle-orm": ["drizzle-orm@1.0.0-rc.6", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@aws/aurora-dsql-node-postgres-connector": ">=0.1.9", "@aws/aurora-dsql-postgresjs-connector": ">=0.3.0", "@cloudflare/workers-types": ">=4", "@effect/sql-d1": ">=4.0.0", "@effect/sql-libsql": ">=4.0.0", "@effect/sql-mysql2": ">=4.0.0", "@effect/sql-pg": ">=4.0.0", "@effect/sql-pglite": ">=4.0.0", "@effect/sql-sqlite-bun": ">=4.0.0", "@effect/sql-sqlite-do": ">=4.0.0", "@effect/sql-sqlite-node": ">=4.0.0", "@effect/sql-sqlite-wasm": ">=4.0.0", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=17", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@sinclair/typebox": ">=0.34.8", "@sqlitecloud/drivers": ">=1.0.653", "@tidbcloud/serverless": "*", "@tursodatabase/database": ">=0.7.1", "@tursodatabase/database-common": ">=0.7.1", "@tursodatabase/database-wasm": ">=0.7.1", "@tursodatabase/serverless": ">=1.4.0", "@tursodatabase/sync": ">=0.7.1", "@types/better-sqlite3": "*", "@types/mssql": ">=9.1.11", "@types/pg": "*", "@types/sql.js": "*", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "arktype": ">=2.0.0", "better-sqlite3": ">=9.3.0", "bun-types": "*", "effect": ">=4.0.0", "expo-sqlite": ">=14.0.0", "mssql": ">=11.0.1", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5", "typebox": ">=1.2.0", "valibot": ">=1.0.0-beta.7", "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@aws/aurora-dsql-node-postgres-connector", "@aws/aurora-dsql-postgresjs-connector", "@cloudflare/workers-types", "@effect/sql-d1", "@effect/sql-libsql", "@effect/sql-mysql2", "@effect/sql-pg", "@effect/sql-pglite", "@effect/sql-sqlite-bun", "@effect/sql-sqlite-do", "@effect/sql-sqlite-node", "@effect/sql-sqlite-wasm", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@sinclair/typebox", "@sqlitecloud/drivers", "@tidbcloud/serverless", "@tursodatabase/database", "@tursodatabase/database-common", "@tursodatabase/database-wasm", "@tursodatabase/serverless", "@tursodatabase/sync", "@types/better-sqlite3", "@types/mssql", "@types/pg", "@types/sql.js", "@vercel/postgres", "@xata.io/client", "arktype", "better-sqlite3", "bun-types", "effect", "expo-sqlite", "mssql", "mysql2", "pg", "postgres", "sql.js", "sqlite3", "typebox", "valibot", "zod"] }, "sha512-z/2UDIuD/IbA862MbficiLc0BZodaWoXqSrv3Opdi1k0lx5oK4iX+rayJ1RwHbwFvvDGJpVP2mTYwxefar1xEg=="], "duron": ["duron@workspace:packages/duron"], @@ -1036,8 +1032,6 @@ "get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="], - "get-tsconfig": ["get-tsconfig@4.14.0", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA=="], - "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], "globrex": ["globrex@0.1.2", "", {}, "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg=="], @@ -1106,8 +1100,6 @@ "js-yaml": ["js-yaml@4.3.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q=="], - "jsbi": ["jsbi@4.3.2", "", {}, "sha512-9fqMSQbhJykSeii05nxKl4m6Eqn2P6rOlYiS+C5Dr/HPIU/7yZxu5qzbs40tgaFORiw2Amd0mirjxatXYMkIew=="], - "jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="], "json-schema": ["json-schema@0.4.0", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="], @@ -1416,8 +1408,6 @@ "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], - "resolve-pkg-maps": ["resolve-pkg-maps@1.0.0", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="], - "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], "rollup": ["rollup@4.62.2", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.2", "@rollup/rollup-android-arm64": "4.62.2", "@rollup/rollup-darwin-arm64": "4.62.2", "@rollup/rollup-darwin-x64": "4.62.2", "@rollup/rollup-freebsd-arm64": "4.62.2", "@rollup/rollup-freebsd-x64": "4.62.2", "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", "@rollup/rollup-linux-arm-musleabihf": "4.62.2", "@rollup/rollup-linux-arm64-gnu": "4.62.2", "@rollup/rollup-linux-arm64-musl": "4.62.2", "@rollup/rollup-linux-loong64-gnu": "4.62.2", "@rollup/rollup-linux-loong64-musl": "4.62.2", "@rollup/rollup-linux-ppc64-gnu": "4.62.2", "@rollup/rollup-linux-ppc64-musl": "4.62.2", "@rollup/rollup-linux-riscv64-gnu": "4.62.2", "@rollup/rollup-linux-riscv64-musl": "4.62.2", "@rollup/rollup-linux-s390x-gnu": "4.62.2", "@rollup/rollup-linux-x64-gnu": "4.62.2", "@rollup/rollup-linux-x64-musl": "4.62.2", "@rollup/rollup-openbsd-x64": "4.62.2", "@rollup/rollup-openharmony-arm64": "4.62.2", "@rollup/rollup-win32-arm64-msvc": "4.62.2", "@rollup/rollup-win32-ia32-msvc": "4.62.2", "@rollup/rollup-win32-x64-gnu": "4.62.2", "@rollup/rollup-win32-x64-msvc": "4.62.2", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA=="], @@ -1608,8 +1598,6 @@ "docs/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], - "drizzle-kit/esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="], - "examples/@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], "fumadocs-ui/fumadocs-core": ["fumadocs-core@16.1.0", "", { "dependencies": { "@formatjs/intl-localematcher": "^0.6.2", "@orama/orama": "^3.1.16", "@shikijs/rehype": "^3.15.0", "@shikijs/transformers": "^3.15.0", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "hast-util-to-estree": "^3.1.3", "hast-util-to-jsx-runtime": "^2.3.6", "image-size": "^2.0.2", "negotiator": "^1.0.0", "npm-to-yarn": "^3.0.1", "path-to-regexp": "^8.3.0", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-rehype": "^11.1.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^3.15.0", "unist-util-visit": "^5.0.0" }, "peerDependencies": { "@mixedbread/sdk": "^0.19.0", "@orama/core": "1.x.x", "@tanstack/react-router": "1.x.x", "@types/react": "*", "algoliasearch": "5.x.x", "lucide-react": "*", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "react-router": "7.x.x", "waku": "^0.26.0 || ^0.27.0" }, "optionalPeers": ["@mixedbread/sdk", "@orama/core", "@tanstack/react-router", "@types/react", "algoliasearch", "lucide-react", "next", "react", "react-dom", "react-router", "waku"] }, "sha512-5pbO2bOGc/xlb2yLQSy6Oag8mvD5CNf5HzQIG80HjZzLXYWEOHW8yovRKnWKRF9gAibn6WHnbssj3YPAlitV/A=="], @@ -1638,58 +1626,6 @@ "compression/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], - "drizzle-kit/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="], - - "drizzle-kit/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="], - - "drizzle-kit/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.12", "", { "os": "android", "cpu": "arm64" }, "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg=="], - - "drizzle-kit/esbuild/@esbuild/android-x64": ["@esbuild/android-x64@0.25.12", "", { "os": "android", "cpu": "x64" }, "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg=="], - - "drizzle-kit/esbuild/@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg=="], - - "drizzle-kit/esbuild/@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA=="], - - "drizzle-kit/esbuild/@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.12", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg=="], - - "drizzle-kit/esbuild/@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.12", "", { "os": "freebsd", "cpu": "x64" }, "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ=="], - - "drizzle-kit/esbuild/@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.12", "", { "os": "linux", "cpu": "arm" }, "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw=="], - - "drizzle-kit/esbuild/@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ=="], - - "drizzle-kit/esbuild/@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.12", "", { "os": "linux", "cpu": "ia32" }, "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA=="], - - "drizzle-kit/esbuild/@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng=="], - - "drizzle-kit/esbuild/@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw=="], - - "drizzle-kit/esbuild/@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.12", "", { "os": "linux", "cpu": "ppc64" }, "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA=="], - - "drizzle-kit/esbuild/@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w=="], - - "drizzle-kit/esbuild/@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.12", "", { "os": "linux", "cpu": "s390x" }, "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg=="], - - "drizzle-kit/esbuild/@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.12", "", { "os": "linux", "cpu": "x64" }, "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw=="], - - "drizzle-kit/esbuild/@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.12", "", { "os": "none", "cpu": "arm64" }, "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg=="], - - "drizzle-kit/esbuild/@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.12", "", { "os": "none", "cpu": "x64" }, "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ=="], - - "drizzle-kit/esbuild/@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.12", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A=="], - - "drizzle-kit/esbuild/@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.12", "", { "os": "openbsd", "cpu": "x64" }, "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw=="], - - "drizzle-kit/esbuild/@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.25.12", "", { "os": "none", "cpu": "arm64" }, "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg=="], - - "drizzle-kit/esbuild/@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.12", "", { "os": "sunos", "cpu": "x64" }, "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w=="], - - "drizzle-kit/esbuild/@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg=="], - - "drizzle-kit/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.12", "", { "os": "win32", "cpu": "ia32" }, "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ=="], - - "drizzle-kit/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="], - "examples/@types/bun/bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], "shared-actions/@types/bun/bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], diff --git a/packages/duron/package.json b/packages/duron/package.json index 2d4a359..5d70c5d 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -100,8 +100,8 @@ "@opentelemetry/core": "^2.4.0", "@types/bun": "latest", "@types/node": "^24.0.15", - "drizzle-kit": "^1.0.0-rc.4", - "drizzle-orm": "^1.0.0-rc.4", + "drizzle-kit": "1.0.0-rc.6", + "drizzle-orm": "1.0.0-rc.6", "postgres": "^4.1.1", "typescript": "^7" } diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 9a45752..763039f 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1639,11 +1639,12 @@ export abstract class PostgresBaseAdapter< delayed_ms: delayMs, retries_count: sql`${jobStepsTable.retries_count} + 1`, expires_at: sql`now() + (${jobStepsTable.timeout_ms} || ' milliseconds')::interval + (${delayMs} || ' milliseconds')::interval`, + // The error JSON parameter is typed text: postgres.js would JSON-encode a jsonb-typed string again. history_failed_attempts: sql`COALESCE(${jobStepsTable.history_failed_attempts}, '{}'::jsonb) || jsonb_build_object( extract(epoch from now())::text, jsonb_build_object( 'failedAt', now(), - 'error', ${JSON.stringify(error)}::jsonb, + 'error', ${JSON.stringify(error)}::text::jsonb, 'delayedMs', ${delayMs}::integer ) )`, @@ -2419,8 +2420,9 @@ export abstract class PostgresBaseAdapter< )` } else { // For non-string values, use exact containment - // Note: JSON.stringify is safe here because drizzle-orm parameterizes the value - return sql`${arrayPath} @> ${JSON.stringify([arrayValue])}::jsonb` + // Note: JSON.stringify is safe here because drizzle-orm parameterizes the value. + // Type the parameter as text: postgres.js would JSON-encode a jsonb-typed string again. + return sql`${arrayPath} @> ${JSON.stringify([arrayValue])}::text::jsonb` } }) diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index 46a4261..617e351 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -646,6 +646,7 @@ function runAdapterTests(adapterFactory: AdapterFactory) { return ids.toSorted() } + // Seed JSON as `${text}::text::jsonb`: postgres.js serializes a jsonb-typed string parameter again. async function seedListingJob(id: string, storage: 'active' | 'archive', fields: SQL) { const { db } = adapter as unknown as { db: { execute: (query: SQL) => Promise } @@ -908,7 +909,7 @@ function runAdapterTests(adapterFactory: AdapterFactory) { await seedListingJob( id, storage, - sql`output = ${JSON.stringify({ payload: 'o'.repeat(16_384) })}::jsonb`, + sql`output = ${JSON.stringify({ payload: 'o'.repeat(16_384) })}::text::jsonb`, ) } const payloadBatches: number[] = [] @@ -1044,8 +1045,8 @@ function runAdapterTests(adapterFactory: AdapterFactory) { id, storage, sql` - input = ${JSON.stringify(inputs[rank])}::jsonb, - output = ${JSON.stringify({ text: rank === 1 ? 'running foxes' : 'unrelated' })}::jsonb, + input = ${JSON.stringify(inputs[rank])}::text::jsonb, + output = ${JSON.stringify({ text: rank === 1 ? 'running foxes' : 'unrelated' })}::text::jsonb, group_key = ${rank === 1 ? 'elsewhere' : 'MiXeD-group'}, description = ${rank === 1 ? 'haystack' : 'MiXeD-needle'}, client_id = ${rank === 1 ? 'client-b' : 'client-a'}, From 9c57982c8893178f1c709a092d4333d04450bbb5 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 21:46:44 -0300 Subject: [PATCH 031/100] chore: upgrade drizzle-kit snapshot to format 10 drizzle-kit 1.0.0-rc.6 refuses to generate from a format 8 snapshot ("run drizzle-kit up"). Ran drizzle-kit up and formatted the file with oxfmt. generate:postgres now reports "No schema changes". The runtime migrator reads only migration.sql, so this file does not affect migrations at runtime. --- .../snapshot.json | 1301 +++++++++++------ 1 file changed, 835 insertions(+), 466 deletions(-) diff --git a/packages/duron/migrations/postgres/20260721213101_fair_ghost_rider/snapshot.json b/packages/duron/migrations/postgres/20260721213101_fair_ghost_rider/snapshot.json index 32dc804..d74891e 100644 --- a/packages/duron/migrations/postgres/20260721213101_fair_ghost_rider/snapshot.json +++ b/packages/duron/migrations/postgres/20260721213101_fair_ghost_rider/snapshot.json @@ -1,44 +1,438 @@ { - "version": "8", + "type": "base", + "version": "10", "dialect": "postgres", "id": "2669b14e-39af-408d-bed1-71acb119e105", "prevIds": ["00000000-0000-0000-0000-000000000000"], + "footprints": [ + { + "statementType": "create_schema", + "statementTarget": ["schema", "duron"], + "writes": ["s|sch|duron", "n|sch|duron", "e|sch|duron"] + }, + { + "statementType": "create_table", + "statementTarget": ["table", "duron", "clients"], + "writes": [ + "s|tbl|duron.clients", + "n|tbl|duron.clients", + "e|tbl|duron.clients", + "n|rel|duron.clients", + "n|type|duron.clients", + "n|rel|duron.clients_pkey" + ], + "reads": ["n|sch|duron"] + }, + { + "statementType": "create_table", + "statementTarget": ["table", "duron", "job_steps_active"], + "writes": [ + "s|tbl|duron.job_steps_active", + "n|tbl|duron.job_steps_active", + "e|tbl|duron.job_steps_active", + "n|rel|duron.job_steps_active", + "n|type|duron.job_steps_active", + "n|rel|duron.job_steps_active_pkey", + "n|rel|duron.unique_job_step_active_name_parent" + ], + "reads": ["n|sch|duron"] + }, + { + "statementType": "create_table", + "statementTarget": ["table", "duron", "job_steps_archive"], + "writes": [ + "s|tbl|duron.job_steps_archive", + "n|tbl|duron.job_steps_archive", + "e|tbl|duron.job_steps_archive", + "n|rel|duron.job_steps_archive", + "n|type|duron.job_steps_archive", + "n|rel|duron.job_steps_archive_pkey" + ], + "reads": ["n|sch|duron"] + }, + { + "statementType": "create_table", + "statementTarget": ["table", "duron", "jobs_active"], + "writes": [ + "s|tbl|duron.jobs_active", + "n|tbl|duron.jobs_active", + "e|tbl|duron.jobs_active", + "n|rel|duron.jobs_active", + "n|type|duron.jobs_active", + "n|rel|duron.jobs_active_pkey" + ], + "reads": ["n|sch|duron"] + }, + { + "statementType": "create_table", + "statementTarget": ["table", "duron", "jobs_archive"], + "writes": [ + "s|tbl|duron.jobs_archive", + "n|tbl|duron.jobs_archive", + "e|tbl|duron.jobs_archive", + "n|rel|duron.jobs_archive", + "n|type|duron.jobs_archive", + "n|rel|duron.jobs_archive_pkey" + ], + "reads": ["n|sch|duron"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "job_steps_active", "idx_job_steps_active_job_id"], + "writes": [ + "s|idx|duron.idx_job_steps_active_job_id", + "n|idx|duron.idx_job_steps_active_job_id", + "e|idx|duron.idx_job_steps_active_job_id", + "n|rel|duron.idx_job_steps_active_job_id" + ], + "reads": [ + "n|tbl|duron.job_steps_active", + "n|sch|duron", + "n|col|duron.job_steps_active.job_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "job_steps_active", "idx_job_steps_active_status"], + "writes": [ + "s|idx|duron.idx_job_steps_active_status", + "n|idx|duron.idx_job_steps_active_status", + "e|idx|duron.idx_job_steps_active_status", + "n|rel|duron.idx_job_steps_active_status" + ], + "reads": [ + "n|tbl|duron.job_steps_active", + "n|sch|duron", + "n|col|duron.job_steps_active.status" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "job_steps_active", "idx_job_steps_active_name"], + "writes": [ + "s|idx|duron.idx_job_steps_active_name", + "n|idx|duron.idx_job_steps_active_name", + "e|idx|duron.idx_job_steps_active_name", + "n|rel|duron.idx_job_steps_active_name" + ], + "reads": ["n|tbl|duron.job_steps_active", "n|sch|duron", "n|col|duron.job_steps_active.name"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "job_steps_active", "idx_job_steps_active_expires_at"], + "writes": [ + "s|idx|duron.idx_job_steps_active_expires_at", + "n|idx|duron.idx_job_steps_active_expires_at", + "e|idx|duron.idx_job_steps_active_expires_at", + "n|rel|duron.idx_job_steps_active_expires_at" + ], + "reads": [ + "n|tbl|duron.job_steps_active", + "n|sch|duron", + "n|col|duron.job_steps_active.expires_at" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "duron", + "job_steps_active", + "idx_job_steps_active_parent_step_id" + ], + "writes": [ + "s|idx|duron.idx_job_steps_active_parent_step_id", + "n|idx|duron.idx_job_steps_active_parent_step_id", + "e|idx|duron.idx_job_steps_active_parent_step_id", + "n|rel|duron.idx_job_steps_active_parent_step_id" + ], + "reads": [ + "n|tbl|duron.job_steps_active", + "n|sch|duron", + "n|col|duron.job_steps_active.parent_step_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "job_steps_archive", "idx_job_steps_archive_job_id"], + "writes": [ + "s|idx|duron.idx_job_steps_archive_job_id", + "n|idx|duron.idx_job_steps_archive_job_id", + "e|idx|duron.idx_job_steps_archive_job_id", + "n|rel|duron.idx_job_steps_archive_job_id" + ], + "reads": [ + "n|tbl|duron.job_steps_archive", + "n|sch|duron", + "n|col|duron.job_steps_archive.job_id" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "duron", + "job_steps_archive", + "idx_job_steps_archive_job_finished_at" + ], + "writes": [ + "s|idx|duron.idx_job_steps_archive_job_finished_at", + "n|idx|duron.idx_job_steps_archive_job_finished_at", + "e|idx|duron.idx_job_steps_archive_job_finished_at", + "n|rel|duron.idx_job_steps_archive_job_finished_at" + ], + "reads": [ + "n|tbl|duron.job_steps_archive", + "n|sch|duron", + "n|col|duron.job_steps_archive.job_finished_at" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "job_steps_archive", "idx_job_steps_archive_name"], + "writes": [ + "s|idx|duron.idx_job_steps_archive_name", + "n|idx|duron.idx_job_steps_archive_name", + "e|idx|duron.idx_job_steps_archive_name", + "n|rel|duron.idx_job_steps_archive_name" + ], + "reads": [ + "n|tbl|duron.job_steps_archive", + "n|sch|duron", + "n|col|duron.job_steps_archive.name" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_action_name"], + "writes": [ + "s|idx|duron.idx_jobs_active_action_name", + "n|idx|duron.idx_jobs_active_action_name", + "e|idx|duron.idx_jobs_active_action_name", + "n|rel|duron.idx_jobs_active_action_name" + ], + "reads": ["n|tbl|duron.jobs_active", "n|sch|duron", "n|col|duron.jobs_active.action_name"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_status"], + "writes": [ + "s|idx|duron.idx_jobs_active_status", + "n|idx|duron.idx_jobs_active_status", + "e|idx|duron.idx_jobs_active_status", + "n|rel|duron.idx_jobs_active_status" + ], + "reads": ["n|tbl|duron.jobs_active", "n|sch|duron", "n|col|duron.jobs_active.status"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_group_key"], + "writes": [ + "s|idx|duron.idx_jobs_active_group_key", + "n|idx|duron.idx_jobs_active_group_key", + "e|idx|duron.idx_jobs_active_group_key", + "n|rel|duron.idx_jobs_active_group_key" + ], + "reads": ["n|tbl|duron.jobs_active", "n|sch|duron", "n|col|duron.jobs_active.group_key"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_expires_at"], + "writes": [ + "s|idx|duron.idx_jobs_active_expires_at", + "n|idx|duron.idx_jobs_active_expires_at", + "e|idx|duron.idx_jobs_active_expires_at", + "n|rel|duron.idx_jobs_active_expires_at" + ], + "reads": ["n|tbl|duron.jobs_active", "n|sch|duron", "n|col|duron.jobs_active.expires_at"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_client_id"], + "writes": [ + "s|idx|duron.idx_jobs_active_client_id", + "n|idx|duron.idx_jobs_active_client_id", + "e|idx|duron.idx_jobs_active_client_id", + "n|rel|duron.idx_jobs_active_client_id" + ], + "reads": ["n|tbl|duron.jobs_active", "n|sch|duron", "n|col|duron.jobs_active.client_id"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_checksum"], + "writes": [ + "s|idx|duron.idx_jobs_active_checksum", + "n|idx|duron.idx_jobs_active_checksum", + "e|idx|duron.idx_jobs_active_checksum", + "n|rel|duron.idx_jobs_active_checksum" + ], + "reads": ["n|tbl|duron.jobs_active", "n|sch|duron", "n|col|duron.jobs_active.checksum"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_action_group"], + "writes": [ + "s|idx|duron.idx_jobs_active_action_group", + "n|idx|duron.idx_jobs_active_action_group", + "e|idx|duron.idx_jobs_active_action_group", + "n|rel|duron.idx_jobs_active_action_group" + ], + "reads": [ + "n|tbl|duron.jobs_active", + "n|sch|duron", + "n|col|duron.jobs_active.action_name", + "n|col|duron.jobs_active.group_key" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_group_key"], + "writes": [ + "s|idx|duron.idx_jobs_archive_group_key", + "n|idx|duron.idx_jobs_archive_group_key", + "e|idx|duron.idx_jobs_archive_group_key", + "n|rel|duron.idx_jobs_archive_group_key" + ], + "reads": ["n|tbl|duron.jobs_archive", "n|sch|duron", "n|col|duron.jobs_archive.group_key"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_action_name"], + "writes": [ + "s|idx|duron.idx_jobs_archive_action_name", + "n|idx|duron.idx_jobs_archive_action_name", + "e|idx|duron.idx_jobs_archive_action_name", + "n|rel|duron.idx_jobs_archive_action_name" + ], + "reads": ["n|tbl|duron.jobs_archive", "n|sch|duron", "n|col|duron.jobs_archive.action_name"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_finished_at"], + "writes": [ + "s|idx|duron.idx_jobs_archive_finished_at", + "n|idx|duron.idx_jobs_archive_finished_at", + "e|idx|duron.idx_jobs_archive_finished_at", + "n|rel|duron.idx_jobs_archive_finished_at" + ], + "reads": ["n|tbl|duron.jobs_archive", "n|sch|duron", "n|col|duron.jobs_archive.finished_at"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_action_group"], + "writes": [ + "s|idx|duron.idx_jobs_archive_action_group", + "n|idx|duron.idx_jobs_archive_action_group", + "e|idx|duron.idx_jobs_archive_action_group", + "n|rel|duron.idx_jobs_archive_action_group" + ], + "reads": [ + "n|tbl|duron.jobs_archive", + "n|sch|duron", + "n|col|duron.jobs_archive.action_name", + "n|col|duron.jobs_archive.group_key" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_input_fts"], + "writes": [ + "s|idx|duron.idx_jobs_archive_input_fts", + "n|idx|duron.idx_jobs_archive_input_fts", + "e|idx|duron.idx_jobs_archive_input_fts", + "n|rel|duron.idx_jobs_archive_input_fts" + ], + "reads": ["n|tbl|duron.jobs_archive", "n|sch|duron"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_output_fts"], + "writes": [ + "s|idx|duron.idx_jobs_archive_output_fts", + "n|idx|duron.idx_jobs_archive_output_fts", + "e|idx|duron.idx_jobs_archive_output_fts", + "n|rel|duron.idx_jobs_archive_output_fts" + ], + "reads": ["n|tbl|duron.jobs_archive", "n|sch|duron"] + }, + { + "statementType": "create_fk", + "statementTarget": ["table", "duron", "job_steps_active"], + "writes": [ + "s|fk|duron.job_steps_active.job_steps_active_job_id_jobs_active_id_fkey", + "n|fk|duron.job_steps_active.job_steps_active_job_id_jobs_active_id_fkey", + "e|fk|duron.job_steps_active.job_steps_active_job_id_jobs_active_id_fkey", + "n|con|duron.job_steps_active.job_steps_active_job_id_jobs_active_id_fkey" + ], + "reads": [ + "n|tbl|duron.job_steps_active", + "n|sch|duron", + "n|tbl|duron.jobs_active", + "n|sch|duron", + "n|col|duron.job_steps_active.job_id", + "n|col|duron.jobs_active.id", + "e|uniqueness|duron.jobs_active.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": ["table", "duron", "job_steps_archive"], + "writes": [ + "s|fk|duron.job_steps_archive.job_steps_archive_job_id_jobs_archive_id_fkey", + "n|fk|duron.job_steps_archive.job_steps_archive_job_id_jobs_archive_id_fkey", + "e|fk|duron.job_steps_archive.job_steps_archive_job_id_jobs_archive_id_fkey", + "n|con|duron.job_steps_archive.job_steps_archive_job_id_jobs_archive_id_fkey" + ], + "reads": [ + "n|tbl|duron.job_steps_archive", + "n|sch|duron", + "n|tbl|duron.jobs_archive", + "n|sch|duron", + "n|col|duron.job_steps_archive.job_id", + "n|col|duron.jobs_archive.id", + "e|uniqueness|duron.jobs_archive.id" + ] + } + ], "ddl": [ { "name": "duron", "entityType": "schemas" }, { - "isRlsEnabled": false, + "schema": "duron", "name": "clients", - "entityType": "tables", - "schema": "duron" + "isRlsEnabled": false, + "entityType": "tables" }, { - "isRlsEnabled": false, + "schema": "duron", "name": "job_steps_active", - "entityType": "tables", - "schema": "duron" + "isRlsEnabled": false, + "entityType": "tables" }, { - "isRlsEnabled": false, + "schema": "duron", "name": "job_steps_archive", - "entityType": "tables", - "schema": "duron" + "isRlsEnabled": false, + "entityType": "tables" }, { - "isRlsEnabled": false, + "schema": "duron", "name": "jobs_active", - "entityType": "tables", - "schema": "duron" + "isRlsEnabled": false, + "entityType": "tables" }, { - "isRlsEnabled": false, + "schema": "duron", "name": "jobs_archive", - "entityType": "tables", - "schema": "duron" + "isRlsEnabled": false, + "entityType": "tables" }, { + "schema": "duron", + "table": "clients", + "name": "client_id", "type": "text", "typeSchema": null, "notNull": true, @@ -46,12 +440,12 @@ "default": null, "generated": null, "identity": null, - "name": "client_id", - "entityType": "columns", - "schema": "duron", - "table": "clients" + "entityType": "columns" }, { + "schema": "duron", + "table": "clients", + "name": "last_seen_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -59,12 +453,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "last_seen_at", - "entityType": "columns", - "schema": "duron", - "table": "clients" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "id", "type": "uuid", "typeSchema": null, "notNull": true, @@ -72,12 +466,12 @@ "default": "gen_random_uuid()", "generated": null, "identity": null, - "name": "id", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "job_id", "type": "uuid", "typeSchema": null, "notNull": true, @@ -85,12 +479,12 @@ "default": null, "generated": null, "identity": null, - "name": "job_id", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "parent_step_id", "type": "uuid", "typeSchema": null, "notNull": false, @@ -98,12 +492,12 @@ "default": null, "generated": null, "identity": null, - "name": "parent_step_id", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "parallel", "type": "boolean", "typeSchema": null, "notNull": true, @@ -111,12 +505,12 @@ "default": "false", "generated": null, "identity": null, - "name": "parallel", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "name", "type": "text", "typeSchema": null, "notNull": true, @@ -124,12 +518,12 @@ "default": null, "generated": null, "identity": null, - "name": "name", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "status", "type": "text", "typeSchema": null, "notNull": true, @@ -137,12 +531,12 @@ "default": "'active'", "generated": null, "identity": null, - "name": "status", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "output", "type": "jsonb", "typeSchema": null, "notNull": false, @@ -150,12 +544,12 @@ "default": null, "generated": null, "identity": null, - "name": "output", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "error", "type": "jsonb", "typeSchema": null, "notNull": false, @@ -163,12 +557,12 @@ "default": null, "generated": null, "identity": null, - "name": "error", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "started_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -176,12 +570,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "started_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "finished_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -189,12 +583,12 @@ "default": null, "generated": null, "identity": null, - "name": "finished_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "timeout_ms", "type": "integer", "typeSchema": null, "notNull": true, @@ -202,12 +596,12 @@ "default": null, "generated": null, "identity": null, - "name": "timeout_ms", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "expires_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -215,12 +609,12 @@ "default": null, "generated": null, "identity": null, - "name": "expires_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "retries_limit", "type": "integer", "typeSchema": null, "notNull": true, @@ -228,12 +622,12 @@ "default": "0", "generated": null, "identity": null, - "name": "retries_limit", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "retries_count", "type": "integer", "typeSchema": null, "notNull": true, @@ -241,12 +635,12 @@ "default": "0", "generated": null, "identity": null, - "name": "retries_count", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "delayed_ms", "type": "integer", "typeSchema": null, "notNull": false, @@ -254,12 +648,12 @@ "default": null, "generated": null, "identity": null, - "name": "delayed_ms", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "history_failed_attempts", "type": "jsonb", "typeSchema": null, "notNull": true, @@ -267,12 +661,12 @@ "default": "'{}'", "generated": null, "identity": null, - "name": "history_failed_attempts", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "created_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -280,12 +674,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "created_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "updated_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -293,12 +687,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "updated_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "id", "type": "uuid", "typeSchema": null, "notNull": true, @@ -306,12 +700,12 @@ "default": null, "generated": null, "identity": null, - "name": "id", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "job_id", "type": "uuid", "typeSchema": null, "notNull": true, @@ -319,12 +713,12 @@ "default": null, "generated": null, "identity": null, - "name": "job_id", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "parent_step_id", "type": "uuid", "typeSchema": null, "notNull": false, @@ -332,12 +726,12 @@ "default": null, "generated": null, "identity": null, - "name": "parent_step_id", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "parallel", "type": "boolean", "typeSchema": null, "notNull": true, @@ -345,12 +739,12 @@ "default": "false", "generated": null, "identity": null, - "name": "parallel", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "name", "type": "text", "typeSchema": null, "notNull": true, @@ -358,12 +752,12 @@ "default": null, "generated": null, "identity": null, - "name": "name", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "status", "type": "text", "typeSchema": null, "notNull": true, @@ -371,12 +765,12 @@ "default": "'active'", "generated": null, "identity": null, - "name": "status", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "output", "type": "jsonb", "typeSchema": null, "notNull": false, @@ -384,12 +778,12 @@ "default": null, "generated": null, "identity": null, - "name": "output", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "error", "type": "jsonb", "typeSchema": null, "notNull": false, @@ -397,12 +791,12 @@ "default": null, "generated": null, "identity": null, - "name": "error", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "started_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -410,12 +804,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "started_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "finished_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -423,12 +817,12 @@ "default": null, "generated": null, "identity": null, - "name": "finished_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "timeout_ms", "type": "integer", "typeSchema": null, "notNull": true, @@ -436,12 +830,12 @@ "default": null, "generated": null, "identity": null, - "name": "timeout_ms", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "expires_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -449,12 +843,12 @@ "default": null, "generated": null, "identity": null, - "name": "expires_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "retries_limit", "type": "integer", "typeSchema": null, "notNull": true, @@ -462,12 +856,12 @@ "default": "0", "generated": null, "identity": null, - "name": "retries_limit", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "retries_count", "type": "integer", "typeSchema": null, "notNull": true, @@ -475,12 +869,12 @@ "default": "0", "generated": null, "identity": null, - "name": "retries_count", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "delayed_ms", "type": "integer", "typeSchema": null, "notNull": false, @@ -488,12 +882,12 @@ "default": null, "generated": null, "identity": null, - "name": "delayed_ms", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "history_failed_attempts", "type": "jsonb", "typeSchema": null, "notNull": true, @@ -501,12 +895,12 @@ "default": "'{}'", "generated": null, "identity": null, - "name": "history_failed_attempts", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "created_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -514,12 +908,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "created_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "updated_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -527,12 +921,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "updated_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "job_finished_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -540,12 +934,12 @@ "default": null, "generated": null, "identity": null, - "name": "job_finished_at", - "entityType": "columns", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "id", "type": "uuid", "typeSchema": null, "notNull": true, @@ -553,12 +947,12 @@ "default": "gen_random_uuid()", "generated": null, "identity": null, - "name": "id", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "action_name", "type": "text", "typeSchema": null, "notNull": true, @@ -566,12 +960,12 @@ "default": null, "generated": null, "identity": null, - "name": "action_name", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "group_key", "type": "text", "typeSchema": null, "notNull": true, @@ -579,12 +973,12 @@ "default": null, "generated": null, "identity": null, - "name": "group_key", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "description", "type": "text", "typeSchema": null, "notNull": false, @@ -592,12 +986,12 @@ "default": null, "generated": null, "identity": null, - "name": "description", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "status", "type": "text", "typeSchema": null, "notNull": true, @@ -605,12 +999,12 @@ "default": "'created'", "generated": null, "identity": null, - "name": "status", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "checksum", "type": "text", "typeSchema": null, "notNull": true, @@ -618,12 +1012,12 @@ "default": null, "generated": null, "identity": null, - "name": "checksum", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "input", "type": "jsonb", "typeSchema": null, "notNull": true, @@ -631,12 +1025,12 @@ "default": "'{}'", "generated": null, "identity": null, - "name": "input", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "output", "type": "jsonb", "typeSchema": null, "notNull": false, @@ -644,12 +1038,12 @@ "default": null, "generated": null, "identity": null, - "name": "output", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "error", "type": "jsonb", "typeSchema": null, "notNull": false, @@ -657,12 +1051,12 @@ "default": null, "generated": null, "identity": null, - "name": "error", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "timeout_ms", "type": "integer", "typeSchema": null, "notNull": true, @@ -670,12 +1064,12 @@ "default": null, "generated": null, "identity": null, - "name": "timeout_ms", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "expires_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -683,12 +1077,12 @@ "default": null, "generated": null, "identity": null, - "name": "expires_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "started_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -696,12 +1090,12 @@ "default": null, "generated": null, "identity": null, - "name": "started_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "finished_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -709,12 +1103,12 @@ "default": null, "generated": null, "identity": null, - "name": "finished_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "client_id", "type": "text", "typeSchema": null, "notNull": false, @@ -722,12 +1116,12 @@ "default": null, "generated": null, "identity": null, - "name": "client_id", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "concurrency_limit", "type": "integer", "typeSchema": null, "notNull": true, @@ -735,12 +1129,12 @@ "default": null, "generated": null, "identity": null, - "name": "concurrency_limit", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "concurrency_step_limit", "type": "integer", "typeSchema": null, "notNull": true, @@ -748,12 +1142,12 @@ "default": null, "generated": null, "identity": null, - "name": "concurrency_step_limit", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "created_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -761,12 +1155,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "created_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_active", + "name": "updated_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -774,12 +1168,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "updated_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_active" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "id", "type": "uuid", "typeSchema": null, "notNull": true, @@ -787,12 +1181,12 @@ "default": null, "generated": null, "identity": null, - "name": "id", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "action_name", "type": "text", "typeSchema": null, "notNull": true, @@ -800,12 +1194,12 @@ "default": null, "generated": null, "identity": null, - "name": "action_name", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "group_key", "type": "text", "typeSchema": null, "notNull": true, @@ -813,12 +1207,12 @@ "default": null, "generated": null, "identity": null, - "name": "group_key", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "description", "type": "text", "typeSchema": null, "notNull": false, @@ -826,12 +1220,12 @@ "default": null, "generated": null, "identity": null, - "name": "description", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "status", "type": "text", "typeSchema": null, "notNull": true, @@ -839,12 +1233,12 @@ "default": null, "generated": null, "identity": null, - "name": "status", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "checksum", "type": "text", "typeSchema": null, "notNull": true, @@ -852,12 +1246,12 @@ "default": null, "generated": null, "identity": null, - "name": "checksum", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "input", "type": "jsonb", "typeSchema": null, "notNull": true, @@ -865,12 +1259,12 @@ "default": "'{}'", "generated": null, "identity": null, - "name": "input", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "output", "type": "jsonb", "typeSchema": null, "notNull": false, @@ -878,12 +1272,12 @@ "default": null, "generated": null, "identity": null, - "name": "output", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "error", "type": "jsonb", "typeSchema": null, "notNull": false, @@ -891,12 +1285,12 @@ "default": null, "generated": null, "identity": null, - "name": "error", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "timeout_ms", "type": "integer", "typeSchema": null, "notNull": true, @@ -904,12 +1298,12 @@ "default": null, "generated": null, "identity": null, - "name": "timeout_ms", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "expires_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -917,12 +1311,12 @@ "default": null, "generated": null, "identity": null, - "name": "expires_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "started_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -930,12 +1324,12 @@ "default": null, "generated": null, "identity": null, - "name": "started_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "finished_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": false, @@ -943,12 +1337,12 @@ "default": null, "generated": null, "identity": null, - "name": "finished_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "client_id", "type": "text", "typeSchema": null, "notNull": false, @@ -956,12 +1350,12 @@ "default": null, "generated": null, "identity": null, - "name": "client_id", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "concurrency_limit", "type": "integer", "typeSchema": null, "notNull": true, @@ -969,12 +1363,12 @@ "default": null, "generated": null, "identity": null, - "name": "concurrency_limit", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "concurrency_step_limit", "type": "integer", "typeSchema": null, "notNull": true, @@ -982,12 +1376,12 @@ "default": null, "generated": null, "identity": null, - "name": "concurrency_step_limit", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "created_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -995,12 +1389,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "created_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "updated_at", "type": "timestamp with time zone", "typeSchema": null, "notNull": true, @@ -1008,12 +1402,12 @@ "default": "now()", "generated": null, "identity": null, - "name": "updated_at", - "entityType": "columns", - "schema": "duron", - "table": "jobs_archive" + "entityType": "columns" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "idx_job_steps_active_job_id", "nameExplicit": true, "columns": [ { @@ -1028,13 +1422,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_job_steps_active_job_id", - "entityType": "indexes", - "schema": "duron", - "table": "job_steps_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "idx_job_steps_active_status", "nameExplicit": true, "columns": [ { @@ -1049,13 +1442,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_job_steps_active_status", - "entityType": "indexes", - "schema": "duron", - "table": "job_steps_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "idx_job_steps_active_name", "nameExplicit": true, "columns": [ { @@ -1070,13 +1462,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_job_steps_active_name", - "entityType": "indexes", - "schema": "duron", - "table": "job_steps_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "idx_job_steps_active_expires_at", "nameExplicit": true, "columns": [ { @@ -1091,13 +1482,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_job_steps_active_expires_at", - "entityType": "indexes", - "schema": "duron", - "table": "job_steps_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "idx_job_steps_active_parent_step_id", "nameExplicit": true, "columns": [ { @@ -1112,13 +1502,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_job_steps_active_parent_step_id", - "entityType": "indexes", - "schema": "duron", - "table": "job_steps_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "idx_job_steps_archive_job_id", "nameExplicit": true, "columns": [ { @@ -1133,13 +1522,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_job_steps_archive_job_id", - "entityType": "indexes", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "idx_job_steps_archive_job_finished_at", "nameExplicit": true, "columns": [ { @@ -1154,13 +1542,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_job_steps_archive_job_finished_at", - "entityType": "indexes", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "idx_job_steps_archive_name", "nameExplicit": true, "columns": [ { @@ -1175,13 +1562,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_job_steps_archive_name", - "entityType": "indexes", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_action_name", "nameExplicit": true, "columns": [ { @@ -1196,13 +1582,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_active_action_name", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_status", "nameExplicit": true, "columns": [ { @@ -1217,13 +1602,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_active_status", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_group_key", "nameExplicit": true, "columns": [ { @@ -1238,13 +1622,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_active_group_key", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_expires_at", "nameExplicit": true, "columns": [ { @@ -1259,13 +1642,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_active_expires_at", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_client_id", "nameExplicit": true, "columns": [ { @@ -1280,13 +1662,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_active_client_id", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_checksum", "nameExplicit": true, "columns": [ { @@ -1301,13 +1682,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_active_checksum", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_action_group", "nameExplicit": true, "columns": [ { @@ -1329,13 +1709,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_active_action_group", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_active" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_group_key", "nameExplicit": true, "columns": [ { @@ -1350,13 +1729,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_archive_group_key", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_action_name", "nameExplicit": true, "columns": [ { @@ -1371,13 +1749,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_archive_action_name", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_finished_at", "nameExplicit": true, "columns": [ { @@ -1392,13 +1769,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_archive_finished_at", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_action_group", "nameExplicit": true, "columns": [ { @@ -1420,13 +1796,12 @@ "where": null, "with": "", "method": "btree", - "concurrently": false, - "name": "idx_jobs_archive_action_group", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_input_fts", "nameExplicit": true, "columns": [ { @@ -1441,13 +1816,12 @@ "where": null, "with": "", "method": "gin", - "concurrently": false, - "name": "idx_jobs_archive_input_fts", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_output_fts", "nameExplicit": true, "columns": [ { @@ -1462,13 +1836,12 @@ "where": null, "with": "", "method": "gin", - "concurrently": false, - "name": "idx_jobs_archive_output_fts", - "entityType": "indexes", - "schema": "duron", - "table": "jobs_archive" + "entityType": "indexes" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "job_steps_active_job_id_jobs_active_id_fkey", "nameExplicit": false, "columns": ["job_id"], "schemaTo": "duron", @@ -1476,12 +1849,12 @@ "columnsTo": ["id"], "onUpdate": "NO ACTION", "onDelete": "CASCADE", - "name": "job_steps_active_job_id_jobs_active_id_fkey", - "entityType": "fks", - "schema": "duron", - "table": "job_steps_active" + "entityType": "fks" }, { + "schema": "duron", + "table": "job_steps_archive", + "name": "job_steps_archive_job_id_jobs_archive_id_fkey", "nameExplicit": false, "columns": ["job_id"], "schemaTo": "duron", @@ -1489,88 +1862,84 @@ "columnsTo": ["id"], "onUpdate": "NO ACTION", "onDelete": "CASCADE", - "name": "job_steps_archive_job_id_jobs_archive_id_fkey", - "entityType": "fks", - "schema": "duron", - "table": "job_steps_archive" + "entityType": "fks" }, { - "columns": ["client_id"], - "nameExplicit": false, - "name": "clients_pkey", "schema": "duron", "table": "clients", + "name": "clients_pkey", + "columns": ["client_id"], + "nameExplicit": false, "entityType": "pks" }, { - "columns": ["id"], - "nameExplicit": false, - "name": "job_steps_active_pkey", "schema": "duron", "table": "job_steps_active", + "name": "job_steps_active_pkey", + "columns": ["id"], + "nameExplicit": false, "entityType": "pks" }, { - "columns": ["id"], - "nameExplicit": false, - "name": "job_steps_archive_pkey", "schema": "duron", "table": "job_steps_archive", + "name": "job_steps_archive_pkey", + "columns": ["id"], + "nameExplicit": false, "entityType": "pks" }, { - "columns": ["id"], - "nameExplicit": false, - "name": "jobs_active_pkey", "schema": "duron", "table": "jobs_active", + "name": "jobs_active_pkey", + "columns": ["id"], + "nameExplicit": false, "entityType": "pks" }, { - "columns": ["id"], - "nameExplicit": false, - "name": "jobs_archive_pkey", "schema": "duron", "table": "jobs_archive", + "name": "jobs_archive_pkey", + "columns": ["id"], + "nameExplicit": false, "entityType": "pks" }, { + "schema": "duron", + "table": "job_steps_active", + "name": "unique_job_step_active_name_parent", "nameExplicit": true, "columns": ["job_id", "name", "parent_step_id"], "nullsNotDistinct": true, - "name": "unique_job_step_active_name_parent", - "entityType": "uniques", - "schema": "duron", - "table": "job_steps_active" + "entityType": "uniques" }, { - "value": "\"status\" IN ('active','completed','failed','cancelled')", - "name": "job_steps_active_status_check", - "entityType": "checks", "schema": "duron", - "table": "job_steps_active" + "table": "job_steps_active", + "name": "job_steps_active_status_check", + "value": "\"status\" IN ('active','completed','failed','cancelled')", + "entityType": "checks" }, { - "value": "\"status\" IN ('active','completed','failed','cancelled')", - "name": "job_steps_archive_status_check", - "entityType": "checks", "schema": "duron", - "table": "job_steps_archive" + "table": "job_steps_archive", + "name": "job_steps_archive_status_check", + "value": "\"status\" IN ('active','completed','failed','cancelled')", + "entityType": "checks" }, { - "value": "\"status\" IN ('created','active','completed','failed','cancelled')", - "name": "jobs_active_status_check", - "entityType": "checks", "schema": "duron", - "table": "jobs_active" + "table": "jobs_active", + "name": "jobs_active_status_check", + "value": "\"status\" IN ('created','active','completed','failed','cancelled')", + "entityType": "checks" }, { - "value": "\"status\" IN ('created','active','completed','failed','cancelled')", - "name": "jobs_archive_status_check", - "entityType": "checks", "schema": "duron", - "table": "jobs_archive" + "table": "jobs_archive", + "name": "jobs_archive_status_check", + "value": "\"status\" IN ('created','active','completed','failed','cancelled')", + "entityType": "checks" } - ], - "renames": [] + ] } From 6c582032507b23bc1c330b9421c4df55d62dcd5f Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 22:17:50 -0300 Subject: [PATCH 032/100] docs: install drizzle-orm@rc and state tested versions and Node floor --- README.md | 10 ++++++---- packages/docs/content/docs/getting-started.mdx | 10 ++++++---- packages/duron/README.md | 10 ++++++---- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index d688e19..3798cf0 100644 --- a/README.md +++ b/README.md @@ -42,15 +42,17 @@ The complete documentation includes detailed guides on actions, adapters, client ### Installation ```bash -bun add duron postgres drizzle-orm@beta +bun add duron postgres drizzle-orm@rc # or -npm install duron postgres drizzle-orm@beta +npm install duron postgres drizzle-orm@rc # or -pnpm add duron postgres drizzle-orm@beta +pnpm add duron postgres drizzle-orm@rc # or -yarn add duron postgres drizzle-orm@beta +yarn add duron postgres drizzle-orm@rc ``` +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.1.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. + ### Creating an Action with Context Actions are defined with Zod schemas and have access to a context object that includes input, variables, and a step function. First define your variables type, then use `defineAction` with the variables type as a generic parameter: diff --git a/packages/docs/content/docs/getting-started.mdx b/packages/docs/content/docs/getting-started.mdx index 710b5d2..dc3800c 100644 --- a/packages/docs/content/docs/getting-started.mdx +++ b/packages/docs/content/docs/getting-started.mdx @@ -12,18 +12,20 @@ Install Duron using your preferred package manager: ```bash # Using npm -npm install duron drizzle-orm@beta +npm install duron drizzle-orm@rc # Using pnpm -pnpm add duron drizzle-orm@beta +pnpm add duron drizzle-orm@rc # Using yarn -yarn add duron drizzle-orm@beta +yarn add duron drizzle-orm@rc # Using bun -bun add duron drizzle-orm@beta +bun add duron drizzle-orm@rc ``` +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.1.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. + Install postgres for the current database: ```bash diff --git a/packages/duron/README.md b/packages/duron/README.md index f896ea9..256f087 100644 --- a/packages/duron/README.md +++ b/packages/duron/README.md @@ -6,18 +6,20 @@ A powerful, type-safe job queue system for Node.js and Bun.js. Duron provides a ```bash # Using bun -bun add duron postgres drizzle-orm@beta +bun add duron postgres drizzle-orm@rc # Using npm -npm install duron postgres drizzle-orm@beta +npm install duron postgres drizzle-orm@rc # Using pnpm -pnpm add duron postgres drizzle-orm@beta +pnpm add duron postgres drizzle-orm@rc # Using yarn -yarn add duron postgres drizzle-orm@beta +yarn add duron postgres drizzle-orm@rc ``` +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.1.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. + ## Quick Start ### 1. Define an Action From 9bd3ab798dbcd5ddfc6d14afa62ef15a2aefa805 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 22:25:03 -0300 Subject: [PATCH 033/100] chore: upgrade PGlite to 0.5.17 (PostgreSQL 18.7) PGlite 0.5.16 fixed its identifier helper to escape double quotes, so the notifications control that expected the old 42601 failure now records the fixed behaviour; Duron's own channel quoting assertions are unchanged. --- bun.lock | 4 ++-- packages/duron/package.json | 2 +- packages/duron/test/notifications.test.ts | 9 +++++---- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/bun.lock b/bun.lock index 691ede9..b789d01 100644 --- a/bun.lock +++ b/bun.lock @@ -62,7 +62,7 @@ "zod": "^4.5.0", }, "devDependencies": { - "@electric-sql/pglite": "^0.3.14", + "@electric-sql/pglite": "^0.5.17", "@opentelemetry/core": "^2.4.0", "@types/bun": "latest", "@types/node": "^24.0.15", @@ -220,7 +220,7 @@ "@dnd-kit/utilities": ["@dnd-kit/utilities@3.2.2", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="], - "@electric-sql/pglite": ["@electric-sql/pglite@0.3.16", "", {}, "sha512-mZkZfOd9OqTMHsK+1cje8OSzfAQcpD7JmILXTl5ahdempjUDdmg4euf1biDex5/LfQIDJ3gvCu6qDgdnDxfJmA=="], + "@electric-sql/pglite": ["@electric-sql/pglite@0.5.17", "", {}, "sha512-8SvKjiUjaU+0O0dbxjOfN+jXz14TEqDWbwDkYOW1aQ11y/ph2JvFVI27ABBo5nfw+ZfSqy4hKCNlbnbB1TDE+g=="], "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="], diff --git a/packages/duron/package.json b/packages/duron/package.json index 5d70c5d..27ecd7a 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -96,7 +96,7 @@ "zod": "^4.5.0" }, "devDependencies": { - "@electric-sql/pglite": "^0.3.14", + "@electric-sql/pglite": "^0.5.17", "@opentelemetry/core": "^2.4.0", "@types/bun": "latest", "@types/node": "^24.0.15", diff --git a/packages/duron/test/notifications.test.ts b/packages/duron/test/notifications.test.ts index 9566984..e17025b 100644 --- a/packages/duron/test/notifications.test.ts +++ b/packages/duron/test/notifications.test.ts @@ -67,7 +67,7 @@ function interceptSubmission( } } -it('keeps installed PGLite identifier-helper and escaped-listen-map controls discriminating', async () => { +it('keeps the escaped-listen-map control discriminating with the installed PGLite identifier helper', async () => { const instance = await pgliteFactory.create({ schema: 'Quote"Name', migrateOnStart: false }) const adapter = instance.adapter as NotificationProbe adapter.setId('pglite-rejected-candidates') @@ -81,10 +81,11 @@ it('keeps installed PGLite identifier-helper and escaped-listen-map controls dis }) let selected: { unlisten: () => void | Promise } | undefined try { + // PGlite 0.3 left `"` unescaped here (42601); 0.5.16+ escapes it. Duron quotes channel names + // itself, so its behaviour below must hold either way. const candidate = templateQuery`LISTEN ${identifier`${channel}`}` - await expect(engine.query(candidate.query, candidate.params)).rejects.toMatchObject({ - code: '42601', - }) + await engine.query(candidate.query, candidate.params) + await engine.query(`UNLISTEN ${candidate.query.slice('LISTEN '.length)}`) const quoted = ( await engine.query<{ identifier: string }>('SELECT quote_ident($1) AS identifier', [channel]) ).rows[0]!.identifier From b68743df8162ddfb13e2db418f1b83f8c9c1f85f Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Sun, 29 Nov 2026 22:30:31 -0300 Subject: [PATCH 034/100] docs: pin PGlite 0.5 in install instructions --- packages/docs/content/docs/getting-started.mdx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/docs/content/docs/getting-started.mdx b/packages/docs/content/docs/getting-started.mdx index dc3800c..6a1614a 100644 --- a/packages/docs/content/docs/getting-started.mdx +++ b/packages/docs/content/docs/getting-started.mdx @@ -46,18 +46,20 @@ Install pglite for the current database: ```bash # Using npm -npm install @electric-sql/pglite +npm install @electric-sql/pglite@0.5 # Using pnpm -pnpm add @electric-sql/pglite +pnpm add @electric-sql/pglite@0.5 # Using yarn -yarn add @electric-sql/pglite +yarn add @electric-sql/pglite@0.5 # Using bun -bun add @electric-sql/pglite +bun add @electric-sql/pglite@0.5 ``` +Duron is tested with PGlite 0.5.17 (PostgreSQL 18). PGlite 0.6 runs PostgreSQL 19 and is not tested yet. + ## Schema Library Duron uses [Standard Schema](https://standardschema.dev) for input/output validation. You'll need a schema library that implements this specification: From 7299b0185df95dad4801b50d3cb6bde1b585ac5e Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 08:57:05 -0300 Subject: [PATCH 035/100] chore(deps): remove unused deps, add duron peer deps, apply in-range updates - Remove unused: dashboard jsonata, radix-ui, elysia (dev); docs @tanstack/react-router-devtools, tailwind-merge; duron @opentelemetry/core (dev); examples zod; shared-actions @types/bun (dev). - duron: move p-retry to devDependencies (src vendors src/utils/p-retry.ts). - duron: declare peerDependencies drizzle-orm "1.0.0-rc.6 || ^1.0.0", postgres ^4.1.1 (optional), @electric-sql/pglite ^0.5.17 (optional). A ">=1.0.0-rc.6" bound would also match drizzle's hash-suffixed 1.0.0-rc.- snapshots under semver precedence. - Apply in-range updates across workspaces (postgres 4.2.0, zod 4.6, OTel 2.12/api 1.10, react 19.3, radix, oxlint 1.95, ...). TanStack Start/Router in docs stay on the current lock: Start 1.169+ requires Vite 8. - Tests: postgres 4.2 types reserve() as Leasing; prune test stubs assign through a Promise-returning view. - Docs: tested with postgres 4.2.0. --- README.md | 2 +- bun.lock | 805 ++++++++---------- package.json | 2 +- .../docs/content/docs/getting-started.mdx | 2 +- packages/docs/package.json | 26 +- packages/duron-dashboard/package.json | 57 +- packages/duron/README.md | 2 +- packages/duron/package.json | 40 +- packages/duron/test/prune-bootstrap.test.ts | 10 +- packages/duron/test/prune-ownership.test.ts | 22 +- packages/duron/test/prune-replies.test.ts | 8 +- packages/duron/test/prune-transport.test.ts | 8 +- packages/examples/package.json | 3 - packages/shared-actions/package.json | 9 +- 14 files changed, 471 insertions(+), 525 deletions(-) diff --git a/README.md b/README.md index 3798cf0..b884745 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ pnpm add duron postgres drizzle-orm@rc yarn add duron postgres drizzle-orm@rc ``` -Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.1.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. ### Creating an Action with Context diff --git a/bun.lock b/bun.lock index b789d01..12cf445 100644 --- a/bun.lock +++ b/bun.lock @@ -6,7 +6,7 @@ "name": "duron-workspace", "devDependencies": { "oxfmt": "^0.59.0", - "oxlint": "^1.74.0", + "oxlint": "^1.95.0", "typescript": "^7.0.2", }, }, @@ -16,29 +16,27 @@ "packages/docs": { "name": "docs", "dependencies": { - "@orama/orama": "^3.1.16", + "@orama/orama": "^3.1.18", "@tanstack/react-router": "^1.134.12", - "@tanstack/react-router-devtools": "^1.134.12", "@tanstack/react-start": "^1.134.12", "@tanstack/start-static-server-functions": "^1.134.12", "fumadocs-core": "16.2.0", "fumadocs-mdx": "14.0.3", "fumadocs-ui": "16.1.0", "lucide-static": "^0.552.0", - "react": "^19.2.0", - "react-dom": "^19.2.0", - "tailwind-merge": "^3.3.1", - "vite": "^7.2.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "vite": "^7.3.8", }, "devDependencies": { - "@tailwindcss/vite": "^4.1.16", - "@types/mdx": "^2.0.13", - "@types/node": "^24.10.0", - "@types/react": "^19.2.2", - "@types/react-dom": "^19.2.2", - "@vitejs/plugin-react": "^5.1.0", - "serve": "^14.2.5", - "tailwindcss": "^4.1.16", + "@tailwindcss/vite": "^4.3.5", + "@types/mdx": "^2.0.14", + "@types/node": "^24.19.4", + "@types/react": "^19.3.3", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^5.2.0", + "serve": "^14.2.8", + "tailwindcss": "^4.3.5", "typescript": "^5.9.3", "vite-tsconfig-paths": "^5.1.4", }, @@ -47,30 +45,38 @@ "name": "duron", "version": "0.5.0-beta.0", "dependencies": { - "@opentelemetry/api": "^1.9.0", - "@opentelemetry/resources": "^2.4.0", - "@opentelemetry/sdk-trace-base": "^2.4.0", - "@opentelemetry/sdk-trace-node": "^2.4.0", - "@opentelemetry/semantic-conventions": "^1.39.0", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/resources": "^2.12.1", + "@opentelemetry/sdk-trace-base": "^2.12.1", + "@opentelemetry/sdk-trace-node": "^2.12.1", + "@opentelemetry/semantic-conventions": "^1.45.0", "@standard-schema/spec": "^1.1.0", "@standard-schema/utils": "^0.3.0", - "elysia": "^1.4.22", - "fastq": "^1.19.1", - "jose": "^6.1.2", - "p-retry": "^7.1.0", - "pino": "^10.1.0", - "zod": "^4.5.0", + "elysia": "^1.4.32", + "fastq": "^1.20.3", + "jose": "^6.2.18", + "pino": "^10.4.0", + "zod": "^4.6.7", }, "devDependencies": { "@electric-sql/pglite": "^0.5.17", - "@opentelemetry/core": "^2.4.0", "@types/bun": "latest", - "@types/node": "^24.0.15", + "@types/node": "^24.19.4", "drizzle-kit": "1.0.0-rc.6", "drizzle-orm": "1.0.0-rc.6", - "postgres": "^4.1.1", + "p-retry": "^7.1.1", + "postgres": "^4.2.0", "typescript": "^7", }, + "peerDependencies": { + "@electric-sql/pglite": "^0.5.17", + "drizzle-orm": "1.0.0-rc.6 || ^1.0.0", + "postgres": "^4.1.1", + }, + "optionalPeers": [ + "@electric-sql/pglite", + "postgres", + ], }, "packages/duron-dashboard": { "name": "duron-dashboard", @@ -84,55 +90,49 @@ "@maskito/kit": "^4.0.1", "@maskito/react": "^4.0.1", "@monaco-editor/react": "^4.7.0", - "@radix-ui/react-accordion": "^1.2.12", - "@radix-ui/react-checkbox": "^1.3.3", - "@radix-ui/react-dialog": "^1.1.15", - "@radix-ui/react-dropdown-menu": "^2.1.16", - "@radix-ui/react-label": "^2.1.8", - "@radix-ui/react-popover": "^1.1.15", - "@radix-ui/react-scroll-area": "^1.2.10", - "@radix-ui/react-select": "^2.2.6", - "@radix-ui/react-separator": "^1.1.8", - "@radix-ui/react-slider": "^1.3.6", - "@radix-ui/react-slot": "^1.2.4", - "@radix-ui/react-tooltip": "^1.2.8", - "@tanstack/react-query": "^5.90.10", + "@radix-ui/react-accordion": "^1.3.1", + "@radix-ui/react-checkbox": "^1.4.1", + "@radix-ui/react-dialog": "^1.3.1", + "@radix-ui/react-dropdown-menu": "^2.2.1", + "@radix-ui/react-label": "^2.1.17", + "@radix-ui/react-popover": "^1.3.1", + "@radix-ui/react-scroll-area": "^1.4.0", + "@radix-ui/react-select": "^2.4.1", + "@radix-ui/react-separator": "^1.2.0", + "@radix-ui/react-slider": "^1.6.1", + "@radix-ui/react-slot": "^1.5.0", + "@radix-ui/react-tooltip": "^1.4.1", + "@tanstack/react-query": "^5.108.4", "@tanstack/react-table": "^8.21.3", - "@tanstack/react-virtual": "^3.13.18", + "@tanstack/react-virtual": "^3.14.30", "bun-plugin-tailwind": "^0.1.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", - "date-fns": "^4.1.0", - "jsonata": "^2.1.0", + "date-fns": "^4.4.0", "lucide-react": "^0.555.0", - "motion": "^12.23.24", - "nanoid": "^5.1.6", - "nuqs": "^2.8.0", - "radix-ui": "^1.4.3", - "react": "^19", - "react-day-picker": "^9.11.2", - "react-dom": "^19", - "react-resizable-panels": "^4.4.1", - "tailwind-merge": "^3.4.0", + "motion": "^12.43.0", + "nanoid": "^5.1.16", + "nuqs": "^2.10.3", + "react": "^19.3.1", + "react-day-picker": "^9.14.0", + "react-dom": "^19.3.1", + "react-resizable-panels": "^4.27.0", + "tailwind-merge": "^3.7.1", "usehooks-ts": "^3.1.1", - "zod": "^4.5.0", + "zod": "^4.6.7", }, "devDependencies": { "@types/bun": "latest", - "@types/react": "^19", - "@types/react-dom": "^19", - "elysia": "^1.4.16", - "tailwindcss": "^4.1.11", + "@types/react": "^19.3.3", + "@types/react-dom": "^19.3.0", + "tailwindcss": "^4.3.5", "tw-animate-css": "^1.4.0", "typescript": "^7", }, }, "packages/examples": { "name": "examples", - "dependencies": { - "zod": "^4.1.12", - }, "devDependencies": { "@types/bun": "latest", "duron": "workspace:*", @@ -145,13 +145,12 @@ "packages/shared-actions": { "name": "shared-actions", "dependencies": { - "@ai-sdk/openai": "^3.0.12", - "@opentelemetry/api": "^1.9.0", - "ai": "^6.0.42", - "zod": "^4.1.12", + "@ai-sdk/openai": "^3.0.147", + "@opentelemetry/api": "^1.10.0", + "ai": "^6.0.339", + "zod": "^4.6.7", }, "devDependencies": { - "@types/bun": "latest", "duron": "workspace:*", }, "peerDependencies": { @@ -160,41 +159,41 @@ }, }, "packages": { - "@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.153", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@ai-sdk/provider-utils": "4.0.40", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-R5r567od2Olqze/lL2dVS4wVOVyVqG6sJ3cEUI/kW12XQJYKf8fetyxWPYS0ZFe87QPcsh3Z3sDnrMAtAIiS3Q=="], + "@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.244", "", { "dependencies": { "@ai-sdk/provider": "3.0.19", "@ai-sdk/provider-utils": "4.0.69", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-U3k15BP8I3WIeKMi/p0G4JvVs/INNSqa16qK2Qj20yNsKBGT63dFDEGdpysxY+EG32SjKLcb7X0DJ0ondY99+g=="], - "@ai-sdk/openai": ["@ai-sdk/openai@3.0.86", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@ai-sdk/provider-utils": "4.0.40" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-np3jjvNmWVZyBjI02a1fx4TzWVnOaOp3yJAfOJw9dxEAPmvnOhyx22TkFcJ91LqyFuCbGKZKtSBj6ee7ARsiPw=="], + "@ai-sdk/openai": ["@ai-sdk/openai@3.0.147", "", { "dependencies": { "@ai-sdk/provider": "3.0.19", "@ai-sdk/provider-utils": "4.0.69" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-OBogVZLOdS6TXjSi6l4hEVgWkC2ijCkSvffGLW2FT9oSYBu9frvsvkh+U3sWFM5OpxqScNpehQAahOp/Qs1kRA=="], - "@ai-sdk/provider": ["@ai-sdk/provider@3.0.14", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-5X1k57JBJ4H7H1QjX7CnJYAB1I19r/trVZTMcSms7/kLNZ8RaU4Nt2agcwZzv82Hfx6Q7/TOLU7agAKeFfc8cA=="], + "@ai-sdk/provider": ["@ai-sdk/provider@3.0.19", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-5lWq7zSfRaU5ylDESn3sDQjgGl2AI1vjZKO/6JY3aFW70ct4zcP1kN+ZUYOuTXr28fVsYbyu2YFhddLdIgQFZQ=="], - "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.40", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-OL5IrpUm9Y8Dwy+w/vvFwPotS6m52O9W0op2oXgXdCROMJIBalBI0oro6OIBYkPxvm5Xg02GSkoQN25RlR0bnw=="], + "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.69", "", { "dependencies": { "@ai-sdk/provider": "3.0.19", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.1.1", "undici": "^6.28.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-j4coUNodGSDug1pGqmBOdRJKSoJ+QwbVs+gsfufLUx6YPuO87b3Q5ryUfsk1G5xL7IvGLFH+SNih26Oh8Ucv2Q=="], "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], "@babel/compat-data": ["@babel/compat-data@7.29.7", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="], - "@babel/core": ["@babel/core@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="], + "@babel/core": ["@babel/core@7.29.16", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.16", "@babel/helper-compilation-targets": "^7.29.13", "@babel/helper-module-transforms": "^7.29.16", "@babel/helpers": "^7.29.16", "@babel/parser": "^7.29.15", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.16", "@babel/types": "^7.29.15", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-qK40pOeReBJY7B0JX6CCIfauMLAa0IlvuVYJ+aZBYLVJwmNUTvsQcEu0En9hVMmNjeSUSQYwvpi1JgXn5imIQw=="], - "@babel/generator": ["@babel/generator@7.29.7", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="], + "@babel/generator": ["@babel/generator@7.29.16", "", { "dependencies": { "@babel/parser": "^7.29.15", "@babel/types": "^7.29.15", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-yRtddtrcYdLJt0l70aP7usb2YpMHNXAdAvJW2hXdka5boR4vKMS/F5BTR5sULkbht9xPk/EKzbY2mCczMutZqQ=="], - "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.7", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g=="], + "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.13", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w=="], "@babel/helper-globals": ["@babel/helper-globals@7.29.7", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="], "@babel/helper-module-imports": ["@babel/helper-module-imports@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g=="], - "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.7", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg=="], + "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.16", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.16" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-jzdW9nRNJXbNAfcbtfZA75vcQK8c/PRniwNL1KIQukiptryb5JlCl+nwi3idOSj611tMgiZxb9PuKg1FI0BvVQ=="], "@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@7.29.7", "", {}, "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw=="], - "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.15", "", {}, "sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w=="], "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], "@babel/helper-validator-option": ["@babel/helper-validator-option@7.29.7", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="], - "@babel/helpers": ["@babel/helpers@7.29.7", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg=="], + "@babel/helpers": ["@babel/helpers@7.29.16", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.15" } }, "sha512-JGNbyEyvOAvceLDQoO6b/w/HbW6KX3sdWgrPCFcAyHfhfsqRoRN14vfaG3GZ90g2dVK7UEe65giopuldeimBjg=="], - "@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], + "@babel/parser": ["@babel/parser@7.29.15", "", { "dependencies": { "@babel/types": "^7.29.15" }, "bin": "./bin/babel-parser.js" }, "sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA=="], "@babel/plugin-transform-react-jsx-self": ["@babel/plugin-transform-react-jsx-self@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw=="], @@ -202,11 +201,11 @@ "@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="], - "@babel/traverse": ["@babel/traverse@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/types": "^7.29.7", "debug": "^4.3.1" } }, "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw=="], + "@babel/traverse": ["@babel/traverse@7.29.16", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.16", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.15", "@babel/template": "^7.29.7", "@babel/types": "^7.29.15", "debug": "^4.3.1" } }, "sha512-a16ah9dTLOLUq5BL7NElJ7keefg/276vgfTfExDf1PizddYboqRnQXDTooVPb0VArIqrKe8KLlghnTxlZFEZtQ=="], - "@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + "@babel/types": ["@babel/types@7.29.15", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.15", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-/XKpKDakL//LZ66bq1XsZOswuqeI5MZqPLDu18o3XdkU1fNJ7bdPtzgnc4ZNS+bBGHV0FJG8jjb8SwcC3nNVQQ=="], - "@borewit/text-codec": ["@borewit/text-codec@0.2.2", "", {}, "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ=="], + "@borewit/text-codec": ["@borewit/text-codec@0.2.3", "", {}, "sha512-49CycTz1aAZmvFcwkeFyhud1HUmRIB5Tabf7ALV+VA4Iu85MTfz2cUwzPagMFAdVBvrWdkCxG67I30tUwwpKsw=="], "@date-fns/tz": ["@date-fns/tz@1.5.0", "", {}, "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg=="], @@ -288,9 +287,9 @@ "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], - "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.3", "", {}, "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g=="], - "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], @@ -314,55 +313,47 @@ "@oozcitak/util": ["@oozcitak/util@10.0.0", "", {}, "sha512-hAX0pT/73190NLqBPPWSdBVGtbY6VOhWYK3qqHqtXQ1gK7kS2yz4+ivsN07hpJ6I3aeMtKP6J6npsEKOAzuTLA=="], - "@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], + "@opentelemetry/api": ["@opentelemetry/api@1.10.0", "", {}, "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ=="], - "@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@2.9.0", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-OQ0vzvbZBiUhjqLnUaoNfYmP8553Crr3aggB4y0ZUi815mZ7idpdJXQmoKdeBKJelYttoBlLSSHubmyw3wvX4w=="], + "@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@2.12.1", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-1+zgZyD7QvBr0/K6+FVx5UAzdGo0shnQf8pbWUFFbj43qZPIKTtfK4xX4J3bS7AmkifiZzAEMdk8dztiEfkgmg=="], - "@opentelemetry/core": ["@opentelemetry/core@2.9.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-m2nckMT80NnmjTYSPjJQObBJ+8dgkoajEOUbznL8AHZ3T3yHRk2P7gI1PhEBc1+lOnrYE9UWrWHqJDsmqjmNbw=="], + "@opentelemetry/core": ["@opentelemetry/core@2.12.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-3hr6Pj0/G0oVgIGb97IVcw9BjZ6eudonKjrmQxw7JquyU/XmVbJelkmyoU0sT/OvHGkv+r1tcrwv8MbSX7aKHw=="], - "@opentelemetry/resources": ["@opentelemetry/resources@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg=="], + "@opentelemetry/resources": ["@opentelemetry/resources@2.12.1", "", { "dependencies": { "@opentelemetry/core": "2.12.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-IwrNcuLCvnJAnNLkXxx0Uw+rjBkVW6VGQrhd7PanNf0LavOzkTk9sDAjdqegM7p/VdxefNRrii6d+wBRJfz35g=="], - "@opentelemetry/sdk-trace": ["@opentelemetry/sdk-trace@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/resources": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-sGA19HvtrrSKYsseHphluH6j3p6Xa3fqc7c7y8f/7mYWejc1lyDFcpSdD1kYa50HCLUeEo4zA5bW0pniaPszuw=="], + "@opentelemetry/sdk-trace": ["@opentelemetry/sdk-trace@2.12.1", "", { "dependencies": { "@opentelemetry/core": "2.12.1", "@opentelemetry/resources": "2.12.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-vANdmCYnn+Ka/alBKxwICMl4Koa+aQBlRC9zAZy+Ig1Obbo3RZt2oiyv+8/gET5rrBBYrO3YniPcXfwZrN01rg=="], - "@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/resources": "2.9.0", "@opentelemetry/sdk-trace": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-cp9zmTl62R8PJrpvFcmc8N2JQU/xfa0S+61q511Nji+QxCfZ8Ifvg7H27G8cANe4crg4RTrWsVvanHiXjSp6ag=="], + "@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@2.12.1", "", { "dependencies": { "@opentelemetry/core": "2.12.1", "@opentelemetry/resources": "2.12.1", "@opentelemetry/sdk-trace": "2.12.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-CMrcqFxTikYmYQCuHToBO4kQvWIseRk2ztzWidTd7VutIxj1rljvJZCZnFPJEGNOS7FvaSmRL21Jeuu3/wrCAQ=="], - "@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@2.9.0", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.9.0", "@opentelemetry/core": "2.9.0", "@opentelemetry/sdk-trace-base": "2.9.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-ec9a7ps37huy5itYk0MalaZdSLlM6AXWp/FhtEjgMpp5leEGojBDvAl/UWttQnkMZOvFHKzRESn8TD3yKTF5nQ=="], + "@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@2.12.1", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.12.1", "@opentelemetry/core": "2.12.1", "@opentelemetry/sdk-trace-base": "2.12.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-nRe0mimXZHknAEW2PKN9VbmML+93il5okotyDIUMhgYJ0QPM999fsh7djH6HDheyAbXO/C24t/B4fOQbNap8Vw=="], - "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="], + "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.45.0", "", {}, "sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw=="], "@orama/orama": ["@orama/orama@3.1.18", "", {}, "sha512-a61ljmRVVyG5MC/698C8/FfFDw5a8LOIvyOLW5fztgUXqUpc1jOfQzOitSCbge657OgXXThmY3Tk8fpiDb4UcA=="], - "@oven/bun-darwin-aarch64": ["@oven/bun-darwin-aarch64@1.3.14", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Omj20SuiHBOUjUBIyqtkNjSUIjOtEOJwmbix/ZyFH4BaQ6OZTaaRWIR4TjHVz0yadHgli6lLTiAh1uarnvD49A=="], - - "@oven/bun-darwin-x64": ["@oven/bun-darwin-x64@1.3.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-FFj3QdU/OhlDyZOJ8CWfN5eWLpRlT4qjZg7lMQi7jA6GuoY5ajlO1zWLP/MuHYRSbXQUvV52RejNi8DVnAp13w=="], + "@oven/bun-darwin-aarch64": ["@oven/bun-darwin-aarch64@1.4.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4MIFXHmctH2EhAxLXm2/qxNtv17dFtLJylvaOCsrgq6KSqHTs6eW5YSrJjRbJxYUJaR901fsN8JfZOa+CsWpWQ=="], - "@oven/bun-darwin-x64-baseline": ["@oven/bun-darwin-x64-baseline@1.3.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-OSfsTZstc898HHElhU4NccaBGOSSDn5VfahiVTnidZ9B/+wb7WTyfZJaBeJcfjwJ9H2W9uTh2TGtl3UfcXgV9g=="], + "@oven/bun-darwin-x64": ["@oven/bun-darwin-x64@1.4.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-qkLPMGHZM9NI6CeHTWwVezzmlo6cC4Ta7yUAjYIWXS366qQcOlcp75t2uZyiuVRBMPS0h9qE0tCcvCHGaFqjJg=="], - "@oven/bun-freebsd-aarch64": ["@oven/bun-freebsd-aarch64@1.3.14", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-LIKrXaFxAHybVO5Pf+9XP2FHUj/5APvXTUKk9dqHm5iFz4oH+W24cmhjkJirNujh9hKeTyrpWSe3no9JZKowIw=="], + "@oven/bun-freebsd-aarch64": ["@oven/bun-freebsd-aarch64@1.4.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-limWGUkd7wNKh9X/KJa4RyPMTdZsI+sqs7KmAWc/zFllRe5BSlN71ZfAVSYDDJMUJUQUvDdAMywH5zYkYrfUzQ=="], - "@oven/bun-freebsd-x64": ["@oven/bun-freebsd-x64@1.3.14", "", { "os": "freebsd", "cpu": "x64" }, "sha512-uwD+fGUH1ADpIF3B1U2jWzzb20QwRLZfj5QZ28GUCGrAJ/nTmWrD6YYGsblCY1wuhldRez3lU40AyuvSCyLYmw=="], + "@oven/bun-freebsd-x64": ["@oven/bun-freebsd-x64@1.4.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-LahCo0mJJzscE0PUKO8FXdFiOc2vqt9zhf35gSFAVemeCn88idDWpp/rhNcnEsHWMhf5GMXxGJA5D9deTmzW1g=="], - "@oven/bun-linux-aarch64": ["@oven/bun-linux-aarch64@1.3.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-X5SsPZHs+iYO8R/efIcRtc7gT2Q2DgPfliCxEkx4cXBumwkw0c/EsHMNwH3EgGpCDaZ7IYVPhpCG/xBOQHEwZw=="], + "@oven/bun-linux-aarch64": ["@oven/bun-linux-aarch64@1.4.5", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-4BXmsSKnjOrlGWqZV4x/oWa7AVoR+B6lCXddMzOAXBIm3t50eslg9wb66gmtW1AamEQ1l1CDvmmruysEhqOWMg=="], - "@oven/bun-linux-aarch64-android": ["@oven/bun-linux-aarch64-android@1.3.14", "", { "os": "android", "cpu": "arm64" }, "sha512-y4kq5b85lsrmFb9Xvi4w9mA5IEFJkLMrSmYn06q24KjL9rUWDWO3VFZEtteZxUN5+ec3Zm5S8OnJw1umaCbVjA=="], + "@oven/bun-linux-aarch64-android": ["@oven/bun-linux-aarch64-android@1.4.5", "", { "os": "android", "cpu": "arm64" }, "sha512-SI502JpXyu6em6y8E3F48GO3LwjYXSG3DWEOPhf9LXJWjjnPG9OwrWajtM91saa2vAixZ0ErlZa8UzNORcgcyQ=="], - "@oven/bun-linux-aarch64-musl": ["@oven/bun-linux-aarch64-musl@1.3.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-jmqOA92Cd1NL/1XBd4bFkJLxQ86K0RW7ohxS2qzzAvuitO4JiIxjjTeCspoU44zCozH72HpfZfUE2On31OjnWA=="], + "@oven/bun-linux-aarch64-musl": ["@oven/bun-linux-aarch64-musl@1.4.5", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-XCNc+WvvMAdNNb+OWTogpy+N9wm62fkVeEVLb6how0RZhW5LPi6c7BlkeVCuWps7XjEl2saFpHFa20/1E+PAHg=="], - "@oven/bun-linux-x64": ["@oven/bun-linux-x64@1.3.14", "", { "os": "linux", "cpu": "x64" }, "sha512-7OVTAKvwfPmSbIV1HpdOoVVx5VRc427GuPPne93N6vk4eQBPId9nXmZDh9/zGaKPdbVjVtQSZafWQoUjx38Utw=="], + "@oven/bun-linux-x64": ["@oven/bun-linux-x64@1.4.5", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-IWX9BELoGHAUtMonkeSaNaZwXzRk+oDw6Mk+HBFXd3KHYIBNBsIGRupMZPcgNoDbJpLu6gAJjIoIVPZtt1aJ1g=="], - "@oven/bun-linux-x64-android": ["@oven/bun-linux-x64-android@1.3.14", "", { "os": "android", "cpu": "x64" }, "sha512-qe9e1d+3VAEU7nAA2ol9Jvmy/o99PVMSgZhHn7Q/9O3YcDrfEqyQ8zm4zoe5qTEo8HZH0dN03Le0Ys2eQPs7eg=="], + "@oven/bun-linux-x64-android": ["@oven/bun-linux-x64-android@1.4.5", "", { "os": "android", "cpu": "x64" }, "sha512-81X3/qn9v18bHHIHfkGikQ/KztJTJpo6GMuqtwKm/jHMQy+Z8JpjIfxdaYocxeiRwgQhBXlby2HTKPvMyEjsOg=="], - "@oven/bun-linux-x64-baseline": ["@oven/bun-linux-x64-baseline@1.3.14", "", { "os": "linux", "cpu": "x64" }, "sha512-q/8EdOC0yUE8FPeoOVq8/Pw5I9/tJaYmUfO/uDUAREx8IUnOJH1RJ5A3BjFqre8pvJoiZA9AovPJq5FnNNjSxA=="], + "@oven/bun-linux-x64-musl": ["@oven/bun-linux-x64-musl@1.4.5", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-10QoW/YfTgnURaGEaHpJCiXjLI2e5iTtfVDaA5JKcyUzaa1cq6cVUY9/Uq5XkYzvtRjHLRe9Oj/lTDIQcxy8HQ=="], - "@oven/bun-linux-x64-musl": ["@oven/bun-linux-x64-musl@1.3.14", "", { "os": "linux", "cpu": "x64" }, "sha512-GBCB/k/sIqcr06eTNgg7g46qiUv35Jasx4XiccJ/n7RGqrE4RWUD/XJBbWFprVPjvqd59+QtSnS99XGqvftHfg=="], + "@oven/bun-windows-aarch64": ["@oven/bun-windows-aarch64@1.4.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-MiPFZnBNDnBXgr1oONc5pizC4fOLjnIOfNkYdFEnWzLmoFTg86naZIG3SvS7d/GglpQSAnCKMAzSjI/TAckiRw=="], - "@oven/bun-linux-x64-musl-baseline": ["@oven/bun-linux-x64-musl-baseline@1.3.14", "", { "os": "linux", "cpu": "x64" }, "sha512-n6iE71G4lQE4XkrZhQQcL5YUlxDbnq6nqV7zeQi33PMsLT/0kYE+RvHOtBWZ3w0wMdXZfINmp63hIb9ijUBGtw=="], - - "@oven/bun-windows-aarch64": ["@oven/bun-windows-aarch64@1.3.14", "", { "os": "win32", "cpu": "arm64" }, "sha512-T7s3x/BsVKQObGU6QDkZeI6wKynzqGbBH1yI77jrrj5siElclxr3DQrDIk8CV4G5/SJq2HHq4kpLyYY2DKCSmA=="], - - "@oven/bun-windows-x64": ["@oven/bun-windows-x64@1.3.14", "", { "os": "win32", "cpu": "x64" }, "sha512-mUFWL3BoYkNpjd8e9PqROiFF/1Xeotq20mABJsiQH62jM1g5zqWh4khw1RZ6bX8Q8fWvlPaxG1PjofkmjUi3vg=="], - - "@oven/bun-windows-x64-baseline": ["@oven/bun-windows-x64-baseline@1.3.14", "", { "os": "win32", "cpu": "x64" }, "sha512-uIjLUC1S9DWgICzuoMba7vurBJnBruE4S5CxnvmZkdqWVXRzx1Rgu636HoH+k0qeaQCFh3jeG3JQ1y6fRHv0sw=="], + "@oven/bun-windows-x64": ["@oven/bun-windows-x64@1.4.5", "", { "os": "win32", "cpu": "x64" }, "sha512-FNvply651vcE/GHgNWz6mZvhmkwBuu8Hw54oNzA+CQog+HW+542rXQmZqNHRkFxazD9L3xi+iTtvO3engAgJfw=="], "@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.59.0", "", { "os": "android", "cpu": "arm" }, "sha512-bNTnfbuG7sAwb2PakMNaDukx5kXeW9duXOBeWtTOiLz3fXz3q2DlWguufPZ+c2IHEVrRXHD+M4aUgEWm841LDA=="], @@ -402,217 +393,183 @@ "@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.59.0", "", { "os": "win32", "cpu": "x64" }, "sha512-dUUbZkKgWrmAeI/puzv4bxN8lzcYaFnQVwFTFtwO2Gp8M7lZGSE2qJjC58g518+1bltJ8mizjYwD0BGHym0l/w=="], - "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.74.0", "", { "os": "android", "cpu": "arm" }, "sha512-+gHd12muVI9ZLBaWLPkHt3Fj7jihFjgQ1MGtBaRL8vWrWrI0P7dLUty/cHrHS0oqPYIRgQUJsPu2CExQuMcwNw=="], + "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.95.0", "", { "os": "android", "cpu": "arm" }, "sha512-hJna6w3COWJjfMPxomjZL82klTdrITm56PEpCsfO/xMkzQw/fNtJWauQ/YEwQqVttj0L5vDIa8rCcuhfAE3L4w=="], - "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.74.0", "", { "os": "android", "cpu": "arm64" }, "sha512-xjKdoMB+H+RCOByv/7l7nfIGW9mlOisqYdcyC75UqYuQecLpReAeEYUf2CNeDEI3KtmUgxpRw/+c63y4AeF/Bw=="], + "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.95.0", "", { "os": "android", "cpu": "arm64" }, "sha512-uAIGZQ9uJVUeogeWOSboI3F7twOuM4mNuZcHXD9+LdYLcWp7J6kbtRUXJ6GVqcs5E0Cjb4emmSBK9FNrkGuhqQ=="], - "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.74.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-iUK7wvc6sejMKsC+Pt67mntoF5weFcyEunhZfLJceU6gL419mexz5wBkSx/EnkFBExMLNtOi9fnDSc5xfK0IzQ=="], + "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.95.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Ogh1vfHO5vshKRop/He46r+WqC5BTqonYwhB4fp9e2gvOFvg1Xi6XsHTuM/lBSH85ZcaG+DS99EMAy9GcwDong=="], - "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.74.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-ggKc/tn5SJ1u2yG2izC6VKODfYKV8MQ2AicJlNzOjuyrC29udvOef6/JzK2r32xqCnBDLFouR1VCkjzEI0/N9Q=="], + "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.95.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-kTrE1xfpQUBMMS50Ws6KY92N8OsJ8LE6JqxKqkHEY3KdsmguQ6kKVGSjzyt1HLwsSi0fQCvNRog8YRBBovD1AA=="], - "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.74.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-u++dH/43jy9hTLbneaWlS0gla/Bp1JdwJ2zgevCl8nDFUh6qRCGMxcL0f0lb7By3A9p/LfFr+7cG4HU1hG856g=="], + "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.95.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-ho7E1VCInK0VnpneRaI1BEpe1ceJE8VjxP2O9THWdReV6bth1Q4+80kYVGGK47mHRyZ2NGztQZ2dWRo6j1lavA=="], - "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.74.0", "", { "os": "linux", "cpu": "arm" }, "sha512-Sj1zmtFDVTPeIbIz4ZfcXAbFHqCmKCXdCUlAJzvTF7I20NTH1RDpoF2PhkqNODutJzVhJYmm3oz0GwgY+tvE2g=="], + "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.95.0", "", { "os": "linux", "cpu": "arm" }, "sha512-94afnouMHcnHr/OtRh07gG5LehC9M0GjiSoik3xxTtrmq6cWxXOTAhYlBtxa67u/GlycbnHlDoGJfYlTshcr/w=="], - "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.74.0", "", { "os": "linux", "cpu": "arm" }, "sha512-//PKyQb/tQXcHArx2f7z+oVI/eMS2Jpv+edNuAtOrgIhWdGcpHxogveAxzmF2rpH1AIHp4Hq04RF/rgJdiICnQ=="], + "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.95.0", "", { "os": "linux", "cpu": "arm" }, "sha512-LEeclqV1/fafxPgJWN21Bri6HBBBZpEFluq/ZH7Avvu9HjJh/XOn6WwogJqX9X7pG2aITZ2nRH39+sUKEQt2WA=="], - "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.74.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-/k1Me+aX2tjuH10K62mLS0y8cLkJBHX6Ce0xPK+eWeel4bSdEGZ8dv4+hYMzg0GrSmjwy4yAYsDPeEeKBft/2w=="], + "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.95.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-EpXpEQKmgtkvc6RyU84LM1e3CrVDWQkgghVzf1hMGgwjBzgKAJ/QntHgnzmu5cNeLBfa7GPCY+gGXxEll8Adcg=="], - "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.74.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-3tFSjBxc5D8/zvjEuLvOqcA8ZXKD0+6NuaVO/edeamNc49MoAsbfaC9s1UiwODwgF6slGaF8yJA2TPkukd77tg=="], + "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.95.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-+96Md8c2BAgFp8nWHrUrpqba87DoU+HVJYIun6qA+QKFoeNd3xAWq1JYE6da4nVli9GgwRpfncfRePcgmQQaIQ=="], - "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.74.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-9QggtPkSPXOCTu8Szis7auOK/sC7KdQaN+/TujP7YVVhzCAOhgdRfgv8uEz0r2tk5xdgus5rLYUrCDoZNtiRUw=="], + "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.95.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-6yG99vsXct3Uv536w6Z1s03w2makRKnE0q3eJSmf+W/IwPmO56QLk8XUA6ebu/R5peCbJ67HmcWqACH+kg/6Bg=="], - "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.74.0", "", { "os": "linux", "cpu": "none" }, "sha512-VM5VPUJ4DJIWiK+AZn8FScUqMr6OFrCAYybMYjEEi7W13ParI64MByiXTkKMqZpBmvQ9zxl9Ebq2VUOiZRJYUg=="], + "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.95.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-Eir0Z4ldh55AsQUqVDlLF4Pw3lSFXIdAl8ZNgU8tp/gTwT9JVCzWY0o3+ys9pCcpTN0vCqBwwuQfAUxzbIgvcQ=="], - "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.74.0", "", { "os": "linux", "cpu": "none" }, "sha512-SaDY1gh9rOA592J54g+gu5hkOFFQBZsMmIYHs+NRHG+Uq0OxtuuCXMWQ3vu1830Eugv5uMXyjG+bv2Z9y4IXjw=="], + "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.95.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-ceRx+K2WJ7C3tIv+XjZS28oAoZ7DY29ZcWChPdXG5M100phI72FRDYwGRlWZEeDfmkROnarLTMKnnrQAtsC42Q=="], - "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.74.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-ZATQeHZCyr6MbDveg0obD5sxLHFOghtOdC5jwVwYlvFWqtFOxctgFEG6Ef/64hYvZrWyhyCckB10AelqLopeDA=="], + "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.95.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-WbD3sM08ZDk2QE6060wK/omihQKbRm+LVzKIg4W5zNTbEhYJChciqX49UZuqW59RGF+wBUxzAup7egUIESTjUA=="], - "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.74.0", "", { "os": "linux", "cpu": "x64" }, "sha512-+aIvJyrdeD7LwCQ2WYLMUWNmnbeDRSPb40aBYtPjD9+PTqUwgJnk+HK5yLfSMeqXrMrDhE9uTmtt2y50tvjhHw=="], + "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.95.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-F4ST2ZkFIiLL9OKyRCyC0KQQpwM5WIv0GTcMiZuYVa6xSRJHR05iVRqst+arOVudEPkhP47EnbuoC9UfVCYDyg=="], - "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.74.0", "", { "os": "linux", "cpu": "x64" }, "sha512-XyktaR8lhK2qWiCK0Tk8oYD+/cgn+oHA6ddRnxSSXUKkkojkV78CmShZUxQF+yrBFs0SuW+JBOPG6hecyc/iZg=="], + "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.95.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-hEpYDZatpuxLrWlTlkwhHZ1e8QkL02aFS55BPQX1XA9iOd+yUEADGFF1iY6z+xkw6RkpzXFrtnDFe4/JNOLSRA=="], - "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.74.0", "", { "os": "none", "cpu": "arm64" }, "sha512-mzbjrPl4neaVUiJ1fUiEUxTGaSZBoiKtaoB6jmIpz9S+VOA2vDYmJpihQ82w6178V5jxziclTg8Cgj5yF6tTDg=="], + "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.95.0", "", { "os": "none", "cpu": "arm64" }, "sha512-+JwIH9/uLgQXfxBvOAKzvp616m5i0fBR5ELEBHm5D+++fStBZ+74T7YW4xBpX13zNU2blr52Swoe3GTF1JyqRg=="], - "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.74.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-vUAe9okpS2Oa5+lX67lqHMuNUvfkleRKwrUDJ/WJBsgmddvZ1mrsh2HVmuFDRzqFELhaJhFaCNOuR6a7L3rtIA=="], + "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.95.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-pzJgcp3WkOSchukg5y5pn5mVIQ6P83RDI79YJ9gQZKed1pOgjhrmlc5AMizjuq6/P8VifhxzBsMqYI6LLjO2TA=="], - "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.74.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-yyXXJyYYSXL4I8K8jAWjJs+J3fa9gH2JmEbo4f5adm+1tNC9itseicBNuwK7BDHvqQ5J534s+yDULu89vYL2ZQ=="], + "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.95.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-54MeQvLRXkJqF1nEFs7wb73SrnurZJQy9fVK4NdEwumNKVwyUUxpGHhvfDMIY2NqJZS7kz0pY9uVty5664Gt1Q=="], - "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.74.0", "", { "os": "win32", "cpu": "x64" }, "sha512-VTC9IYTIMrVUk/i6Ms1ohzzDKZFkWn0KU2OBbPBzgmVZ2V30165T/zK4LztTr0Xgp9fZ1qQZ1rsZAu/rEmySlA=="], + "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.95.0", "", { "os": "win32", "cpu": "x64" }, "sha512-I/Fn+Fed1qzb1k2uRjMe2VRtRN1+ZObyU+E76B6v/Ul3Z6JdeAW5zBHSe0n5d8a0ZyU4iorzVy0Rw9LYgo3MSQ=="], "@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="], - "@radix-ui/number": ["@radix-ui/number@1.1.2", "", {}, "sha512-ceTwaxc4I5IOi97DgCotl3pqiyRGvffcc0oOsE2dQYaJOFIDsDt4VWG6xEbg1QePv9QWausCEIppud/tJ1wNig=="], - - "@radix-ui/primitive": ["@radix-ui/primitive@1.1.5", "", {}, "sha512-d86WIWFYNtGA0H/d8exstrTRTp7eWJYlYJbtNofxr/3ljupZYn6EFDG/Qgu/0Kc8v7yMUxySagqJsL1+PdYjWg=="], - - "@radix-ui/react-accessible-icon": ["@radix-ui/react-accessible-icon@1.1.11", "", { "dependencies": { "@radix-ui/react-visually-hidden": "1.2.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-HQDOFTKwSnmUij6l54wYJJtxTAnxI71+YJLOrjm2ladFB8HAV5Jt7hwaZPhWTGBkYoW4+ZAOfNZrLDh/qvxSYA=="], - - "@radix-ui/react-accordion": ["@radix-ui/react-accordion@1.2.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collapsible": "1.1.16", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-BpZJNmetujnGgUI6OX0jEhEmlA46WPqgub8Rv09Kyquwd0cc1ndMKpiPYCjmBU6KSSRPAMtgLpEoZSG/tdNIWQ=="], - - "@radix-ui/react-alert-dialog": ["@radix-ui/react-alert-dialog@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-dialog": "1.1.19", "@radix-ui/react-primitive": "2.1.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-FA7n1f6D/DwGE0+AWxiY5LacNbbExQuEgMubeG06idEaH+mSLuf9dp/qBNqOnvbTQ+4gZ2ue1RATF1Ub91Mg5g=="], - - "@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.11", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Kdil9BB1rIFC/khmf4hC35bn8701AJcizTU7G7cUbEbk5XqqbjDuHW60uUfKqO5WojjZcbAW51Q7P0hRmMLw8A=="], - - "@radix-ui/react-aspect-ratio": ["@radix-ui/react-aspect-ratio@1.1.11", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-IUAhIVpBUvP5NNICjlaB1OFmtRLGqQqTF3ZOSGPoq3XeLXRFtHiWTRxSVEULgOd9GQR2c7tsYqDnhUennapZnw=="], + "@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="], - "@radix-ui/react-avatar": ["@radix-ui/react-avatar@1.2.2", "", { "dependencies": { "@radix-ui/react-context": "1.2.0", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-is-hydrated": "0.1.1", "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-sST0qh8GzOB7besQ3tMLWLyngnRuSk0gc/Hm+667KYKQFCt6Y6ZXv25WlqM7dIDK54ULCh5+CHmk4LIolzfz+A=="], + "@radix-ui/primitive": ["@radix-ui/primitive@1.2.0", "", {}, "sha512-KABY+VMIRPJL+Vyzv/335FEhXXD/xDv8BMb1kl48/aXJZMH0LtHCTx5ga5RnxaEP3nZHtmTLf1P9vanmFX46bw=="], - "@radix-ui/react-checkbox": ["@radix-ui/react-checkbox@1.3.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-previous": "1.1.2", "@radix-ui/react-use-size": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-JroKHfQBfh+fDuzpPsBC+pESkhuq8ql4hljTguz8MWnS35cISr3d/Jhl9kYrB44FlDtxCArYdDvTx+BSsJ64rQ=="], + "@radix-ui/react-accordion": ["@radix-ui/react-accordion@1.3.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-collapsible": "1.2.1", "@radix-ui/react-collection": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-controllable-state": "1.3.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-lCZ6sbGS/7WO0j84yx4srIgOf0MRJ/sZ13RonADXxvKBym8xrxNCq5f6DibGcr38sIlwPk8/52uYdXeOPsbEDw=="], - "@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-opfXRe6nnzyGmCDPx+l1Aqo/RbqWtQal2FnsBqF9hhePp6j0LsRoBaRxcMOlTv+uYTJVtWYZKg9t9wTe+BA/ZA=="], + "@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.17", "", { "dependencies": { "@radix-ui/react-primitive": "2.2.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ=="], - "@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.12", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-slot": "1.3.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-nb67INpE0IahJKN7EYPp9m9YGwYeKlnzxT3MwXVkgCskaSJia97kG4T0ywpjNUSSnoJk/uvk12V8vbrEHEj+/Q=="], + "@radix-ui/react-checkbox": ["@radix-ui/react-checkbox@1.4.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-size": "1.1.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-KWtwhh+98ML3seZ9vO9yRY2OwaQG90dCiDAxjpSNY2AaZ3Hik3B0dsk6m0ILywo/no3A9/SozadyPMNweVT8yw=="], - "@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-rYOP8OMnuuPMQF1uhPVlGNcCDlkokKqGFE3JcxFViIkAXP7EvFWUliJAstrapypaBLJNHbZL6jGhbVDGTwmVhA=="], + "@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.2.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-fSzLb/qy1wuZSxQBcxpW0hNXYHDMWiIXDGyJGdA4+FSLknOWZsNRrTCUavxb4PI8b8lvHo/CysO6NVi5zLpo5g=="], - "@radix-ui/react-context": ["@radix-ui/react-context@1.2.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-fOE+JtN9rygNZkCnHRBEP0TAvLldlhyOxMsbwFvTP4nAs+nBmfnna+o/Zski2wkmY1YMrFC0aSzsHoLY47iLrg=="], + "@radix-ui/react-collection": ["@radix-ui/react-collection@1.2.0", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q=="], - "@radix-ui/react-context-menu": ["@radix-ui/react-context-menu@2.3.3", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-menu": "2.1.20", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-PS+gKE0z2prJ74Y0sM+brAGK4mYOHIR7TlcV5EJgUQ6E0xMvyswkK2X4yRqyganrzsRL+WCSKAPu0NQITICRWg=="], + "@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.5", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="], - "@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-focus-guards": "1.1.4", "@radix-ui/react-focus-scope": "1.1.12", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-slot": "1.3.0", "@radix-ui/react-use-controllable-state": "1.2.3", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-+HhbN2+YtkRgVirjZ2afMeutQRuGOrdkWR5+EFC58SJojGmtyNQwYzgi6tHBpOxvFHefMtPeHdgtjz0BOGxFQg=="], + "@radix-ui/react-context": ["@radix-ui/react-context@1.3.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-v5AYEocMISkbJ+1fTXzZpiFv7NRr3D2WiYbLIKf+FkmJ8VkP6d503eV2n34MFussHXY1pcoq3yfJiQH77dc4Mg=="], - "@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-C3vFhbyi4SW3PmbAi6Awpu4OzJtd0MxGurvSsYtr7p7nM8RNB3VAF3CUmnp2j50knpkrRcB7+ycVXzgLgF6yNA=="], + "@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.3.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-dismissable-layer": "1.2.1", "@radix-ui/react-focus-guards": "1.2.0", "@radix-ui/react-focus-scope": "1.3.1", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-portal": "1.2.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-layout-effect": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-+0E4qvVTwjAWra9sEhJ+9BTsvHE00zkUuNw1VGh7S+Gc13dfYk+S1PVQdchWDj+XYHhAai7Z7IpzXVDCGsDplg=="], - "@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-effect-event": "0.0.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-b0XaRlzn2QKuo10XyNgi2DAJDf5XC9d1nD3FJcuvCjbR7+4Ad28zmZsLsqx+hvDEzMnRuZaZxZm9gYObV6RmRA=="], + "@radix-ui/react-direction": ["@radix-ui/react-direction@1.2.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FtRA52a/r+LKStFT+neLUm+8vSe7wbzkbQGGeU8ixFiwC8NU14Evoq9ATECqL3eGbcUzJR4fyfA4KkK/q6dfqg=="], - "@radix-ui/react-dropdown-menu": ["@radix-ui/react-dropdown-menu@2.1.20", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-menu": "2.1.20", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-slfm+rRaZRuQBvHq60lXvSVUPhid0IPtjSZzIuUlWZMUs01iYZNlGS3mJgRD3ChLQVBAYlKiL/tFyWGX+dz8Xw=="], + "@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.2.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-callback-ref": "1.1.5", "@radix-ui/react-use-effect-event": "0.0.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-KIfDcAsx+oVylFZ4xryVKusJUrLLhTQmfnJW4kwk4Km5myvhHCrj04hnWWUC166+xD4DHdH8tQGylwYX1h6+Pg=="], - "@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-cot/aB/mOm0IYVYTTmQcEEK1M48lZWi8FlYe5nDPQQ8NYZUlXEFgncJ9p2Kzer3RKSrY7cTTpEMLZKNo9QoP5Q=="], + "@radix-ui/react-dropdown-menu": ["@radix-ui/react-dropdown-menu@2.2.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-menu": "2.2.1", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-controllable-state": "1.3.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-XsHcmYG2AcqnvTqrOXXWcMrhquEIlqucizuDH1MV/qMRW+DndpBCMvNeTRXOxqmG1H5j89M/+I0/34Zdd+zDcQ=="], - "@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.12", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-callback-ref": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-jjk/lqTeNL0azUx5ZYzVrl4NgaDIrdzTNE4mABV9yBFI7FQqN7pIgzV1bTleUezP2QiTGA1BFTqY8MegDgWX9A=="], + "@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.2.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-MPm5R0iRGUDrDnPNxmLBkv+X7pN4XKzt+MbWJEuJQsH3NFH4omrbpXpucyYCCKTSt+na/ZxGhEWQrWTZ0285cA=="], - "@radix-ui/react-form": ["@radix-ui/react-form@0.1.12", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-label": "2.1.11", "@radix-ui/react-primitive": "2.1.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-JTX94E4LDL91rzLg7X0mHPdxr0A8JEdVwZEmeOwZJSMDHCGW5DFtSlTSJozUyUs807IQmnvbfzKZFVCK5DmkqQ=="], + "@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.3.1", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-callback-ref": "1.1.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ugeMhbXt4y5S2T1GnIqbWDKEN962PDwnX1fN0eKOOgf5f63Dh2mn8F1FUySlgW0iF6GiVsRF32DzuDIWTUyQJg=="], - "@radix-ui/react-hover-card": ["@radix-ui/react-hover-card@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-popper": "1.3.3", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-2KTgMLQtKvicznQgbindEI2RZ3QbDIwU5gabjUPwFJsormjGDz+rUvO4NANmYwzEEpTcTONUt33vBHIfTIVSfw=="], + "@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], - "@radix-ui/react-id": ["@radix-ui/react-id@1.1.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-orBC88futVpqCmhX1p4cvquNHsELQ+w+vBJnuj3ftETI5bJb0bZn3Tqu3SWN2IOcPycTnMGnhwoermvISt72sA=="], + "@radix-ui/react-label": ["@radix-ui/react-label@2.1.17", "", { "dependencies": { "@radix-ui/react-primitive": "2.2.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-xmj7MN/drx1oUAXkfiFIvyDmGNUIN/omGobvA5oAoNqu9zO2MkISYGZOkBcqSzs/UZXXwV+/3ACRE7q7mGcmkA=="], - "@radix-ui/react-label": ["@radix-ui/react-label@2.1.11", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-3PKvDDxOn62k0oV1n4QtNtD2vpu+zYjXR7ojLBPaO6SPvhy53yg0vAmgNeBQeJW5rV3dffoRG+HYfLBZuzw0CQ=="], + "@radix-ui/react-menu": ["@radix-ui/react-menu@2.2.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-collection": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-dismissable-layer": "1.2.1", "@radix-ui/react-focus-guards": "1.2.0", "@radix-ui/react-focus-scope": "1.3.1", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.4.0", "@radix-ui/react-portal": "1.2.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-roving-focus": "1.2.1", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-callback-ref": "1.1.5", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-G34BsU90SBj5foYpz8pQqq/Q0Dlfyyl6KitWEfRwXC0QvfwhWNAwS49DWP2+rRJ0iwv20Z2Qx7Sk+T03bGo5JA=="], - "@radix-ui/react-menu": ["@radix-ui/react-menu@2.1.20", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-focus-guards": "1.1.4", "@radix-ui/react-focus-scope": "1.1.12", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-popper": "1.3.3", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-roving-focus": "1.1.15", "@radix-ui/react-slot": "1.3.0", "@radix-ui/react-use-callback-ref": "1.1.2", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-VsUrXxFe9d2ScbZF0fR/oPR1+qjyeLs5p0jzG8h90puMoA9bq4SirYlXbE+USRg9Q2qTeJSFNqjw2nts8jJe4w=="], + "@radix-ui/react-navigation-menu": ["@radix-ui/react-navigation-menu@1.4.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-collection": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-dismissable-layer": "1.2.1", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-callback-ref": "1.1.5", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.13" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-XPPZjkeyCSMNNvt0FyDv/PUauG7Ow4GwHQ/XZSwW36F/TS7rR4HFTsXH8ewLnXTOLn3x96/pmTPNQIVoTX/86g=="], - "@radix-ui/react-menubar": ["@radix-ui/react-menubar@1.1.20", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-menu": "2.1.20", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-roving-focus": "1.1.15", "@radix-ui/react-use-controllable-state": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-gzFZvybgmwYsFBWDqanycIoEYnhyk8MMnuLamdFVHUZYGp4COM+sqXiwbnn0VMWqGLeeU7GV7jm+dXRa+Wufag=="], + "@radix-ui/react-popover": ["@radix-ui/react-popover@1.3.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-dismissable-layer": "1.2.1", "@radix-ui/react-focus-guards": "1.2.0", "@radix-ui/react-focus-scope": "1.3.1", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.4.0", "@radix-ui/react-portal": "1.2.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-layout-effect": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ZNxvXRx5W2Wos4fXCXb5lpdqN0Z5chf+mStOUOTr4ik7d+62MRvoe9rzCA/eGNg36lxXqSrKEKmwuZEcUrIstw=="], - "@radix-ui/react-navigation-menu": ["@radix-ui/react-navigation-menu@1.2.18", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-layout-effect": "1.1.2", "@radix-ui/react-use-previous": "1.1.2", "@radix-ui/react-visually-hidden": "1.2.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-K9HiuxZ6xCwSaHcIuUpxyhy4w5gpwzWjh9dHTSbMN3Ix4qAyVObS9RlU3zMycb0PO3v9Tpk0BXMwWvXOUbVXew=="], + "@radix-ui/react-popper": ["@radix-ui/react-popper@1.4.0", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.17", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-callback-ref": "1.1.5", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-rect": "1.1.4", "@radix-ui/react-use-size": "1.1.5", "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-yCWRvLeGv9Pz3+efwHqGPp70mZ56r3kfIgQVF56Oj2aAa4uP/Tb+IE59wNcc+758rctqbCKx4LbK8II/r7Bn0Q=="], - "@radix-ui/react-one-time-password-field": ["@radix-ui/react-one-time-password-field@0.1.12", "", { "dependencies": { "@radix-ui/number": "1.1.2", "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-roving-focus": "1.1.15", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-effect-event": "0.0.3", "@radix-ui/react-use-is-hydrated": "0.1.1", "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-nQLu5OAcORDQp1EHAv6k3mJGV1hjMTw2NTGVAsGE1g/mWeNqAd1R5jyaAs3U+A8ZD/W8XNPY2yKT0ZdQnqo3NA=="], + "@radix-ui/react-portal": ["@radix-ui/react-portal@1.2.0", "", { "dependencies": { "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-StX7xXnaRU41VvFtMm9zlhVGz8XF6GmWWTXftkQaY+tqVkbs/R9UmAp5mLzHHapk5hM9RMZQvO/3usyIP/g42g=="], - "@radix-ui/react-password-toggle-field": ["@radix-ui/react-password-toggle-field@0.1.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-effect-event": "0.0.3", "@radix-ui/react-use-is-hydrated": "0.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-gB1Mr8vzdv1XzDjrtJTXmL0JORRs1B4g7ngUs0F+H2VvMOwXTZMTmLCl0wZZ3m7ylX8TssI7NCvgiSHmLuTm/A=="], + "@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.11", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Z7/atlkab36Z8hm+V8zYc79r0W+tiOB1o0tun1By94JyadkekLQmtEAnBSP9XKXBNQsStoStS4+gX10JpS5akA=="], - "@radix-ui/react-popover": ["@radix-ui/react-popover@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-focus-guards": "1.1.4", "@radix-ui/react-focus-scope": "1.1.12", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-popper": "1.3.3", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-slot": "1.3.0", "@radix-ui/react-use-controllable-state": "1.2.3", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-jkrTdQVxnIB8fpn0NyyxW9CTB5aCXZZelVz5z+Xmii6g5WxMqS3fInNslZ63puP39+Puu4jYohUK31y3dT87gQ=="], + "@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.2.0", "", { "dependencies": { "@radix-ui/react-slot": "1.5.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-HCTSPMNqv55Qk0IX4geJbpyXazmqulcimwuyjxTkKi29v+QZbG2Zho9BnbBq4YS2PF+KlNb2CXoLz66uUmblkg=="], - "@radix-ui/react-popper": ["@radix-ui/react-popper@1.3.3", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.11", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.2", "@radix-ui/react-use-rect": "1.1.2", "@radix-ui/react-use-size": "1.1.2", "@radix-ui/rect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mS7dGpyjv6b+gsDjLF7e0ia1W4Im1B1hSCy2yuXlHuvnZxHKagfDaobt/KAKt27EpZMit2pss8eJBVyVjEWM+g=="], + "@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.2.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-collection": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-callback-ref": "1.1.5", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UwraORzVUeEPMclhO1p0vz0qI+TbdDLO9i+FiOqhJyHKwdpCRCck9yVEscUnAMIzCiuNoQa8D4A9bIpOPXGt6Q=="], - "@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.13", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-z3oXfmaHLJTF1wktbjgD6cn9jiEbq3WSondB10LIuIt2m2Ym4iJlrW04/euMwENDdWDdE7z+OuY7Qyp1YpRSwA=="], + "@radix-ui/react-scroll-area": ["@radix-ui/react-scroll-area@1.4.0", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-callback-ref": "1.1.5", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-CFrLqHNejWq5FhKAcj9V/WPGRsol76HBQto81NdOBVFEOqIEkJkKIJt0Z824A/9hHLCtoiR/Kw3euRgzXP2pxg=="], - "@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.7", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-zBZ4QM5XG3JRanDmqXYf3MD6th4AFXFmgU6KNMFzUaV6F3uw9I5/zjMUvFriSEn5ewo1nxuibvyxJdmLlDcslA=="], + "@radix-ui/react-select": ["@radix-ui/react-select@2.4.1", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.2.0", "@radix-ui/react-collection": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-dismissable-layer": "1.2.1", "@radix-ui/react-focus-guards": "1.2.0", "@radix-ui/react-focus-scope": "1.3.1", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.4.0", "@radix-ui/react-portal": "1.2.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-callback-ref": "1.1.5", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.13", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-888ZwW0Md6GyptuqYABRX9nLKgoYfcooCyBBvVaX5Jp3e+8Jp2i4Zo/Uy50Hm+Ysn2JfloQXstW4U36w8teVtg=="], - "@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.7", "", { "dependencies": { "@radix-ui/react-slot": "1.3.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bC3NiwsprbxKjuon9l7X6BUTw7FPVzEYaL92MPEY5SCd/9hUTPXVFtVwRix7778wtRsVao+zE062gL79FZleeQ=="], + "@radix-ui/react-separator": ["@radix-ui/react-separator@1.2.0", "", { "dependencies": { "@radix-ui/react-primitive": "2.2.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-1jUAap0wZEqVP05Ou7kJgRxe/W+Qftng+rUNWGa0qkKbv9r5pWTG3E7a3ELKo2eJoHKMECnzuYrZpSyO1YgcYQ=="], - "@radix-ui/react-progress": ["@radix-ui/react-progress@1.1.12", "", { "dependencies": { "@radix-ui/react-context": "1.2.0", "@radix-ui/react-primitive": "2.1.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ZPHyI0JyzoH/rP0tq2uRaIZTj/4s8+kAbqPz+e2N8+ejHvwPJ889dHhqn+vh7PNvNeq+boAoH9yzqeoShzwF2w=="], + "@radix-ui/react-slider": ["@radix-ui/react-slider@1.6.1", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.2.0", "@radix-ui/react-collection": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-size": "1.1.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-IRNRR90moPqxfwCJ0XbMJIxo70W0/1ZExT/sNCxEHMaPx0SF9HoQrcPEC75+H28cFKa0b+KH63anfLYJmwKacw=="], - "@radix-ui/react-radio-group": ["@radix-ui/react-radio-group@1.4.3", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-roving-focus": "1.1.15", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-previous": "1.1.2", "@radix-ui/react-use-size": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-WwZFjWV4s3aC1QtR3k04R+oANHtX2q6fgKlc7MCEiDNlnTxCZ3H8k3mHtEgVlOejystwk1WQgarQhNOQZ2bK1g=="], + "@radix-ui/react-slot": ["@radix-ui/react-slot@1.5.0", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-tyYd9ddPXAysAbdbD9eYxgwpCSv6f3PncqVSNKQFSR5lcJVLz3cb/pANDoYrLiHBpXv7skortyUgGUWsYuPPFQ=="], - "@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-is-hydrated": "0.1.1", "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-40svmmugfM3mUN7VUDGVE1tQGOhyi8enlGD0CNJEcMM36C1f71PKM21DFgNHUfem0XnA+d8H8oN3Z9ZpJjSslg=="], + "@radix-ui/react-tabs": ["@radix-ui/react-tabs@1.2.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-direction": "1.2.0", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-roving-focus": "1.2.1", "@radix-ui/react-use-controllable-state": "1.3.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-hRoJlode+hg5ZNlR+3tkfkUliIybdTpD5lkAvHQ9yaXseGf7XVO9Ib2GPEIOuaJJbo7YWYbNpDDRfo8Dhf6/xA=="], - "@radix-ui/react-scroll-area": ["@radix-ui/react-scroll-area@1.2.14", "", { "dependencies": { "@radix-ui/number": "1.1.2", "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bBODCWZK7JTbQLHs0uIP4f73wIWatakK4OS33UzkR1x897wu0PuO658a3f+6P2GEGyDzGYMuHRatMVoAk9WZTw=="], + "@radix-ui/react-tooltip": ["@radix-ui/react-tooltip@1.4.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-dismissable-layer": "1.2.1", "@radix-ui/react-focus-scope": "1.3.1", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.4.0", "@radix-ui/react-portal": "1.2.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.13" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-NxLFGSFtZ78zVfcoOhTwR1xwqo5qx1Jh8Pw6FMZ9McCaqfRzz7/gIRahs2Oy5XlPgQ+8QkUcKbN5B0U44J/kCg=="], - "@radix-ui/react-select": ["@radix-ui/react-select@2.3.3", "", { "dependencies": { "@radix-ui/number": "1.1.2", "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-focus-guards": "1.1.4", "@radix-ui/react-focus-scope": "1.1.12", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-popper": "1.3.3", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-slot": "1.3.0", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-layout-effect": "1.1.2", "@radix-ui/react-use-previous": "1.1.2", "@radix-ui/react-visually-hidden": "1.2.7", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-L5RQTXz6Anxsf9CCv+pTgiAsUpyVj7rJxsGtmhFaEOJ++cVfXucv4qWfsIO0AIB4NAhi3yovWGVMKKS1Xf1Wrg=="], + "@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.5", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Y5GBf4NKeADoXI1geiMlMuMoURT3k9MizzzKhGb/m55H94aGigZ01PIpkvsO6lML13BA6XYAXSJ6gza7vTn5nw=="], - "@radix-ui/react-separator": ["@radix-ui/react-separator@1.1.11", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-jRhe86+8PF7VZ1u14eOWVOuh2BuAhALg/FT1VcMC4OHedMTRUazDnDlKTt+yxo5cRNKHMfmvZ4sSQtWDeMV4CQ=="], + "@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.3.0", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TAcBI7bw2ljYCbv4+zuTSd6zICu8pRt6SDN2vJ/Z06K2MXh6I9WYFe/A9ovlFDtR5HVHGm5iDxDoABm/++dbKg=="], - "@radix-ui/react-slider": ["@radix-ui/react-slider@1.4.3", "", { "dependencies": { "@radix-ui/number": "1.1.2", "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-layout-effect": "1.1.2", "@radix-ui/react-use-previous": "1.1.2", "@radix-ui/react-use-size": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-CWVVj+XaTom0SKCqw1EUgb0NuiLwS+N3OFG73mVEezKEjgNIvZiu0EevMelSSU+CbX3owbqJweG2gPU31WGC5A=="], + "@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.5", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg=="], - "@radix-ui/react-slot": ["@radix-ui/react-slot@1.3.0", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-MojKku4U/miO8Av4Dkb+ctMAQx7JmY96LmtDQlAarCRtd7rN52QCSzBF+XAvr5S6coSVj9HEPBgHAHKEJVk/WA=="], + "@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw=="], - "@radix-ui/react-switch": ["@radix-ui/react-switch@1.3.3", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-previous": "1.1.2", "@radix-ui/react-use-size": "1.1.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-1+mlB4/lxJfk5tgJ4g+R5mUCbRpPE1T9+UsEyeLYbGgMtwiMgmuTnfKz4Mw1nHALHjuwyxw4MLd4cSHn6pNSlQ=="], + "@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], - "@radix-ui/react-tabs": ["@radix-ui/react-tabs@1.1.17", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-roving-focus": "1.1.15", "@radix-ui/react-use-controllable-state": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-nRyXnrAVCwjeXcHbvEbLS6ndbTeKHG1RqCP4A8Gw5L4cemDzPXdD8rAmr6wet0v57R69wGvuIIsFjHSVkZiMzQ=="], + "@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg=="], - "@radix-ui/react-toast": ["@radix-ui/react-toast@1.2.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-layout-effect": "1.1.2", "@radix-ui/react-visually-hidden": "1.2.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-SxfVZfVOibWKWdkf0Xx1awW2d09fQu4V4PXDY1j5hi4MVf7MWdJZqTBJMa1KWtOr1S6GGtCk02nniZ0Iia+dHw=="], + "@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.4", "", { "dependencies": { "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ=="], - "@radix-ui/react-toggle": ["@radix-ui/react-toggle@1.1.14", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-use-controllable-state": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-QI/hB65XKWACA66P64A+aHxtLUgHJeJLkaQa+awUNXT6T3swndtY5DojeHA+vldrTspMTtFBd7HfZ9QGbM1Qrw=="], + "@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.5", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-V1McDQkMGzgivwqdu7u96APs7oi0Jvj9LTzgq3WWrDZqxWdAqU9yZnZQqk5OizGFR8badUQwZsrlao7MOlWYOA=="], - "@radix-ui/react-toggle-group": ["@radix-ui/react-toggle-group@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-roving-focus": "1.1.15", "@radix-ui/react-toggle": "1.1.14", "@radix-ui/react-use-controllable-state": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-gIC5Q+Xljg7lmUdzSuDoy0t97yZn1sZl00Ra37ZvKrYdWnQLU6sWLd09yG8cIB9jUAlQfHgJ2ACAG00MFwsqSQ=="], + "@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.13", "", { "dependencies": { "@radix-ui/react-primitive": "2.2.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-feijiN1oPk4rck4u9Dm9tsU4mT6Wp9oeEEhaz1WUEs1VuqLf8xzsFG+Qk+uWq6TnMH9O+WRECRg0NftyP9E4Fw=="], - "@radix-ui/react-toolbar": ["@radix-ui/react-toolbar@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-roving-focus": "1.1.15", "@radix-ui/react-separator": "1.1.11", "@radix-ui/react-toggle-group": "1.1.15" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t/iEuVjUnXXtrsGK40AA43uIx37sn3AqZ7oAVnPICK6lFJP6dzMzWR3U9b6eCfFjb6wtSEqkJ9Rn9xDjiOx20g=="], - - "@radix-ui/react-tooltip": ["@radix-ui/react-tooltip@1.2.12", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-id": "1.1.2", "@radix-ui/react-popper": "1.3.3", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-slot": "1.3.0", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-visually-hidden": "1.2.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-U3HoftgWnmla78vzQbLvKKb7bUYJxoiiqYFzp1wu/TBMyDqMZSuCl3aRICsD6EfVEwcJD2mumGDGUXLFVqQHKA=="], - - "@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-xCso9j1/u8sEgP1RNHjFrXJLApL8LiqOkI1R4ywuN00rxWdYg4oQXuwKLS3i0j5NWLromUD27/4nlxj2UFVvIw=="], - - "@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.3", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.3", "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-PLzC90MS+ReootmjC597dvopoelpZ8Q61HJkDXZSExitIq7PL55vHNnesAHwguHK0aPfBnpdNzQtv1uliaqQrA=="], - - "@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.3", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-6c8ZqvPTWILEKnyVkP53EGRCcpnJiKTC21sS/6R1GF5xKyHJJWQEPfkqlcgUkdRQivd6tb23abUwe4ngWmY0JA=="], - - "@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.3", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-3wEkMiPHXha/2VadZ68rYBcmYnPINVGl4Y3gtcM7fKRjANk0OscK+cdqBgUWdozb7YJxsh0vefM7vgAMHXOjqg=="], - - "@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-qwOiz4Tjo8CNnrOLAYUMXeZwDzXgXpvK4TKQPmWLECM9XoWvA6+0Z2/7Ag3A4ivjS4ovbLJPbskkxioFyBhr8A=="], - - "@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jrBWOxZITuGcnjRCM2t2U5ZPkCLxD+Ym6DjfssS5haTj2iiak/DOb64JeN6OdLfLgptb6/e2kKR+ZuTrGoZTPA=="], - - "@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-IGBQPtRFdhN6MQ8dbegVmBq1LVZluya3F1jWY+puIcQC3MHctRwTDSBWCkL/3ZcnMJLTMJ++Z+ktmvg0F89iCw=="], - - "@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.2", "", { "dependencies": { "@radix-ui/rect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-d8a+bBY/FxikNPlgJJoaBHZX+zKVbWHYJGTLnLvveQgFSTntkGdEKv3JDtHrMS0DNYpllz2nRsTLGLKYttbpmw=="], - - "@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-giWQp+4mxjBPt4KZ0MmyuykFNWfbDxKt4x+fPkRYmgRFJSbCZFzUglvMb/Kjn38tm10YP4ufiQZDx3zna4LU6w=="], - - "@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-1wNZBggTDK3GRuuQ6nP4k2yi7a6l7I5qbMPbZcRsrGsGVead/f/d5FhEzUvqFs0bcrDLx7n1zKQ3JvLR6whaaw=="], - - "@radix-ui/rect": ["@radix-ui/rect@1.1.2", "", {}, "sha512-xnXE7wG13PI+cxieVssYXlQJuYVRhH9NBoxt3KNwzghDIA69GMm7d4wXRouHIYjE+KvS6U/MsMO73NdS2MH9ZA=="], + "@radix-ui/rect": ["@radix-ui/rect@1.1.3", "", {}, "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw=="], "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.3", "", {}, "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q=="], - "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.2", "", { "os": "android", "cpu": "arm" }, "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg=="], + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.69.1", "", { "os": "android", "cpu": "arm" }, "sha512-sCxEAuzIiiqKvOqniRjG7hA5XdxnjGI75fizhb8WoycNP+HIKtO/BQGtVCxtlWZD8+xI+WvtHYXKDiwlf8skDg=="], - "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.2", "", { "os": "android", "cpu": "arm64" }, "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw=="], + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.69.1", "", { "os": "android", "cpu": "arm64" }, "sha512-jXds5O/FbKFEblo7pZzaiqJk8mK0A2jH3sxZy0t8XyyGT0L6NGPkURBlCySOQj7usO7o8F1oeKdcGISQjIC4rA=="], - "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.62.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A=="], + "@rollup/rollup-android-x64": ["@rollup/rollup-android-x64@4.69.1", "", { "os": "android", "cpu": "x64" }, "sha512-OsNys8AqzoeyfCCHxB8yyOGOlg2IsCqB6jZG3V7lP1k42n96+D/5weBUxAfDr4F9VgvDaT1KQZCpCokw4n6+pw=="], - "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.62.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA=="], + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.69.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-lMId5BFhUyDt/PsbeNkuU5mRz8pT8z3uH7UEVNEognzAcCeURGE6wPHCYDGJxk26DEs+hMLgHorbcAVKGctCNg=="], - "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.62.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw=="], + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.69.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-LXGbkadbp+YtMyeFz4+OUtEU9jJs/DFtlWb6+xXig1OnM6UQBmHAO1TxKsO1prbWB8/bKzGZl0dusz3hdASZxg=="], - "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.62.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg=="], + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.69.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-1TqVjgaRHdf9Lt8VDUrGGp0jnRcDPz+bQzXinLec8b45HdE+xhMWQCfL69aLhGZcPGXLQ/d5GW0Hubl/7CSSzQ=="], - "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.62.2", "", { "os": "linux", "cpu": "arm" }, "sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg=="], + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.69.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-BiHfDJHCa2esEDIOJCI2uyakP8Ln9iaUrKdVb0+nUMWXcaoTvJT5ZURhe86pVp8G7QQ3iNQfHWOfBDLJeOZVgQ=="], - "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.62.2", "", { "os": "linux", "cpu": "arm" }, "sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA=="], + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.69.1", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-/JYdUwNaWv+qFZEtxBUrbM5eiJx1DplFtTqN0Buc9gdOJBw7aKX5vqpCk4823BoLP0s4A9DYg2qEhOZDwsw/Lg=="], - "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.62.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA=="], + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.69.1", "", { "os": "linux", "cpu": "arm", "libc": "musl" }, "sha512-7AATkTU0K8z8sIguTsUKO2i7OL8Q/r//1FfWxtwE5c6CzoIp03k0LP9JAAjXl7L520jbWt7TcnJ897e1XBumYw=="], - "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.62.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ=="], + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.69.1", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-fgcL+1NuR6sc1W48xMoDe0wyAWGrbMazJr0XWkr2HmFf4RX/D5nI7H6qx63juiJd3h72qfxIXaLHcTszMq1XxQ=="], - "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.62.2", "", { "os": "linux", "cpu": "none" }, "sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg=="], + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.69.1", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-QEQcLTo84tZ1Z9s8vwuCT9KsQmxy+WGBssFTZU8BODHR4f9uywy0R7veeAipnY9JPAI+V45ZDJ89ceoYLLX4SA=="], - "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.62.2", "", { "os": "linux", "cpu": "none" }, "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ=="], + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.69.1", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-102cDq5JJvbxdtUDb5LwzOEjq0yStgKHda9SEg3d33oZGC5xkNIdLKUDqYGtR1SJN1vGV3QtQiBxUZdNopC1Hw=="], - "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.62.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A=="], + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.69.1", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-u3Stzh5CjPKmLnrdCoxk6EALdkAlxic6TSvgl/+VWMUgdOw12iq1FtTlmbDkxsZKmyKz/c/MxW5Qjqbf8oz+nw=="], - "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.62.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w=="], + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.69.1", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-swxB3KVxsUisFEIltDUi9TzdfeJcDfK+UPAtSwYMxL2Vb66GenjayIMkwZ/63E6c/YXXLlD5XWrAlvQwzwVopg=="], - "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.62.2", "", { "os": "linux", "cpu": "none" }, "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg=="], + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.69.1", "", { "os": "linux", "cpu": "ppc64", "libc": "musl" }, "sha512-PjZLbzl5r+nzSwxqY01lTxB3BjfsuExdBmBGKR1ZVZkXGaYSovLtfMmWzmUid6wmfJB8kXAkBruNxZ3TsSNQ9w=="], - "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.62.2", "", { "os": "linux", "cpu": "none" }, "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q=="], + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.69.1", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-jfxumKunDjw0loeYY8UROvqlHj387mi+uTX17GNoJW6tNVR27Bsdo5tFT+DuK3gwVSTqRbLiI8WdeQ9ToBo/rQ=="], - "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.62.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg=="], + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.69.1", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-mAq8rMA5WzZR3SssDWsYuytH+N81PN8QajlkX9fMz6HVJk8V3oYTchtsM9XLLCmg8h3/ApKo+X64+HQbOjWxyA=="], - "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.62.2", "", { "os": "linux", "cpu": "x64" }, "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A=="], + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.69.1", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-pRZh+DrTUS83CYGLDkAFX9QigC9C2AwCQ93jxcZfq17W6F99LuUqwFHA9AhgZcpV9mg+2L1DiSlpX4vh/jU2jg=="], - "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.62.2", "", { "os": "linux", "cpu": "x64" }, "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg=="], + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.69.1", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-Kbm4FoPozFvVHKMXzvgorwSMy7wdA2mDY/dk3gsoHNxmNz9cslSmxf1V3KgvT99v62MNOqUYS+3ospRZ2l+hoA=="], - "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.62.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg=="], + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.69.1", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-RNstQiIU1ViUIrrK9irG/jA3TD2w9o9OCgcavyR0GyzM9B6KvqbCc2tnSfwY5q0f6rS2ZWpe74tZX3Q7iAsCpg=="], - "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.62.2", "", { "os": "none", "cpu": "arm64" }, "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA=="], + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.69.1", "", { "os": "openbsd", "cpu": "x64" }, "sha512-tpm4c2fYArjIFYQlhXzchMT8ex9egIZuqa8L68YLIOPsPOA7Q+h+vU6Y6yf/asODtPToSJGDtUYNELPx56YsTg=="], - "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.62.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg=="], + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.69.1", "", { "os": "none", "cpu": "arm64" }, "sha512-bTk0Q4MazBUJiAatuiB94cxEsh1R6SdBG8W7lxUQEoYoI+lrZK2173lImxWa1hZ8SGXCnN4TASxQj8Q5iqdGaw=="], - "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.62.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q=="], + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.69.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-bUDnKDQTlUWAZ+FME2Tn6MoEW2xmcfROZrqr0BKSTL4lXfepqNI0aXZVFuQb4P1KzUHnOPNesSjjALzY/fZWGg=="], - "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.62.2", "", { "os": "win32", "cpu": "x64" }, "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg=="], + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.69.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-jEkve8EoQY2CB8W99GM4bbi1/aAncAOIgd/d2uCf2bE1wReqyvEz11rvuq5CkXsh3MfWNF6yFVBCQRz6Do53jw=="], - "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.62.2", "", { "os": "win32", "cpu": "x64" }, "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA=="], + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.69.1", "", { "os": "win32", "cpu": "x64" }, "sha512-xdR6tc+o1eH1EhG0dSZECD2NVGmdZE9Xobw0Fbw+K0HiiN4ZIxNbvbcsGRJjtX9cc/wRyudPKFw9n/uuRi/eYw=="], + + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.69.1", "", { "os": "win32", "cpu": "x64" }, "sha512-cD0egoYNA3Lx+HH+Eo76kr9aBvgd46fCKRU77BHIJCR2dMs01YD6HPpjUDiLc5ssdXhYQGEHt5PGn6oltVTL9Q=="], "@shikijs/core": ["@shikijs/core@3.23.0", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-NSWQz0riNb67xthdm5br6lAkvpDJRTgB36fxlo37ZzM2yq0PQFFzbd8psqC2XMPgCzo1fW6cVi18+ArJ44wqgA=="], @@ -630,7 +587,7 @@ "@shikijs/types": ["@shikijs/types@3.23.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="], - "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.0.2", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="], + "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.1.0", "", {}, "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ=="], "@sinclair/typebox": ["@sinclair/typebox@0.34.52", "", {}, "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw=="], @@ -640,47 +597,45 @@ "@tabby_ai/hijri-converter": ["@tabby_ai/hijri-converter@1.0.5", "", {}, "sha512-r5bClKrcIusDoo049dSL8CawnHR6mRdDwhlQuIgZRNty68q0x8k3Lf1BtPAMxRf/GgnHBnIO4ujd3+GQdLWzxQ=="], - "@tailwindcss/node": ["@tailwindcss/node@4.3.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="], + "@tailwindcss/node": ["@tailwindcss/node@4.3.5", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.5", "jiti": "^2.7.0", "lightningcss": "1.33.0", "magic-string": "^1.1.0", "source-map-js": "^1.2.1", "tailwindcss": "4.3.5" } }, "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g=="], - "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.3", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.3", "@tailwindcss/oxide-darwin-arm64": "4.3.3", "@tailwindcss/oxide-darwin-x64": "4.3.3", "@tailwindcss/oxide-freebsd-x64": "4.3.3", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", "@tailwindcss/oxide-linux-x64-musl": "4.3.3", "@tailwindcss/oxide-wasm32-wasi": "4.3.3", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" } }, "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA=="], + "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.5", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.5", "@tailwindcss/oxide-darwin-arm64": "4.3.5", "@tailwindcss/oxide-darwin-x64": "4.3.5", "@tailwindcss/oxide-freebsd-x64": "4.3.5", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", "@tailwindcss/oxide-linux-x64-musl": "4.3.5", "@tailwindcss/oxide-wasm32-wasi": "4.3.5", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" } }, "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg=="], - "@tailwindcss/oxide-android-arm64": ["@tailwindcss/oxide-android-arm64@4.3.3", "", { "os": "android", "cpu": "arm64" }, "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw=="], + "@tailwindcss/oxide-android-arm64": ["@tailwindcss/oxide-android-arm64@4.3.5", "", { "os": "android", "cpu": "arm64" }, "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q=="], - "@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/oxide-darwin-arm64@4.3.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw=="], + "@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/oxide-darwin-arm64@4.3.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ=="], - "@tailwindcss/oxide-darwin-x64": ["@tailwindcss/oxide-darwin-x64@4.3.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw=="], + "@tailwindcss/oxide-darwin-x64": ["@tailwindcss/oxide-darwin-x64@4.3.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ=="], - "@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/oxide-freebsd-x64@4.3.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw=="], + "@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/oxide-freebsd-x64@4.3.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg=="], - "@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/oxide-linux-arm-gnueabihf@4.3.3", "", { "os": "linux", "cpu": "arm" }, "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ=="], + "@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/oxide-linux-arm-gnueabihf@4.3.5", "", { "os": "linux", "cpu": "arm" }, "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA=="], - "@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/oxide-linux-arm64-gnu@4.3.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w=="], + "@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/oxide-linux-arm64-gnu@4.3.5", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ=="], - "@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/oxide-linux-arm64-musl@4.3.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA=="], + "@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/oxide-linux-arm64-musl@4.3.5", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw=="], - "@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/oxide-linux-x64-gnu@4.3.3", "", { "os": "linux", "cpu": "x64" }, "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w=="], + "@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/oxide-linux-x64-gnu@4.3.5", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g=="], - "@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/oxide-linux-x64-musl@4.3.3", "", { "os": "linux", "cpu": "x64" }, "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img=="], + "@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/oxide-linux-x64-musl@4.3.5", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg=="], - "@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/oxide-wasm32-wasi@4.3.3", "", { "dependencies": { "@emnapi/core": "^1.11.1", "@emnapi/runtime": "^1.11.1", "@emnapi/wasi-threads": "^1.2.2", "@napi-rs/wasm-runtime": "^1.1.4", "@tybys/wasm-util": "^0.10.2", "tslib": "^2.8.1" }, "cpu": "none" }, "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ=="], + "@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/oxide-wasm32-wasi@4.3.5", "", { "dependencies": { "@emnapi/core": "^1.11.3", "@emnapi/runtime": "^1.11.3", "@emnapi/wasi-threads": "^1.2.3", "@napi-rs/wasm-runtime": "^1.2.2", "@tybys/wasm-util": "^0.10.3", "tslib": "^2.8.1" } }, "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw=="], - "@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/oxide-win32-arm64-msvc@4.3.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ=="], + "@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/oxide-win32-arm64-msvc@4.3.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg=="], - "@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/oxide-win32-x64-msvc@4.3.3", "", { "os": "win32", "cpu": "x64" }, "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw=="], + "@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/oxide-win32-x64-msvc@4.3.5", "", { "os": "win32", "cpu": "x64" }, "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg=="], - "@tailwindcss/vite": ["@tailwindcss/vite@4.3.3", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="], + "@tailwindcss/vite": ["@tailwindcss/vite@4.3.5", "", { "dependencies": { "@tailwindcss/node": "4.3.5", "@tailwindcss/oxide": "4.3.5", "tailwindcss": "4.3.5" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ=="], "@tanstack/history": ["@tanstack/history@1.162.0", "", {}, "sha512-79pf/RkhteYZTRgcR4F9kbk84P2N8rugQJswxfIqovlbRiT3yI7eBE+5QorIrZaOKktsgzRlXh1l/du/xpl4iA=="], - "@tanstack/query-core": ["@tanstack/query-core@5.101.2", "", {}, "sha512-hH5MLoJhF7KaIGd7q3xTXGXvslI+GYlM1Z/35aSHHWaCJWB7XvTSHYuV3eM7tw+aE0mT/xMro4M4Q9rCGHT0lw=="], + "@tanstack/query-core": ["@tanstack/query-core@5.108.4", "", {}, "sha512-2Ks5dlLWz4eXJrthOyG0qW3SLt3xx0RrQmAmN0rnmogiaaOYuWiAe6HAm9KE2b2v8nig+vraNz8fsfZ6fF6zFg=="], - "@tanstack/react-query": ["@tanstack/react-query@5.101.2", "", { "dependencies": { "@tanstack/query-core": "5.101.2" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-seDkr6kzGzX1okaaTtZPtgA688CDPlXUz1C6xSg0ESqn04Vuc8tlrYms1s3de+znBqhPVxFRfpAfUf+6XvfPWg=="], + "@tanstack/react-query": ["@tanstack/react-query@5.108.4", "", { "dependencies": { "@tanstack/query-core": "5.108.4" }, "peerDependencies": { "@types/react": "^18 || ^19", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-GlTa94kfEKTVsbzXe58rFA3GZ0ZE7N1aFtbZAfOS3XxMv8YNn4C+8rsz40LorHLazdm5PsqCroWaYAR+ZkMXMQ=="], "@tanstack/react-router": ["@tanstack/react-router@1.170.18", "", { "dependencies": { "@tanstack/history": "1.162.0", "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "1.171.15", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-wpbGYZEp/fmz1q4bn7BD8VZ+/VZ7GBqSJv5V969pU+chP8y7dquWDmKTFMohvUegb9lg12m1uPVvD6kB2wORvQ=="], - "@tanstack/react-router-devtools": ["@tanstack/react-router-devtools@1.167.0", "", { "dependencies": { "@tanstack/router-devtools-core": "1.168.0" }, "peerDependencies": { "@tanstack/react-router": "^1.170.0", "@tanstack/router-core": "^1.170.0", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" }, "optionalPeers": ["@tanstack/router-core"] }, "sha512-nGw095EG7IHx0h5NtlEmzf6vcCTaFNPWdTSuDKazajhN0ct/v/TkekJ9J6KYUCeV1a8/2ZmToc58M+0rrOyn7w=="], - - "@tanstack/react-start": ["@tanstack/react-start@1.168.31", "", { "dependencies": { "@tanstack/react-router": "1.170.18", "@tanstack/react-start-client": "1.168.16", "@tanstack/react-start-rsc": "0.1.30", "@tanstack/react-start-server": "1.167.22", "@tanstack/router-utils": "1.162.2", "@tanstack/start-client-core": "1.170.14", "@tanstack/start-plugin-core": "1.171.23", "@tanstack/start-server-core": "1.169.17", "pathe": "^2.0.3" }, "peerDependencies": { "@rsbuild/core": "^2.0.0", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", "vite": ">=7.0.0" }, "optionalPeers": ["@rsbuild/core", "vite"] }, "sha512-8uzryvrFQTE+N8Mw5Egzgstmo+E5FhLYknIvBuiz1vOhCAga0MGWwYS0GAMLlpySBmxc+eH1tfUJ6ZbImjgk0A=="], + "@tanstack/react-start": ["@tanstack/react-start@1.168.31", "", { "dependencies": { "@tanstack/react-router": "1.170.18", "@tanstack/react-start-client": "1.168.16", "@tanstack/react-start-rsc": "0.1.30", "@tanstack/react-start-server": "1.167.22", "@tanstack/router-utils": "1.162.2", "@tanstack/start-client-core": "1.170.14", "@tanstack/start-plugin-core": "1.171.23", "@tanstack/start-server-core": "1.169.17", "pathe": "^2.0.3" }, "peerDependencies": { "@rsbuild/core": "^2.0.0", "@vitejs/plugin-rsc": "*", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", "vite": ">=7.0.0" }, "optionalPeers": ["@rsbuild/core", "@vitejs/plugin-rsc", "vite"] }, "sha512-8uzryvrFQTE+N8Mw5Egzgstmo+E5FhLYknIvBuiz1vOhCAga0MGWwYS0GAMLlpySBmxc+eH1tfUJ6ZbImjgk0A=="], "@tanstack/react-start-client": ["@tanstack/react-start-client@1.168.16", "", { "dependencies": { "@tanstack/react-router": "1.170.18", "@tanstack/router-core": "1.171.15", "@tanstack/start-client-core": "1.170.14" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-1OfHgy0wpHwe2tlB3FxMeA+IMX6Il/QAMf+8UdXuimReIc2Lz3BkMLBL38k4GIxBguX9sI8EMLO5jlTZ4e1olw=="], @@ -692,12 +647,10 @@ "@tanstack/react-table": ["@tanstack/react-table@8.21.3", "", { "dependencies": { "@tanstack/table-core": "8.21.3" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww=="], - "@tanstack/react-virtual": ["@tanstack/react-virtual@3.14.6", "", { "dependencies": { "@tanstack/virtual-core": "3.17.4" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-4+Uq8m0/gzO4kMCHUEpTtGX1RnONK0C+g88b2ltwPMWUBiaVarBuWKoPJaz7gj1cKCVRAdyu+U8GcKhwCc2beA=="], + "@tanstack/react-virtual": ["@tanstack/react-virtual@3.14.30", "", { "dependencies": { "@tanstack/virtual-core": "3.19.15" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-vVq9U2WahGWue0RVPrzGuBM8QxhGKq6WV7AOUyXWR17F3kYNxHMZekYZdKm0X63/S4QZGCDlBqASvAukpXQ8GQ=="], "@tanstack/router-core": ["@tanstack/router-core@1.171.15", "", { "dependencies": { "@tanstack/history": "1.162.0", "cookie-es": "^3.0.0", "seroval": "^1.5.4", "seroval-plugins": "^1.5.4" } }, "sha512-IILCDcLaItMZQ2jEmCABHY1Nhjjn5XUvwpQp3e4Nmu+vfg0BgYFuu/QASz2SwE2ZNbVMrvt8X/wxa+Gg5aErxA=="], - "@tanstack/router-devtools-core": ["@tanstack/router-devtools-core@1.168.0", "", { "dependencies": { "clsx": "^2.1.1", "goober": "^2.1.16" }, "peerDependencies": { "@tanstack/router-core": "^1.170.0", "csstype": "^3.0.10" }, "optionalPeers": ["csstype"] }, "sha512-wQoQhlBK7nlZgqzaqdYXKWNTpdHdsaREdaPhFZVH0/Ador+F+eM3/NF2i3f2LPeS0GgKraZUQXe1Q/1+KHyEYg=="], - "@tanstack/router-generator": ["@tanstack/router-generator@1.167.21", "", { "dependencies": { "@babel/types": "^7.28.5", "@tanstack/router-core": "1.171.15", "@tanstack/router-utils": "1.162.2", "@tanstack/virtual-file-routes": "1.162.0", "jiti": "^2.7.0", "magic-string": "^0.30.21", "prettier": "^3.5.0", "zod": "^4.4.3" } }, "sha512-m3oXZyienj8owialdyoZ0txHQrnEx/Ra+D9kWtar5fC2cWZr5Pvxl86VY2mX5RRLC5QLKLeRGT1x4HV95wHVDQ=="], "@tanstack/router-plugin": ["@tanstack/router-plugin@1.168.22", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/template": "^7.27.2", "@babel/types": "^7.28.5", "@tanstack/router-core": "1.171.15", "@tanstack/router-generator": "1.167.21", "@tanstack/router-utils": "1.162.2", "chokidar": "^5.0.0", "unplugin": "^3.0.0", "zod": "^4.4.3" }, "peerDependencies": { "@rsbuild/core": ">=1.0.2 || ^2.0.0", "@tanstack/react-router": "^1.170.18", "vite": ">=5.0.0 || >=6.0.0 || >=7.0.0 || >=8.0.0", "vite-plugin-solid": "^2.11.10 || ^3.0.0-0", "webpack": ">=5.92.0" }, "optionalPeers": ["@rsbuild/core", "@tanstack/react-router", "vite", "vite-plugin-solid", "webpack"] }, "sha512-+iBkwRWQ7dlTcL4TIKrphcToJf95DAd75FY9duiel7OFfDt8oT4tlfn713TKlgSHpZ9PVLQQQHe8ijcEseM39Q=="], @@ -720,11 +673,11 @@ "@tanstack/table-core": ["@tanstack/table-core@8.21.3", "", {}, "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg=="], - "@tanstack/virtual-core": ["@tanstack/virtual-core@3.17.4", "", {}, "sha512-nGm5KteqxasUdThLc2izl6dHUqLv0LQj7Nuyo5gYalTPf/U8a9ermvsl7reT+6ioBW1l8WfpP/mcU338nLXpqw=="], + "@tanstack/virtual-core": ["@tanstack/virtual-core@3.19.15", "", {}, "sha512-XL0RLw2Y1Qm5IrtIuz0cmX2nDc2hjtKr0J+7S+xHaDHcy19u8Fg1o17nCBMIKlrCgmMcgnViexlHGDx8SniuBw=="], "@tanstack/virtual-file-routes": ["@tanstack/virtual-file-routes@1.162.0", "", {}, "sha512-uhOeFyxLcU41HzvrxsGpiWdcMbScY1EDgbZ5K7DVRMYInbLYWAC0EA/kx9wXAoSM8q82bUG2hRl8+EAjE6XAbA=="], - "@tokenizer/inflate": ["@tokenizer/inflate@0.4.1", "", { "dependencies": { "debug": "^4.4.3", "token-types": "^6.1.1" } }, "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA=="], + "@tokenizer/inflate": ["@tokenizer/inflate@0.6.1", "", { "dependencies": { "debug": "^4.4.3", "strtok3": "^10.8.0", "token-types": "^6.2.0" } }, "sha512-EuqSyHdOXN61cc5/rsW6uUn1TJZJGZr56jlkUbsLwVJ6uHgvwQyFkYfOCf+zzPFAYjftPk1WeJnEhpLVvzbm1A=="], "@tokenizer/token": ["@tokenizer/token@0.3.0", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="], @@ -736,11 +689,11 @@ "@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="], - "@types/bun": ["@types/bun@1.4.0", "", { "dependencies": { "bun-types": "1.4.0" } }, "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ=="], + "@types/bun": ["@types/bun@1.4.5", "", { "dependencies": { "bun-types": "1.4.5" } }, "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q=="], "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], - "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + "@types/estree": ["@types/estree@1.0.11", "", {}, "sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg=="], "@types/estree-jsx": ["@types/estree-jsx@1.0.5", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="], @@ -752,11 +705,11 @@ "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], - "@types/node": ["@types/node@24.13.3", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q=="], + "@types/node": ["@types/node@24.19.4", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-s04odlR3ksJrLu7QLi+pddkWLD0RmSbcP9KuWn2/ozQKAp/YgwBC/6x9kJj8yAzZnGPfxePm7zm7nysVPCRagw=="], - "@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], + "@types/react": ["@types/react@19.3.3", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-K8uWpJc4teiuOPdiP1umjeA9rGMgVPiXuoL66fcS1QlwBT1WMqY8PORmub9FadopIs+RCW6siYEs7Lpq+vDlog=="], - "@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="], + "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], "@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="], @@ -802,31 +755,31 @@ "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], - "@ungap/structured-clone": ["@ungap/structured-clone@1.3.3", "", {}, "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg=="], + "@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="], "@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="], "@vitejs/plugin-react": ["@vitejs/plugin-react@5.2.0", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw=="], + "@vscode/diff": ["@vscode/diff@0.0.2-145", "", {}, "sha512-atPcmNrAU4B8OsbrmqYlHbZREt//m8z52o400YA8uuvq3Be5wnmIhLoLqhMum7Jv7kRC0FE+m3WAUbaZF681wg=="], + "@zeit/schemas": ["@zeit/schemas@2.36.0", "", {}, "sha512-7kjMwcChYEzMKjeex9ZFXkt1AyNov9R5HZtjBKVsmVpw7pa7ZtlCGvCBC2vnnXctaYN+aRI61HjIqeetZW5ROg=="], - "acorn": ["acorn@8.17.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg=="], + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], - "ai": ["ai@6.0.230", "", { "dependencies": { "@ai-sdk/gateway": "3.0.153", "@ai-sdk/provider": "3.0.14", "@ai-sdk/provider-utils": "4.0.40", "@opentelemetry/api": "^1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-TQKOUPL7GLirkGvA2/sxA3bNzPeTY2w30mOyzwfQyiB8WvTQTr08mGgBBETPHwKIefgYF8HbLeVMgEahRVsX/Q=="], + "ai": ["ai@6.0.339", "", { "dependencies": { "@ai-sdk/gateway": "3.0.244", "@ai-sdk/provider": "3.0.19", "@ai-sdk/provider-utils": "4.0.69", "@opentelemetry/api": "^1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-uJUaEICQoFDJ8tQQgv2VUwDwjw4obkcVuBNRsEaXiQ91qbHTFlPHAK8J0qQJAL/2+RQla8dSW7Q4jP2cbgJg5w=="], "ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="], "ansi-align": ["ansi-align@3.0.1", "", { "dependencies": { "string-width": "^4.1.0" } }, "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w=="], - "ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "ansi-regex": ["ansi-regex@6.6.0", "", {}, "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g=="], "ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], - "ansis": ["ansis@4.3.1", "", {}, "sha512-BJ8/l4R5LRE7hW9WdSuGYrLSHi2ynxeFpDFbH0K/CgNeY/tyhk+vO6TYxXC5r5CpUhNVX310xzPsN/H9lCdfOA=="], - - "arch": ["arch@2.2.0", "", {}, "sha512-Of/R0wqp83cgHozfIYLbBMnej79U/SVGOOyuB3VVFv1NRM/PSFMK12x9KVtiYzJqmnU5WR2qp0Z5rHb7sWGnFQ=="], + "ansis": ["ansis@4.5.0", "", {}, "sha512-KwIVkfFfJSSzBmZhDGuTmkhWqTdyB5oNVzzznBJbBZ5bZtHiqSrcugRF0RKJKT4Ss3d7ZrcjnlFVDlQNmtWfWw=="], "arg": ["arg@5.0.2", "", {}, "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg=="], @@ -846,25 +799,25 @@ "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], - "baseline-browser-mapping": ["baseline-browser-mapping@2.10.43", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-AjYpR78kDWAY3Efj+cDTFH9t9SCoL7OoTp1BOb0mQV7S+6CiLwnWM3FyxhJtdPufDFKzmCSFoUncKjWgJEZTCQ=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.11.41", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-yjL/sZCpbpL0ocwmrUe1YFUelyMcifcByF4UYCBDyubFXQRs3lUjo9VoPKdjoFFhmzLAAGNJb1GBBCQJ6B4eyg=="], "boxen": ["boxen@7.0.0", "", { "dependencies": { "ansi-align": "^3.0.1", "camelcase": "^7.0.0", "chalk": "^5.0.1", "cli-boxes": "^3.0.0", "string-width": "^5.1.2", "type-fest": "^2.13.0", "widest-line": "^4.0.1", "wrap-ansi": "^8.0.1" } }, "sha512-j//dBVuyacJbvW+tvZ9HuH03fZ46QcaKvvhZickZqtB271DxJ7SNRSNxrV/dZX0085m7hISRZWbzWlJvx/rHSg=="], - "brace-expansion": ["brace-expansion@1.1.16", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw=="], + "brace-expansion": ["brace-expansion@1.1.22", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ=="], - "browserslist": ["browserslist@4.28.6", "", { "dependencies": { "baseline-browser-mapping": "^2.10.42", "caniuse-lite": "^1.0.30001803", "electron-to-chromium": "^1.5.389", "node-releases": "^2.0.51", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-FQBYNK15VMslhLHpA7+n+n1GOlF1kId2xcCg7/j95f24AOF6VDYMNH4mFxF7KuaTdv627faazpOAjFzMrfJOUw=="], + "browserslist": ["browserslist@4.29.6", "", { "dependencies": { "baseline-browser-mapping": "^2.11.37", "caniuse-lite": "^1.0.30001826", "electron-to-chromium": "^1.5.486", "node-releases": "^2.0.64", "update-browserslist-db": "^1.4.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w=="], - "bun": ["bun@1.3.14", "", { "optionalDependencies": { "@oven/bun-darwin-aarch64": "1.3.14", "@oven/bun-darwin-x64": "1.3.14", "@oven/bun-darwin-x64-baseline": "1.3.14", "@oven/bun-freebsd-aarch64": "1.3.14", "@oven/bun-freebsd-x64": "1.3.14", "@oven/bun-linux-aarch64": "1.3.14", "@oven/bun-linux-aarch64-android": "1.3.14", "@oven/bun-linux-aarch64-musl": "1.3.14", "@oven/bun-linux-x64": "1.3.14", "@oven/bun-linux-x64-android": "1.3.14", "@oven/bun-linux-x64-baseline": "1.3.14", "@oven/bun-linux-x64-musl": "1.3.14", "@oven/bun-linux-x64-musl-baseline": "1.3.14", "@oven/bun-windows-aarch64": "1.3.14", "@oven/bun-windows-x64": "1.3.14", "@oven/bun-windows-x64-baseline": "1.3.14" }, "os": [ "!aix", "!sunos", "!openbsd", ], "cpu": [ "x64", "arm64", ], "bin": { "bun": "bin/bun.exe", "bunx": "bin/bunx.exe" } }, "sha512-aB6GVd42x1Y5ie1K16SF+oLGtgSkwX9hgoDdIW88pjvfTccU8F1vfpoOt34QLv0dZ1v3XimtaxPlZUG81Gx9Zg=="], + "bun": ["bun@1.4.5", "", { "optionalDependencies": { "@oven/bun-darwin-aarch64": "1.4.5", "@oven/bun-darwin-x64": "1.4.5", "@oven/bun-freebsd-aarch64": "1.4.5", "@oven/bun-freebsd-x64": "1.4.5", "@oven/bun-linux-aarch64": "1.4.5", "@oven/bun-linux-aarch64-android": "1.4.5", "@oven/bun-linux-aarch64-musl": "1.4.5", "@oven/bun-linux-x64": "1.4.5", "@oven/bun-linux-x64-android": "1.4.5", "@oven/bun-linux-x64-musl": "1.4.5", "@oven/bun-windows-aarch64": "1.4.5", "@oven/bun-windows-x64": "1.4.5" }, "os": [ "!aix", "!sunos", "!openbsd", ], "cpu": [ "x64", "arm64", ], "hasInstallScript": true, "bin": { "bun": "bin/bun.exe", "bunx": "bin/bunx.exe" } }, "sha512-SWOAncfhwiqIyaZ3uyuUD/6o8aWbG8QtU6SChlz4u6U/C89gTZafLDCmbUvyNjx+ccxLLHV+lSsWqE1OBN8bBw=="], "bun-plugin-tailwind": ["bun-plugin-tailwind@0.1.2", "", { "peerDependencies": { "bun": ">=1.0.0" } }, "sha512-41jNC1tZRSK3s1o7pTNrLuQG8kL/0vR/JgiTmZAJ1eHwe0w5j6HFPKeqEk0WAD13jfrUC7+ULuewFBBCoADPpg=="], - "bun-types": ["bun-types@1.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="], + "bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], "camelcase": ["camelcase@7.0.1", "", {}, "sha512-xlx1yCK2Oc1APsPXDL2LdlNP6+uu8OCDdhOBSVT279M/S+y75O30C2VuD8T2ogdePBBl7PfPF4504tnLgX3zfw=="], - "caniuse-lite": ["caniuse-lite@1.0.30001806", "", {}, "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw=="], + "caniuse-lite": ["caniuse-lite@1.0.30001829", "", {}, "sha512-FeVvlaVr3r+cdHIYXyZhtVkqroSYjYaoNxItxQNjusurUE+IqODawDsbzk02HJgi2RdKiaGGFm+EKbXku+yITg=="], "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], @@ -886,8 +839,6 @@ "cli-boxes": ["cli-boxes@3.0.0", "", {}, "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g=="], - "clipboardy": ["clipboardy@3.0.0", "", { "dependencies": { "arch": "^2.2.0", "execa": "^5.1.1", "is-wsl": "^2.2.0" } }, "sha512-Su+uU5sr1jkUy1sGRpLKjKrvEOVXgSgiSInwa/qeID6aJ07yh+5NWc3h2QfjHjBnfX4LhtFcuAWKUsJ3r+fjbg=="], - "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], "cmdk": ["cmdk@1.1.1", "", { "dependencies": { "@radix-ui/react-compose-refs": "^1.1.1", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-id": "^1.1.0", "@radix-ui/react-primitive": "^2.0.2" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg=="], @@ -902,25 +853,23 @@ "compressible": ["compressible@2.0.18", "", { "dependencies": { "mime-db": ">= 1.43.0 < 2" } }, "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg=="], - "compression": ["compression@1.8.1", "", { "dependencies": { "bytes": "3.1.2", "compressible": "~2.0.18", "debug": "2.6.9", "negotiator": "~0.6.4", "on-headers": "~1.1.0", "safe-buffer": "5.2.1", "vary": "~1.1.2" } }, "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w=="], + "compression": ["compression@1.8.2", "", { "dependencies": { "bytes": "3.1.2", "compressible": "~2.0.18", "debug": "2.6.9", "destroy": "1.2.0", "negotiator": "~0.6.4", "on-headers": "~1.1.0", "safe-buffer": "5.2.1", "vary": "~1.1.2" } }, "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ=="], - "compute-scroll-into-view": ["compute-scroll-into-view@3.1.1", "", {}, "sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw=="], + "compute-scroll-into-view": ["compute-scroll-into-view@3.2.2", "", {}, "sha512-X+jf3y2j3TbtxA3fq3/kBNiSnD1QlIChiIQdAc2Yo1LtOc0yjO1TzgxWJf8PwtKPGgSvSfWUlVvrb7vGx1eYWA=="], "concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="], "content-disposition": ["content-disposition@0.5.2", "", {}, "sha512-kRGRZw3bLlFISDBgwTSA1TMBFN6J6GWDeubmDE3AF+3+yXL8hTWv8r5rkLbqYXY4RjPk/EzHnClI3zQf1cFmHA=="], + "content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], "cookie-es": ["cookie-es@3.1.1", "", {}, "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg=="], - "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], - - "cssesc": ["cssesc@3.0.0", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="], - - "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "csstype": ["csstype@3.2.4", "", {}, "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ=="], "date-fns": ["date-fns@4.4.0", "", {}, "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w=="], @@ -934,6 +883,8 @@ "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], + "destroy": ["destroy@1.2.0", "", {}, "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg=="], + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], "detect-node-es": ["detect-node-es@1.1.0", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="], @@ -944,7 +895,7 @@ "docs": ["docs@workspace:packages/docs"], - "dompurify": ["dompurify@3.2.7", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-WhL/YuveyGXJaerVlMYGWhvQswa7myDG17P7Vu65EWC05o8vfeNbvNf4d/BOvH99+ZW+LlQsc1GDKMa1vNK6dw=="], + "dompurify": ["dompurify@3.4.17", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w=="], "drizzle-kit": ["drizzle-kit@1.0.0-rc.6", "", { "peerDependencies": { "drizzle-orm": ">=1.0.0-rc.5", "oxc-parser": "^0.157.0" }, "optionalPeers": ["drizzle-orm", "oxc-parser"], "bin": { "drizzle-kit": "bin.js" } }, "sha512-UNwJcuwG8Iw/5M/aKmmzaX61OQgX+gj87MIEZE4J/2pSDCnQJHjhFhmPq8YNHAHnY81bbGsqiWxlyiybDD1E/g=="], @@ -956,13 +907,13 @@ "eastasianwidth": ["eastasianwidth@0.2.0", "", {}, "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="], - "electron-to-chromium": ["electron-to-chromium@1.5.393", "", {}, "sha512-kiDJdIUawuEIcp9XoICKp1iTYDEbgguIPq526N1Q7jIQDeQ3CqoMx71025PI/7E48Ddtw2HuWsVjY7afEgNxmg=="], + "electron-to-chromium": ["electron-to-chromium@1.5.495", "", {}, "sha512-dZcmtNbDI5oeT9uP9Z+D7h/H5C1mvBewDTLgZgo9WgyPmqOXSt2cmoCK99evPygUOn9lyXZ4w0Eb8APrkBjqBA=="], - "elysia": ["elysia@1.4.29", "", { "dependencies": { "cookie": "^1.1.1", "exact-mirror": "^0.2.7", "fast-decode-uri-component": "^1.0.1", "memoirist": "^0.4.0" }, "peerDependencies": { "@sinclair/typebox": ">= 0.34.0 < 1", "@types/bun": ">= 1.2.0", "file-type": ">= 20.0.0", "openapi-types": ">= 12.0.0", "typescript": ">= 5.0.0" }, "optionalPeers": ["@types/bun", "typescript"] }, "sha512-GwMRGGwSdjfPt+w3LA0fqTuYJtS8uVRJicvoar98/HrO5qdFKDc9CwjIb6Kja+v39lkY+58hr2JvdR9jQzlUuA=="], + "elysia": ["elysia@1.4.32", "", { "dependencies": { "cookie": "^1.1.1", "exact-mirror": "^0.2.9", "fast-decode-uri-component": "^1.0.1", "memoirist": "^0.4.0" }, "peerDependencies": { "@sinclair/typebox": ">= 0.34.0 < 1", "@types/bun": ">= 1.2.0", "file-type": ">= 20.0.0", "openapi-types": ">= 12.0.0", "typescript": ">= 5.0.0" }, "optionalPeers": ["@types/bun", "typescript"] }, "sha512-pSWBPKJe0t24r6oQydL8xmFnbOOVs0bXN1ShIwSPxXJbE/z9NRRXs8FigQRhXyjdbi3YSuJgEKe22BVx4cU99w=="], "emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], - "enhanced-resolve": ["enhanced-resolve@5.24.2", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-rpsZEGT1jFuve6QlpyRp9ckQ+kN61hvF9BzCPyMdaKTm8UJce96KBn3sorXOFXlzjPrs3Vc4T1NsSroZ3PxlFw=="], + "enhanced-resolve": ["enhanced-resolve@5.27.0", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ=="], "esast-util-from-estree": ["esast-util-from-estree@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "unist-util-position-from-estree": "^2.0.0" } }, "sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ=="], @@ -980,7 +931,7 @@ "estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="], - "estree-util-scope": ["estree-util-scope@1.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0" } }, "sha512-2CAASclonf+JFWBNJPndcOpA8EMJwa0Q8LUFJEKqXLW6+qBvbFZuF5gItbQOs/umBUkjviCSDCbBwU2cXbmrhQ=="], + "estree-util-scope": ["estree-util-scope@1.0.1", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0" } }, "sha512-B0np3dcdxqILX5e9nEi5/Fr4K7gL4oYFVPV1zRa2e9wRCbQoZZNWOZFYyoInvXUPJXBXjss+QXlWLJChDEHDkA=="], "estree-util-to-js": ["estree-util-to-js@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "astring": "^1.8.0", "source-map": "^0.7.0" } }, "sha512-WDF+xj5rRWmD5tj6bIqRi6CkLIXbbNQUcxQHzGysQzvHmdYG2G7p/Tf0J0gpxGgkeMZNTIjT/AoSvC9Xehcgdg=="], @@ -990,15 +941,13 @@ "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], - "eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="], + "eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="], - "exact-mirror": ["exact-mirror@0.2.7", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-+MeEmDcLA4o/vjK2zujgk+1VTxPR4hdp23qLqkWfStbECtAq9gmsvQa3LW6z/0GXZyHJobrCnmy1cdeE7BjsYg=="], + "exact-mirror": ["exact-mirror@0.2.9", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-7+ecLdWdlY0Br1E1Fax2Pss5VU3b1WQwJ8bdyt5azPNdhKHuivjQlV8baXF9NkQwlvnyOwaM6ITBiuK43PQ4wg=="], "examples": ["examples@workspace:packages/examples"], - "execa": ["execa@5.1.1", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="], - - "exsolve": ["exsolve@1.1.0", "", {}, "sha512-D+42+T12DdIlJM3uepa55qGiL3sYdLBOxIl2ifQCzCHz4c7eiolaHsi3BIqEr7JxBzxv2pYZQX9kw16ziMcEmw=="], + "exsolve": ["exsolve@1.2.0", "", {}, "sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg=="], "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], @@ -1006,17 +955,17 @@ "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], - "fast-uri": ["fast-uri@3.1.4", "", {}, "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw=="], + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], - "fastq": ["fastq@1.20.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="], + "fastq": ["fastq@1.20.3", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw=="], "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "fetchdts": ["fetchdts@0.1.7", "", {}, "sha512-YoZjBdafyLIop9lSxXVI33oLD5kN31q4Td+CasofLLYeLXRFeOsuOw0Uo+XNRi9PZlbfdlN2GmRtm4tCEQ9/KA=="], - "file-type": ["file-type@22.0.1", "", { "dependencies": { "@tokenizer/inflate": "^0.4.1", "strtok3": "^10.3.5", "token-types": "^6.1.2", "uint8array-extras": "^1.5.0" } }, "sha512-ww5Mhre0EE+jmBvOXTmXAbEMuZE7uX4a3+oRCQFNj8w++g3ev913N6tXQz0XTXbueQ5TWQfm6BdaViEHHn8bhA=="], + "file-type": ["file-type@22.3.0", "", { "dependencies": { "@tokenizer/inflate": "^0.6.0", "strtok3": "^10.6.3", "token-types": "^6.1.2", "uint8array-extras": "^1.6.0" } }, "sha512-PrPedgnnWl5bWz3JHgar0QSzRvzeyFh7dZ9JpYOgcPZu4KALS9zw4MMa6qXRYyjeBsAlpaWB2boLuG991+0HIQ=="], - "framer-motion": ["framer-motion@12.42.2", "", { "dependencies": { "motion-dom": "^12.42.2", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-5XY9luDiu0oHfHBjpDthFMh0ES+122w6p/papSJBweMkO8Sn+PW2QaEgRblQBpWFnuvZS5qvarpt/hO2pjGmnw=="], + "framer-motion": ["framer-motion@12.43.0", "", { "dependencies": { "motion-dom": "^12.43.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -1030,15 +979,11 @@ "get-nonce": ["get-nonce@1.0.1", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="], - "get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="], - "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], "globrex": ["globrex@0.1.2", "", {}, "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg=="], - "goober": ["goober@2.1.19", "", { "peerDependencies": { "csstype": "^3.0.10" } }, "sha512-U7veizMqxyKlM58+Z5j2ngJBH/r9siDmxpvNxSw0PylF6WQvrASJEZrxh1hidRBJc2jqoBVSyOban5u8m+6Rxg=="], - - "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + "graceful-fs": ["graceful-fs@4.2.12", "", {}, "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw=="], "h3-v2": ["h3@2.0.1-rc.20", "", { "dependencies": { "rou3": "^0.8.1", "srvx": "^0.11.13" }, "peerDependencies": { "crossws": "^0.4.1" }, "optionalPeers": ["crossws"], "bin": { "h3": "bin/h3.mjs" } }, "sha512-28ljodXuUp0fZovdiSRq4G9OgrxCztrJe5VdYzXAB7ueRvI7pIUqLU14Xi3XqdYJ/khXjfpUOOD2EQa6CmBgsg=="], @@ -1046,9 +991,9 @@ "hast-util-to-estree": ["hast-util-to-estree@3.1.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-attach-comments": "^3.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w=="], - "hast-util-to-html": ["hast-util-to-html@9.0.5", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="], + "hast-util-to-html": ["hast-util-to-html@9.0.7", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-HYNDA3qdnzUPitY/LcQm1nWs8z0cWFNH1Nz09jdI/tXifAqF7h3+jrLl4S/b9Mi4VSjn0Dsn54ctuTV6zhBthA=="], - "hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.6", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="], + "hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.7", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-object": "^2.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-F7DNV2NMcTxA4GqPVHnXzX+mpoPHAIY9rJAVH3CZ1FdBZOcBUEjUuvMkMpHVs/sicEtznh9tMGj5WUR9S4E2rg=="], "hast-util-to-string": ["hast-util-to-string@3.0.1", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A=="], @@ -1056,15 +1001,13 @@ "html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="], - "human-signals": ["human-signals@2.1.0", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="], - "ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], - "image-size": ["image-size@2.0.2", "", { "bin": { "image-size": "bin/image-size.js" } }, "sha512-IRqXKlaXwgSMAMtpNzZa1ZAe8m+Sa1770Dhk8VkSsP9LS+iHD62Zd8FQKs8fbPiagBE7BzoFX23cxFnwshpV6w=="], + "image-size": ["image-size@2.2.0", "", { "bin": { "image-size": "bin/image-size.js" } }, "sha512-93QTtmEv0UD26RTJfmxQvWzhlauWO1TizNPjCumqzlACXYmI7TlwRWWT2+M4at7kZwnj+WkMOW9XKI76eX0dWw=="], "ini": ["ini@1.3.8", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="], - "inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="], + "inline-style-parser": ["inline-style-parser@0.2.9", "", {}, "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg=="], "is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="], @@ -1072,8 +1015,6 @@ "is-decimal": ["is-decimal@2.0.1", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="], - "is-docker": ["is-docker@2.2.1", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="], - "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], "is-hexadecimal": ["is-hexadecimal@2.0.1", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="], @@ -1084,21 +1025,15 @@ "is-port-reachable": ["is-port-reachable@4.0.0", "", {}, "sha512-9UoipoxYmSk6Xy7QFgRv2HDyaysmgSG75TFQs6S+3pDM7ZhKTF/bskZV+0UlABHzKjNVhPjYCLfeZUEg1wXxig=="], - "is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], - - "is-wsl": ["is-wsl@2.2.0", "", { "dependencies": { "is-docker": "^2.0.0" } }, "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww=="], - - "isbot": ["isbot@5.2.1", "", {}, "sha512-dJ+LpKyClQZ7NG+j3OensC/mAZkGpukE9YUrgPYvAZj2doVL0edfDgywTUh5CXa0o+nW9a1V9e5+CJTX8+SxRw=="], - - "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + "isbot": ["isbot@5.2.4", "", {}, "sha512-qFPSy82nnxEUrHdKpIQPVpYwsGJqL/+VGWYVYP5c8XMOyRRPDVb1C5ZMwmKs3nB4Evsw/ux0WqHBkf2UUawC1A=="], "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], - "jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="], + "jose": ["jose@6.2.18", "", {}, "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg=="], "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], - "js-yaml": ["js-yaml@4.3.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q=="], + "js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="], "jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="], @@ -1108,31 +1043,29 @@ "json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], - "jsonata": ["jsonata@2.2.2", "", {}, "sha512-XDFH2PuaAXv0AXJEWwElXbqADmKFGKMLMkFb+qOz0EhjQW2EIJ6pgtordLU+4u3IVERyBfqy6bi6kZKEncvRqA=="], + "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], - "lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], + "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], - "lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="], + "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="], - "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.32.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="], + "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="], - "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.32.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="], + "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="], - "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.32.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="], + "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="], - "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.32.0", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="], + "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="], - "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.32.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="], + "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="], - "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.32.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="], + "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="], - "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.32.0", "", { "os": "linux", "cpu": "x64" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="], + "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="], - "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.32.0", "", { "os": "linux", "cpu": "x64" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="], + "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="], - "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.32.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="], - - "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="], + "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], "lodash.debounce": ["lodash.debounce@4.0.8", "", {}, "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow=="], @@ -1140,59 +1073,57 @@ "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], - "lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], + "lru-cache": ["lru-cache@11.5.4", "", {}, "sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw=="], "lucide-react": ["lucide-react@0.555.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-D8FvHUGbxWBRQM90NZeIyhAvkFfsh3u9ekrMvJ30Z6gnpBHS6HC6ldLg7tL45hwiIz/u66eKDtdA23gwwGsAHA=="], "lucide-static": ["lucide-static@0.552.0", "", {}, "sha512-wL+9EAx8k/4i/w9qGuAwHrrV8SryVsJk+Ug9SErtg18Zq95FMwMXlu4Dhl4RS8C2b1oxFu66p7YK96yrNsm6cg=="], - "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + "magic-string": ["magic-string@1.4.5", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w=="], "markdown-extensions": ["markdown-extensions@2.0.0", "", {}, "sha512-o5vL7aDWatOTX8LzaS1WMoaoxIiLRQJuIKKe2wAw6IeULDHaqbiqiggmx+pKvZDb1Sj+pE46Sn1T7lCqfFtg1Q=="], - "markdown-table": ["markdown-table@3.0.4", "", {}, "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw=="], + "markdown-table": ["markdown-table@3.1.0", "", {}, "sha512-xpeSCdM+B+6P3ncfgaB7FoDbtJ30xAe6Z18TGT7AgXJsHqCElCICZovQqdRMm7kHgpTyYv36EupqewoFFSB8vw=="], "marked": ["marked@14.0.0", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ=="], - "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg=="], + "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.5", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-of3wZLEBWpK8mSYy8wmKnwyxfUKjhCkXxGLz45DVBqfcahTP37LscCK+0oAZh+ReZ5OunPDkB2zdGMIxrojLhw=="], - "mdast-util-from-markdown": ["mdast-util-from-markdown@2.0.3", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q=="], + "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], "mdast-util-gfm": ["mdast-util-gfm@3.1.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-gfm-autolink-literal": "^2.0.0", "mdast-util-gfm-footnote": "^2.0.0", "mdast-util-gfm-strikethrough": "^2.0.0", "mdast-util-gfm-table": "^2.0.0", "mdast-util-gfm-task-list-item": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ=="], - "mdast-util-gfm-autolink-literal": ["mdast-util-gfm-autolink-literal@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-find-and-replace": "^3.0.0", "micromark-util-character": "^2.0.0" } }, "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ=="], + "mdast-util-gfm-autolink-literal": ["mdast-util-gfm-autolink-literal@2.1.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-find-and-replace": "^3.0.0", "micromark-util-character": "^2.0.0" } }, "sha512-rAlbZBGZfv2YRr6lSFGHTN305KkNawOYRRlbldFyPHnTlHJZwlGdzVwyIDvr3fxbhRbmJOSZc06c8H5Fgfu8Ng=="], "mdast-util-gfm-footnote": ["mdast-util-gfm-footnote@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0" } }, "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ=="], - "mdast-util-gfm-strikethrough": ["mdast-util-gfm-strikethrough@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg=="], + "mdast-util-gfm-strikethrough": ["mdast-util-gfm-strikethrough@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw=="], - "mdast-util-gfm-table": ["mdast-util-gfm-table@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg=="], + "mdast-util-gfm-table": ["mdast-util-gfm-table@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "mdast-util-to-string": "^4.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-fiIjPrAy4kz68/eFbPHhsiWDGHhqUSVoU1XsfLM5DsEPXw7MxgiVVyulUggFRckVWeT1KXQXkg5vm3kv4oMSOA=="], - "mdast-util-gfm-task-list-item": ["mdast-util-gfm-task-list-item@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ=="], + "mdast-util-gfm-task-list-item": ["mdast-util-gfm-task-list-item@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-jXVO1hvB2hs82g1esi7I9nIJDqiijbQLIyH2jDUb5s7jIAZMr/79h0VHSq7XHKTqpLARRm+DDNjduB7S9+6XZA=="], "mdast-util-mdx": ["mdast-util-mdx@3.0.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w=="], "mdast-util-mdx-expression": ["mdast-util-mdx-expression@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ=="], - "mdast-util-mdx-jsx": ["mdast-util-mdx-jsx@3.2.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0", "unist-util-stringify-position": "^4.0.0", "vfile-message": "^4.0.0" } }, "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q=="], + "mdast-util-mdx-jsx": ["mdast-util-mdx-jsx@3.2.2", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0", "unist-util-stringify-position": "^4.0.0", "vfile-message": "^4.0.0" } }, "sha512-/0FHaZMv2fSjIL3z/NYmXnQTSdzYyamPpI1BXpSCngTUqpSvMNIlERa26ABz+Z6UFQbrh3I5Yhzp448WZsPfMA=="], "mdast-util-mdxjs-esm": ["mdast-util-mdxjs-esm@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg=="], "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], - "mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="], + "mdast-util-to-hast": ["mdast-util-to-hast@13.2.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-l2pnmOuqs+SGLVpTVXnRLQu5v1AzvDe181404fbXzzqObVxrAnnVxapAP27pUwzLBL/ABIkgUhGlPVU7QSvIFg=="], - "mdast-util-to-markdown": ["mdast-util-to-markdown@2.1.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA=="], + "mdast-util-to-markdown": ["mdast-util-to-markdown@2.2.5", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", "micromark-util-character": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-mxOMQQ8NgisvTarkSUqZwi6GmzNo490V932DpEK/0+OETIeVJBzq4QuMt45fqqcsF5EYMlJENjSSAZxh89VJsg=="], "mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="], "memoirist": ["memoirist@0.4.0", "", {}, "sha512-zxTgA0mSYELa66DimuNQDvyLq36AwDlTuVRbnQtB+VuTcKWm5Qc4z3WkSpgsFWHNhexqkIooqpv4hdcqrX5Nmg=="], - "merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="], - - "micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="], + "micromark": ["micromark@4.0.3", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-edit-map": "^1.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw=="], - "micromark-core-commonmark": ["micromark-core-commonmark@2.0.3", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg=="], + "micromark-core-commonmark": ["micromark-core-commonmark@2.0.4", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.1.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-edit-map": "^1.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.3" } }, "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w=="], "micromark-extension-gfm": ["micromark-extension-gfm@3.0.0", "", { "dependencies": { "micromark-extension-gfm-autolink-literal": "^2.0.0", "micromark-extension-gfm-footnote": "^2.0.0", "micromark-extension-gfm-strikethrough": "^2.0.0", "micromark-extension-gfm-table": "^2.0.0", "micromark-extension-gfm-tagfilter": "^2.0.0", "micromark-extension-gfm-task-list-item": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w=="], @@ -1202,7 +1133,7 @@ "micromark-extension-gfm-strikethrough": ["micromark-extension-gfm-strikethrough@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw=="], - "micromark-extension-gfm-table": ["micromark-extension-gfm-table@2.1.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg=="], + "micromark-extension-gfm-table": ["micromark-extension-gfm-table@2.1.2", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA=="], "micromark-extension-gfm-tagfilter": ["micromark-extension-gfm-tagfilter@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg=="], @@ -1224,7 +1155,7 @@ "micromark-factory-mdx-expression": ["micromark-factory-mdx-expression@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ=="], - "micromark-factory-space": ["micromark-factory-space@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg=="], + "micromark-factory-space": ["micromark-factory-space@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q=="], "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], @@ -1242,6 +1173,8 @@ "micromark-util-decode-string": ["micromark-util-decode-string@2.0.1", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ=="], + "micromark-util-edit-map": ["micromark-util-edit-map@1.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q=="], + "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], "micromark-util-events-to-acorn": ["micromark-util-events-to-acorn@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg=="], @@ -1258,23 +1191,21 @@ "micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="], - "micromark-util-types": ["micromark-util-types@2.0.2", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="], + "micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], "mime-types": ["mime-types@2.1.18", "", { "dependencies": { "mime-db": "~1.33.0" } }, "sha512-lc/aahn+t4/SWV/qcmumYjymLsWfN3ELhpmVuUFjgsORruuZPVSwAQryq+HHGvO/SI2KVX26bx+En+zhM8g8hQ=="], - "mimic-fn": ["mimic-fn@2.1.0", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="], - "minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], - "monaco-editor": ["monaco-editor@0.55.1", "", { "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" } }, "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A=="], + "monaco-editor": ["monaco-editor@0.58.0", "", { "dependencies": { "@vscode/diff": "0.0.2-145", "dompurify": "3.4.17", "marked": "14.0.0" } }, "sha512-Lj5hlfT4zdM5GSG9VxTHslWnwibGBvO6d9Mq/+9zmb1CkTZnib4+uAZUKl1zg+tMHRgY2OGax6hHKZNBtldR1g=="], - "motion": ["motion@12.42.2", "", { "dependencies": { "framer-motion": "^12.42.2", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-Atvv11yUKIid41cVrRBDVX5m8tF8kNpExRSlbpt6APClhDjtwQssgFHhQzejxw7/7YYbjHSPKBVbHo05BuJT5Q=="], + "motion": ["motion@12.43.0", "", { "dependencies": { "framer-motion": "^12.43.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-BQgQbSa9Hn3/mtbib0MK53y6JSANa+YKUKlaYnWzAVDH424RYQ5LVpV3pNiWH00BA2z4ojsSdMzqT7g2FQwjuQ=="], - "motion-dom": ["motion-dom@12.42.2", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-5gIMWLp/PycBtJRJWRgjxke5n8dlvkSn2DrYW+tr3XcqAZY1xZh6BJyooJXCM8wdfM7wfMjkBJNLge1CKPUIRA=="], + "motion-dom": ["motion-dom@12.43.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag=="], "motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="], @@ -1282,24 +1213,20 @@ "nanoid": ["nanoid@5.1.16", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="], - "negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], + "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], "next-themes": ["next-themes@0.4.6", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="], - "node-releases": ["node-releases@2.0.51", "", {}, "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ=="], + "node-releases": ["node-releases@2.0.66", "", {}, "sha512-uSMWN9/XtWzxaE0d9ZNHe00Hda6028AXH3WRjTsK71neiPCSeL5nGSD9MXTQX/6Qx0k7Op1AyyinmIUw9fBzrg=="], - "npm-run-path": ["npm-run-path@4.0.1", "", { "dependencies": { "path-key": "^3.0.0" } }, "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw=="], + "npm-to-yarn": ["npm-to-yarn@3.2.0", "", {}, "sha512-K1HmQeZT2HrjpsR6KgqbN2FAXL2NrJJmNUSD9ck7HGTVu1JKXox8n9SB+tjbU8m8JGLF4OscrroPepew/L7/Xw=="], - "npm-to-yarn": ["npm-to-yarn@3.0.1", "", {}, "sha512-tt6PvKu4WyzPwWUzy/hvPFqn+uwXO0K1ZHka8az3NnrhWJDmSqI8ncWq0fkL0k/lmmi5tAC11FXwXuh0rFbt1A=="], - - "nuqs": ["nuqs@2.9.1", "", { "dependencies": { "@standard-schema/spec": "1.1.0" }, "peerDependencies": { "@remix-run/react": ">=2", "@tanstack/react-router": "^1", "next": ">=14.2.0", "react": ">=18.2.0 || ^19.0.0-0", "react-router": "^5 || ^6 || ^7 || ^8", "react-router-dom": "^5 || ^6 || ^7" }, "optionalPeers": ["@remix-run/react", "@tanstack/react-router", "next", "react-router", "react-router-dom"] }, "sha512-xctOTExJ/M2lV9NBXTkLMb3vnGBLk/eMuZyiXSbj0jA24H6ie2d7/LJiaA0C30p5XCIWaDTZl5DEF/N2Yo1LCw=="], + "nuqs": ["nuqs@2.10.3", "", { "dependencies": { "@standard-schema/spec": "1.1.0" }, "peerDependencies": { "@remix-run/react": ">=2", "@tanstack/react-router": "^1", "next": ">=14.2.0", "react": ">=18.2.0 || ^19.0.0-0", "react-router": "^5 || ^6 || ^7 || ^8", "react-router-dom": "^5 || ^6 || ^7" }, "optionalPeers": ["@remix-run/react", "@tanstack/react-router", "next", "react-router", "react-router-dom"] }, "sha512-dNGDsvpKFoxyDLOWZh+OiQ02od3RLJ52044I+Ld1wjTCVOv7ZZtBmd2Aq7CHFdDGYRn+hg6FPPh6FUMFX2YLaQ=="], "on-exit-leak-free": ["on-exit-leak-free@2.1.2", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="], "on-headers": ["on-headers@1.1.0", "", {}, "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A=="], - "onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="], - "oniguruma-parser": ["oniguruma-parser@0.12.2", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="], "oniguruma-to-es": ["oniguruma-to-es@4.3.6", "", { "dependencies": { "oniguruma-parser": "^0.12.2", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA=="], @@ -1308,7 +1235,7 @@ "oxfmt": ["oxfmt@0.59.0", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.59.0", "@oxfmt/binding-android-arm64": "0.59.0", "@oxfmt/binding-darwin-arm64": "0.59.0", "@oxfmt/binding-darwin-x64": "0.59.0", "@oxfmt/binding-freebsd-x64": "0.59.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.59.0", "@oxfmt/binding-linux-arm-musleabihf": "0.59.0", "@oxfmt/binding-linux-arm64-gnu": "0.59.0", "@oxfmt/binding-linux-arm64-musl": "0.59.0", "@oxfmt/binding-linux-ppc64-gnu": "0.59.0", "@oxfmt/binding-linux-riscv64-gnu": "0.59.0", "@oxfmt/binding-linux-riscv64-musl": "0.59.0", "@oxfmt/binding-linux-s390x-gnu": "0.59.0", "@oxfmt/binding-linux-x64-gnu": "0.59.0", "@oxfmt/binding-linux-x64-musl": "0.59.0", "@oxfmt/binding-openharmony-arm64": "0.59.0", "@oxfmt/binding-win32-arm64-msvc": "0.59.0", "@oxfmt/binding-win32-ia32-msvc": "0.59.0", "@oxfmt/binding-win32-x64-msvc": "0.59.0" }, "peerDependencies": { "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-Xqk6cPZS1yMvVa7OAuenaDZUsgMDutvvbZ9/L5gSvAfW64+WN4HVhgipLj5rVERbYQt8fLs9TopyZ1rU1XEG/w=="], - "oxlint": ["oxlint@1.74.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.74.0", "@oxlint/binding-android-arm64": "1.74.0", "@oxlint/binding-darwin-arm64": "1.74.0", "@oxlint/binding-darwin-x64": "1.74.0", "@oxlint/binding-freebsd-x64": "1.74.0", "@oxlint/binding-linux-arm-gnueabihf": "1.74.0", "@oxlint/binding-linux-arm-musleabihf": "1.74.0", "@oxlint/binding-linux-arm64-gnu": "1.74.0", "@oxlint/binding-linux-arm64-musl": "1.74.0", "@oxlint/binding-linux-ppc64-gnu": "1.74.0", "@oxlint/binding-linux-riscv64-gnu": "1.74.0", "@oxlint/binding-linux-riscv64-musl": "1.74.0", "@oxlint/binding-linux-s390x-gnu": "1.74.0", "@oxlint/binding-linux-x64-gnu": "1.74.0", "@oxlint/binding-linux-x64-musl": "1.74.0", "@oxlint/binding-openharmony-arm64": "1.74.0", "@oxlint/binding-win32-arm64-msvc": "1.74.0", "@oxlint/binding-win32-ia32-msvc": "1.74.0", "@oxlint/binding-win32-x64-msvc": "1.74.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.24.0", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-odGl2s2x5IOJoj3A0v1k0PGBXVFBZeZ2+AK/+K2MJur7Ghi3bkyX5NuLUWHKqa4js1wjep3hJeuTQJOlr+4+dA=="], + "oxlint": ["oxlint@1.95.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.95.0", "@oxlint/binding-android-arm64": "1.95.0", "@oxlint/binding-darwin-arm64": "1.95.0", "@oxlint/binding-darwin-x64": "1.95.0", "@oxlint/binding-freebsd-x64": "1.95.0", "@oxlint/binding-linux-arm-gnueabihf": "1.95.0", "@oxlint/binding-linux-arm-musleabihf": "1.95.0", "@oxlint/binding-linux-arm64-gnu": "1.95.0", "@oxlint/binding-linux-arm64-musl": "1.95.0", "@oxlint/binding-linux-ppc64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-musl": "1.95.0", "@oxlint/binding-linux-s390x-gnu": "1.95.0", "@oxlint/binding-linux-x64-gnu": "1.95.0", "@oxlint/binding-linux-x64-musl": "1.95.0", "@oxlint/binding-openharmony-arm64": "1.95.0", "@oxlint/binding-win32-arm64-msvc": "1.95.0", "@oxlint/binding-win32-ia32-msvc": "1.95.0", "@oxlint/binding-win32-x64-msvc": "1.95.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2008", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-eNzjFjm1TU02/+ohAJjOB7aekRQgTXhOWxMGscEm8VJMokNnnix+PCZn7kqIuGIqxAoBnHxatqlN3Chz3N6PKA=="], "p-retry": ["p-retry@7.1.1", "", { "dependencies": { "is-network-error": "^1.1.0" } }, "sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w=="], @@ -1316,49 +1243,45 @@ "path-is-inside": ["path-is-inside@1.0.2", "", {}, "sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w=="], - "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], - "path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], - "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], - "pino": ["pino@10.3.1", "", { "dependencies": { "@pinojs/redact": "^0.4.0", "atomic-sleep": "^1.0.0", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^3.0.0", "pino-std-serializers": "^7.0.0", "process-warning": "^5.0.0", "quick-format-unescaped": "^4.0.3", "real-require": "^0.2.0", "safe-stable-stringify": "^2.3.1", "sonic-boom": "^4.0.1", "thread-stream": "^4.0.0" }, "bin": { "pino": "bin.js" } }, "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg=="], + "pino": ["pino@10.4.0", "", { "dependencies": { "@pinojs/redact": "^0.4.0", "atomic-sleep": "^1.0.0", "on-exit-leak-free": "^2.1.0", "pino-abstract-transport": "^3.0.0", "pino-std-serializers": "^7.0.0", "process-warning": "^5.0.0", "quick-format-unescaped": "^4.0.3", "real-require": "^1.0.0", "safe-stable-stringify": "^2.3.1", "sonic-boom": "^4.0.1", "thread-stream": "^4.0.0" }, "bin": { "pino": "bin.js" } }, "sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA=="], "pino-abstract-transport": ["pino-abstract-transport@3.0.0", "", { "dependencies": { "split2": "^4.0.0" } }, "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg=="], "pino-std-serializers": ["pino-std-serializers@7.1.0", "", {}, "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw=="], - "postcss": ["postcss@8.5.20", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-lW616l85ucIQL+FocMmL7pQFPqBmwejrCMg+iPxyImlrANNJG9NHq/RkyCZopDhd8C3LA03PHRJDjkbGu8vvug=="], + "postcss": ["postcss@8.5.34", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.4" } }, "sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw=="], - "postcss-selector-parser": ["postcss-selector-parser@7.1.4", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg=="], + "postcss-selector-parser": ["postcss-selector-parser@7.2.1", "", { "dependencies": { "util-deprecate": "^1.0.2" } }, "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ=="], - "postgres": ["postgres@4.1.1", "", {}, "sha512-1kJDojqNZC+iTHHXh6eif0J98LUtyLAePe/qkW1GK35eh2JixlsAiIKq3FGI+xqI+SUGTNodzf7TScVeIIyUug=="], + "postgres": ["postgres@4.2.0", "", {}, "sha512-9/HKJPaDuY7bhg97y8aYcTaF9hNAXGu85Fo/TNGnPkVoTGZWLsJNcLmhjv291K4mxC4glRdsfsbV42986JbntQ=="], - "prettier": ["prettier@3.9.5", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-/FVl766LpUfB5vXgCYOYa0MeV/441Ia99AeICQIQFTY/Nw0roZwULcXpku5i1/m5kt/baz+s4Zogspd839HSMg=="], + "prettier": ["prettier@3.10.1", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg=="], - "process-warning": ["process-warning@5.0.0", "", {}, "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA=="], + "process-warning": ["process-warning@5.1.1", "", {}, "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg=="], "property-information": ["property-information@7.2.0", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="], "quick-format-unescaped": ["quick-format-unescaped@4.0.4", "", {}, "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="], - "radix-ui": ["radix-ui@1.6.2", "", { "dependencies": { "@radix-ui/primitive": "1.1.5", "@radix-ui/react-accessible-icon": "1.1.11", "@radix-ui/react-accordion": "1.2.16", "@radix-ui/react-alert-dialog": "1.1.19", "@radix-ui/react-arrow": "1.1.11", "@radix-ui/react-aspect-ratio": "1.1.11", "@radix-ui/react-avatar": "1.2.2", "@radix-ui/react-checkbox": "1.3.7", "@radix-ui/react-collapsible": "1.1.16", "@radix-ui/react-collection": "1.1.12", "@radix-ui/react-compose-refs": "1.1.3", "@radix-ui/react-context": "1.2.0", "@radix-ui/react-context-menu": "2.3.3", "@radix-ui/react-dialog": "1.1.19", "@radix-ui/react-direction": "1.1.2", "@radix-ui/react-dismissable-layer": "1.1.15", "@radix-ui/react-dropdown-menu": "2.1.20", "@radix-ui/react-focus-guards": "1.1.4", "@radix-ui/react-focus-scope": "1.1.12", "@radix-ui/react-form": "0.1.12", "@radix-ui/react-hover-card": "1.1.19", "@radix-ui/react-label": "2.1.11", "@radix-ui/react-menu": "2.1.20", "@radix-ui/react-menubar": "1.1.20", "@radix-ui/react-navigation-menu": "1.2.18", "@radix-ui/react-one-time-password-field": "0.1.12", "@radix-ui/react-password-toggle-field": "0.1.7", "@radix-ui/react-popover": "1.1.19", "@radix-ui/react-popper": "1.3.3", "@radix-ui/react-portal": "1.1.13", "@radix-ui/react-presence": "1.1.7", "@radix-ui/react-primitive": "2.1.7", "@radix-ui/react-progress": "1.1.12", "@radix-ui/react-radio-group": "1.4.3", "@radix-ui/react-roving-focus": "1.1.15", "@radix-ui/react-scroll-area": "1.2.14", "@radix-ui/react-select": "2.3.3", "@radix-ui/react-separator": "1.1.11", "@radix-ui/react-slider": "1.4.3", "@radix-ui/react-slot": "1.3.0", "@radix-ui/react-switch": "1.3.3", "@radix-ui/react-tabs": "1.1.17", "@radix-ui/react-toast": "1.2.19", "@radix-ui/react-toggle": "1.1.14", "@radix-ui/react-toggle-group": "1.1.15", "@radix-ui/react-toolbar": "1.1.15", "@radix-ui/react-tooltip": "1.2.12", "@radix-ui/react-use-callback-ref": "1.1.2", "@radix-ui/react-use-controllable-state": "1.2.3", "@radix-ui/react-use-effect-event": "0.0.3", "@radix-ui/react-use-escape-keydown": "1.1.3", "@radix-ui/react-use-is-hydrated": "0.1.1", "@radix-ui/react-use-layout-effect": "1.1.2", "@radix-ui/react-use-size": "1.1.2", "@radix-ui/react-visually-hidden": "1.2.7" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-OwYUjzMwiInCUxgAWpPsavXC3Kh4iyi/49uU1/qZTG3RQDlvegyk1GOMiGvSkjua1RDb3JD3fo3eroL9FV4GQw=="], - "range-parser": ["range-parser@1.2.0", "", {}, "sha512-kA5WQoNVo4t9lNx2kQNFCxKeBl5IbbSNBl1M/tLkw9WCn+hxNBAW5Qh8gdhs63CJnhjJ2zQWFoqPJP2sK1AV5A=="], "rc": ["rc@1.2.8", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="], - "react": ["react@19.2.7", "", {}, "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ=="], + "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], "react-day-picker": ["react-day-picker@9.14.0", "", { "dependencies": { "@date-fns/tz": "^1.4.1", "@tabby_ai/hijri-converter": "1.0.5", "date-fns": "^4.1.0", "date-fns-jalali": "4.1.0-0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-tBaoDWjPwe0M5pGrum4H0SR6Lyk+BO9oHnp9JbKpGKW2mlraNPgP9BMfsg5pWpwrssARmeqk7YBl2oXutZTaHA=="], - "react-dom": ["react-dom@19.2.7", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.7" } }, "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ=="], + "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], - "react-medium-image-zoom": ["react-medium-image-zoom@5.4.8", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-72CIldEUaPejjcaDOYIeDsGlWzNKpmxyKgiPi1LBCkWCIGHDLlA2KTeo2uNtmN/m72Y3k/2uWDfon9SDiPbHaA=="], + "react-medium-image-zoom": ["react-medium-image-zoom@5.4.9", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-czBdTbJI6JEbqeRIT5M8D3j7TrffBfo00U0P0lzzd19usj8PiR1yPH7PK/vQlwBE/Sv9YFdJGN6XauJPi4jRyg=="], "react-refresh": ["react-refresh@0.18.0", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="], @@ -1366,13 +1289,13 @@ "react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="], - "react-resizable-panels": ["react-resizable-panels@4.12.2", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" } }, "sha512-NwY5LCo4WrxVvDh0xoMML6EMLPONP/8ckKcIdpnojxexoatZdjLiRqLJQjQK5CPkd4SYiB/2M5BVrjZBQtOO7Q=="], + "react-resizable-panels": ["react-resizable-panels@4.27.0", "", { "peerDependencies": { "@types/react": "^18.2.6 || ^19.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-Vx1iV27gJ3P0yYTJPWMlrVw/k8DUGKGossvM+igzfr5Hia4zeVHoC9EalqU/v+BCmFYBxmIdDXbp6W84HX1q3w=="], "react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="], "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], - "real-require": ["real-require@0.2.0", "", {}, "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="], + "real-require": ["real-require@1.0.0", "", {}, "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g=="], "recma-build-jsx": ["recma-build-jsx@1.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-util-build-jsx": "^3.0.0", "vfile": "^6.0.0" } }, "sha512-8GtdyqaBcDfva+GUKDr3nev3VpKAhup1+RvkMvUxURHpW7QyIvk9F5wz7Vzo06CEMSilw6uArgRqhpiUcWp8ew=="], @@ -1410,7 +1333,7 @@ "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], - "rollup": ["rollup@4.62.2", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.62.2", "@rollup/rollup-android-arm64": "4.62.2", "@rollup/rollup-darwin-arm64": "4.62.2", "@rollup/rollup-darwin-x64": "4.62.2", "@rollup/rollup-freebsd-arm64": "4.62.2", "@rollup/rollup-freebsd-x64": "4.62.2", "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", "@rollup/rollup-linux-arm-musleabihf": "4.62.2", "@rollup/rollup-linux-arm64-gnu": "4.62.2", "@rollup/rollup-linux-arm64-musl": "4.62.2", "@rollup/rollup-linux-loong64-gnu": "4.62.2", "@rollup/rollup-linux-loong64-musl": "4.62.2", "@rollup/rollup-linux-ppc64-gnu": "4.62.2", "@rollup/rollup-linux-ppc64-musl": "4.62.2", "@rollup/rollup-linux-riscv64-gnu": "4.62.2", "@rollup/rollup-linux-riscv64-musl": "4.62.2", "@rollup/rollup-linux-s390x-gnu": "4.62.2", "@rollup/rollup-linux-x64-gnu": "4.62.2", "@rollup/rollup-linux-x64-musl": "4.62.2", "@rollup/rollup-openbsd-x64": "4.62.2", "@rollup/rollup-openharmony-arm64": "4.62.2", "@rollup/rollup-win32-arm64-msvc": "4.62.2", "@rollup/rollup-win32-ia32-msvc": "4.62.2", "@rollup/rollup-win32-x64-gnu": "4.62.2", "@rollup/rollup-win32-x64-msvc": "4.62.2", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA=="], + "rollup": ["rollup@4.69.1", "", { "dependencies": { "@types/estree": "^1.0.10" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.69.1", "@rollup/rollup-android-arm64": "4.69.1", "@rollup/rollup-android-x64": "4.69.1", "@rollup/rollup-darwin-arm64": "4.69.1", "@rollup/rollup-darwin-x64": "4.69.1", "@rollup/rollup-freebsd-arm64": "4.69.1", "@rollup/rollup-freebsd-x64": "4.69.1", "@rollup/rollup-linux-arm-gnueabihf": "4.69.1", "@rollup/rollup-linux-arm-musleabihf": "4.69.1", "@rollup/rollup-linux-arm64-gnu": "4.69.1", "@rollup/rollup-linux-arm64-musl": "4.69.1", "@rollup/rollup-linux-loong64-gnu": "4.69.1", "@rollup/rollup-linux-loong64-musl": "4.69.1", "@rollup/rollup-linux-ppc64-gnu": "4.69.1", "@rollup/rollup-linux-ppc64-musl": "4.69.1", "@rollup/rollup-linux-riscv64-gnu": "4.69.1", "@rollup/rollup-linux-riscv64-musl": "4.69.1", "@rollup/rollup-linux-s390x-gnu": "4.69.1", "@rollup/rollup-linux-x64-gnu": "4.69.1", "@rollup/rollup-linux-x64-musl": "4.69.1", "@rollup/rollup-openbsd-x64": "4.69.1", "@rollup/rollup-openharmony-arm64": "4.69.1", "@rollup/rollup-win32-arm64-msvc": "4.69.1", "@rollup/rollup-win32-ia32-msvc": "4.69.1", "@rollup/rollup-win32-x64-gnu": "4.69.1", "@rollup/rollup-win32-x64-msvc": "4.69.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-vWe2JWir6FmmYA78Af6xZABpkYGvuKcgy6gZuOxa7PXNayPQ/lJqkqUgeiZelX8q2Djgu5XKP0qk77y0WXn2JQ=="], "rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="], @@ -1418,35 +1341,29 @@ "safe-stable-stringify": ["safe-stable-stringify@2.5.0", "", {}, "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA=="], - "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], + "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], - "scroll-into-view-if-needed": ["scroll-into-view-if-needed@3.1.0", "", { "dependencies": { "compute-scroll-into-view": "^3.0.2" } }, "sha512-49oNpRjWRvnU8NyGVmUaYG4jtTkNonFZI86MmGRDqBphEK2EXT9gdEUoQPZhuBM8yWHxCWbobltqYO5M4XrUvQ=="], + "scroll-into-view-if-needed": ["scroll-into-view-if-needed@3.2.1", "", { "dependencies": { "compute-scroll-into-view": "^3.2.2" } }, "sha512-dgeJvJhSV9MY6hyhtsivbSxHoZVm+lumsWTObtUdAchJflwOGmKKHNkEpU8pVYMomZ8h/yrfzVQkcPlObQNDWQ=="], - "semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], - "seroval": ["seroval@1.5.5", "", {}, "sha512-bSjOuPcwPKLSJNhr9+bZxA20nQxVle5J5MNsYRVE6cIg7KpRLXGupymePavu0jrxlPiPsr4xGZSB8yUY2sH2sw=="], + "seroval": ["seroval@1.8.2", "", {}, "sha512-zmMxi/9MdLK1MKazLmIP6Rk39RuK0Xydd+QHeOYntS37olJeTjB3+nwVj4ce/ZWiZJeRhcO5htfxt0mUzQBscQ=="], - "seroval-plugins": ["seroval-plugins@1.5.5", "", { "peerDependencies": { "seroval": "^1.0" } }, "sha512-+BDhqYM6CEn3x09v44dpa9p6974FuUB2dxk+Ctn04k0cO1Zt6QODTXfmEZK0eBaTe/fJBvP4NMGuNJ+R8T+QMg=="], + "seroval-plugins": ["seroval-plugins@1.8.0", "", { "peerDependencies": { "seroval": "^1.8.0" } }, "sha512-96vBb12rDvPPwdKUgWw1op3fGq8AVBFOr0IllbnM72yR5J9WWXF18cQ4g1XfDO7HCyh2dt70P3XdtyRayP8FWg=="], - "serve": ["serve@14.2.6", "", { "dependencies": { "@zeit/schemas": "2.36.0", "ajv": "8.18.0", "arg": "5.0.2", "boxen": "7.0.0", "chalk": "5.0.1", "chalk-template": "0.4.0", "clipboardy": "3.0.0", "compression": "1.8.1", "is-port-reachable": "4.0.0", "serve-handler": "6.1.7", "update-check": "1.5.4" }, "bin": { "serve": "build/main.js" } }, "sha512-QEjUSA+sD4Rotm1znR8s50YqA3kYpRGPmtd5GlFxbaL9n/FdUNbqMhxClqdditSk0LlZyA/dhud6XNRTOC9x2Q=="], + "serve": ["serve@14.2.8", "", { "dependencies": { "@zeit/schemas": "2.36.0", "ajv": "8.18.0", "arg": "5.0.2", "boxen": "7.0.0", "chalk": "5.0.1", "chalk-template": "0.4.0", "compression": "1.8.2", "is-port-reachable": "4.0.0", "serve-handler": "6.1.7", "tinyclip": "^0.1.12", "update-check": "1.5.4" }, "bin": { "serve": "build/main.js" } }, "sha512-7or7YqR3zXwHhiBGj40l9yODyQY146O+hXKaEAfQYQkcvHtMDdX95K96xr50qL9EjXScyYVJb1NIgVE8F0i5cA=="], "serve-handler": ["serve-handler@6.1.7", "", { "dependencies": { "bytes": "3.0.0", "content-disposition": "0.5.2", "mime-types": "2.1.18", "minimatch": "3.1.5", "path-is-inside": "1.0.2", "path-to-regexp": "3.3.0", "range-parser": "1.2.0" } }, "sha512-CinAq1xWb0vR3twAv9evEU8cNWkXCb9kd5ePAHUKJBkOsUpR1wt/CvGdeca7vqumL1U5cSaeVQ6zZMxiJ3yWsg=="], "shared-actions": ["shared-actions@workspace:packages/shared-actions"], - "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], - - "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], - "shiki": ["shiki@3.23.0", "", { "dependencies": { "@shikijs/core": "3.23.0", "@shikijs/engine-javascript": "3.23.0", "@shikijs/engine-oniguruma": "3.23.0", "@shikijs/langs": "3.23.0", "@shikijs/themes": "3.23.0", "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-55Dj73uq9ZXL5zyeRPzHQsK7Nbyt6Y10k5s7OjuFZGMhpp4r/rsLBH0o/0fstIzX1Lep9VxefWljK/SKCzygIA=="], - "signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], - "sonic-boom": ["sonic-boom@4.2.1", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q=="], "source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], - "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + "source-map-js": ["source-map-js@1.3.0", "", {}, "sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q=="], "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], @@ -1458,37 +1375,37 @@ "string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="], - "stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="], + "stringify-entities": ["stringify-entities@4.0.5", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-jNuI2fNNw5ecxrWmgm90R3iH0Kc/94AQwoQWoSUYphWzvmUA2pjFG34H56Z7Z3FkvH3FpYwwewKAa97oQnPFhw=="], "strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], - "strip-final-newline": ["strip-final-newline@2.0.0", "", {}, "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="], - "strip-json-comments": ["strip-json-comments@2.0.1", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="], - "strtok3": ["strtok3@10.3.5", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA=="], + "strtok3": ["strtok3@10.8.0", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-e6bW3fD6V01DPmcbLfNtn0cjsiHvTKS/hivgbzqYMfHb/nLes4QQ0H5QBxlkPQayF4xv08AvlSgptGwN86Eemw=="], "style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="], - "style-to-object": ["style-to-object@1.0.14", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="], + "style-to-object": ["style-to-object@2.0.2", "", { "dependencies": { "inline-style-parser": "0.2.9" } }, "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA=="], "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], - "tailwind-merge": ["tailwind-merge@3.6.0", "", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="], + "tailwind-merge": ["tailwind-merge@3.7.1", "", {}, "sha512-v7y4BV4FUlO8exj/4M5UXKeoowDiuugVUg3tkMNIyOUCOHy5xp8+5aWQeXCtZ2491sUV1YPsVeM9EveZ6/xuZQ=="], + + "tailwindcss": ["tailwindcss@4.3.5", "", {}, "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ=="], - "tailwindcss": ["tailwindcss@4.3.3", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="], + "tapable": ["tapable@2.3.4", "", {}, "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg=="], - "tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="], + "thread-stream": ["thread-stream@4.2.1", "", { "dependencies": { "real-require": "^1.0.0" } }, "sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ=="], - "thread-stream": ["thread-stream@4.2.0", "", { "dependencies": { "real-require": "^1.0.0" } }, "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ=="], + "tinyclip": ["tinyclip@0.1.15", "", {}, "sha512-uo33abH+Ays0xYaDysoBt494Hb3hsEczMpcC0MwFl773pazORx4fmvKhclhR1wonUbB6vvpRsvVMwnhfqeMc+A=="], - "tinyexec": ["tinyexec@1.2.4", "", {}, "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg=="], + "tinyexec": ["tinyexec@1.4.0", "", {}, "sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg=="], "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], "tinypool": ["tinypool@2.1.0", "", {}, "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw=="], - "token-types": ["token-types@6.1.2", "", { "dependencies": { "@borewit/text-codec": "^0.2.1", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww=="], + "token-types": ["token-types@6.2.0", "", { "dependencies": { "@borewit/text-codec": "^0.2.3", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-s9euYHM//T3loJtbNUYdbAzsMlvKBeRS+XCLFy+UGosMQH19Hwjap5k19i4PPAEJJBsVIpMpVTxl4fIqCuNfUg=="], "trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="], @@ -1496,7 +1413,7 @@ "tsconfck": ["tsconfck@3.1.6", "", { "peerDependencies": { "typescript": "^5.0.0" }, "optionalPeers": ["typescript"], "bin": { "tsconfck": "bin/tsconfck.js" } }, "sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w=="], - "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], "tw-animate-css": ["tw-animate-css@1.4.0", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="], @@ -1506,9 +1423,11 @@ "ufo": ["ufo@1.6.4", "", {}, "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA=="], - "uint8array-extras": ["uint8array-extras@1.5.0", "", {}, "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A=="], + "uint8array-extras": ["uint8array-extras@1.6.0", "", {}, "sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q=="], - "undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="], + "undici": ["undici@6.29.1", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="], + + "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], "unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="], @@ -1522,13 +1441,13 @@ "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], - "unist-util-visit": ["unist-util-visit@5.1.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg=="], + "unist-util-visit": ["unist-util-visit@5.2.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ=="], - "unist-util-visit-parents": ["unist-util-visit-parents@6.0.2", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="], + "unist-util-visit-parents": ["unist-util-visit-parents@6.1.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w=="], - "unplugin": ["unplugin@3.3.0", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "picomatch": "^4.0.4", "webpack-virtual-modules": "^0.6.2" }, "peerDependencies": { "@farmfe/core": "*", "@rspack/core": "*", "bun-types-no-globals": "*", "esbuild": "*", "rolldown": "*", "rollup": "*", "unloader": "*", "vite": "*", "webpack": "*" }, "optionalPeers": ["@farmfe/core", "@rspack/core", "bun-types-no-globals", "esbuild", "rolldown", "rollup", "unloader", "vite", "webpack"] }, "sha512-qa66K+crbfyE6JK10GjvbJeRrOsuC/JpbnHctfyp/i4oBTxWOzJfRZyDiOk1PtErMFRu8JhsU/wPvOdBNWe5Rg=="], + "unplugin": ["unplugin@3.7.0", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "@rolldown/pluginutils": "^1.0.1", "picomatch": "^4.0.7", "webpack-virtual-modules": "^0.6.2" }, "peerDependencies": { "@farmfe/core": "*", "@rsbuild/core": "*", "@rspack/core": "*", "bun-types-no-globals": "*", "esbuild": "*", "rolldown": "*", "rollup": "*", "unloader": "*", "vite": "*", "webpack": "*" }, "optionalPeers": ["@farmfe/core", "@rsbuild/core", "@rspack/core", "bun-types-no-globals", "esbuild", "rolldown", "rollup", "unloader", "vite", "webpack"] }, "sha512-GrM2uq3DQo3hvLU2FjeYhooJ8BY9N6j1Fbzgx7Pta3VVJevsD3VP4dPjZkZOS0mLvN8w9zzr9OlP+31bSMyuLw=="], - "update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="], + "update-browserslist-db": ["update-browserslist-db@1.4.0", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w=="], "update-check": ["update-check@1.5.4", "", { "dependencies": { "registry-auth-token": "3.3.2", "registry-url": "3.1.0" } }, "sha512-5YHsflzHP4t1G+8WGPlvKbJEbAJGCgw+Em+dGR1KmBUbr1J36SJBqlHLjR7oob7sco5hWHGQVcr9B2poIVDDTQ=="], @@ -1536,7 +1455,7 @@ "use-sidecar": ["use-sidecar@1.1.3", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="], - "use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="], + "use-sync-external-store": ["use-sync-external-store@1.7.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="], "usehooks-ts": ["usehooks-ts@3.1.1", "", { "dependencies": { "lodash.debounce": "^4.0.8" }, "peerDependencies": { "react": "^16.8.0 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-I4diPp9Cq6ieSUH2wu+fDAVQO43xwtulo+fKEidHUwZPnYImbtkTjzIJYcDcJqxgmX31GVqNFURodvcgHcW0pA=="], @@ -1546,18 +1465,16 @@ "vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="], - "vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="], + "vfile-message": ["vfile-message@4.0.4", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg=="], - "vite": ["vite@7.3.6", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="], + "vite": ["vite@7.3.8", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw=="], "vite-tsconfig-paths": ["vite-tsconfig-paths@5.1.4", "", { "dependencies": { "debug": "^4.1.1", "globrex": "^0.1.2", "tsconfck": "^3.0.3" }, "peerDependencies": { "vite": "*" }, "optionalPeers": ["vite"] }, "sha512-cYj0LRuLV2c2sMqhqhGpaO3LretdtMn/BVX4cPLanIZuwwrkVl+lK84E/miEXkCHWXuq65rhNN4rXsBcOB3S4w=="], - "vitefu": ["vitefu@1.1.3", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg=="], + "vitefu": ["vitefu@1.1.4", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-qbEIDswfXH3x3IYRMScl/bf1AVW0dn7Z8qkr7g7nohkusfuC7tcFa7t5EoTOz60AunosLM9sDrDjHxsX+Up+CQ=="], "webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], - "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], - "widest-line": ["widest-line@4.0.1", "", { "dependencies": { "string-width": "^5.0.1" } }, "sha512-o0cyEG0e8GPzT4iGHphIOh0cJOV8fivsXxddQasHPHfoZf1ZexrfeA21w2NaEN1RHE+fXlfISmOE8R9N3u3Qig=="], "wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="], @@ -1566,23 +1483,37 @@ "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], - "zod": ["zod@4.5.4", "", {}, "sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA=="], + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], - "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.2", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" }, "bundled": true }, "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA=="], + "@opentelemetry/context-async-hooks/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="], + "@opentelemetry/core/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], + "@opentelemetry/resources/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" }, "bundled": true }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="], + "@opentelemetry/sdk-trace/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="], + "@opentelemetry/sdk-trace-base/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "@opentelemetry/sdk-trace-node/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], + + "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.7", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" }, "bundled": true }, "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ=="], + + "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/wasm-util@0.10.5", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA=="], + + "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.9.1", "", { "bundled": true }, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + + "@tanstack/router-generator/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], "@tanstack/router-plugin/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], @@ -1598,25 +1529,23 @@ "docs/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], - "examples/@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], - "fumadocs-ui/fumadocs-core": ["fumadocs-core@16.1.0", "", { "dependencies": { "@formatjs/intl-localematcher": "^0.6.2", "@orama/orama": "^3.1.16", "@shikijs/rehype": "^3.15.0", "@shikijs/transformers": "^3.15.0", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "hast-util-to-estree": "^3.1.3", "hast-util-to-jsx-runtime": "^2.3.6", "image-size": "^2.0.2", "negotiator": "^1.0.0", "npm-to-yarn": "^3.0.1", "path-to-regexp": "^8.3.0", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-rehype": "^11.1.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^3.15.0", "unist-util-visit": "^5.0.0" }, "peerDependencies": { "@mixedbread/sdk": "^0.19.0", "@orama/core": "1.x.x", "@tanstack/react-router": "1.x.x", "@types/react": "*", "algoliasearch": "5.x.x", "lucide-react": "*", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "react-router": "7.x.x", "waku": "^0.26.0 || ^0.27.0" }, "optionalPeers": ["@mixedbread/sdk", "@orama/core", "@tanstack/react-router", "@types/react", "algoliasearch", "lucide-react", "next", "react", "react-dom", "react-router", "waku"] }, "sha512-5pbO2bOGc/xlb2yLQSy6Oag8mvD5CNf5HzQIG80HjZzLXYWEOHW8yovRKnWKRF9gAibn6WHnbssj3YPAlitV/A=="], "mime-types/mime-db": ["mime-db@1.33.0", "", {}, "sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ=="], "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], - "postcss/nanoid": ["nanoid@3.3.16", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="], + "postcss/nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], "serve-handler/bytes": ["bytes@3.0.0", "", {}, "sha512-pMhOfFDPiv9t5jjIXkHosWmkSyQbvsgEVNkz0ERHbuLh2T/7j4Mqqpz523Fe8MVY89KC6Sh/QfS2sM+SjgFDcw=="], "serve-handler/path-to-regexp": ["path-to-regexp@3.3.0", "", {}, "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw=="], - "shared-actions/@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], + "style-to-js/style-to-object": ["style-to-object@1.0.14", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="], - "thread-stream/real-require": ["real-require@1.0.0", "", {}, "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g=="], + "unplugin/@rolldown/pluginutils": ["@rolldown/pluginutils@1.1.1", "", {}, "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA=="], - "@tanstack/router-plugin/chokidar/readdirp": ["readdirp@5.0.0", "", {}, "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ=="], + "@tanstack/router-plugin/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], "ansi-align/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], @@ -1626,9 +1555,7 @@ "compression/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], - "examples/@types/bun/bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], - - "shared-actions/@types/bun/bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], + "style-to-js/style-to-object/inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="], "ansi-align/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], } diff --git a/package.json b/package.json index 9d756b1..a51ac66 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "dependencies": {}, "devDependencies": { "oxfmt": "^0.59.0", - "oxlint": "^1.74.0", + "oxlint": "^1.95.0", "typescript": "^7.0.2" } } diff --git a/packages/docs/content/docs/getting-started.mdx b/packages/docs/content/docs/getting-started.mdx index 6a1614a..a9d2c74 100644 --- a/packages/docs/content/docs/getting-started.mdx +++ b/packages/docs/content/docs/getting-started.mdx @@ -24,7 +24,7 @@ yarn add duron drizzle-orm@rc bun add duron drizzle-orm@rc ``` -Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.1.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. Install postgres for the current database: diff --git a/packages/docs/package.json b/packages/docs/package.json index 70ef883..087af53 100644 --- a/packages/docs/package.json +++ b/packages/docs/package.json @@ -11,29 +11,27 @@ "postinstall": "fumadocs-mdx" }, "dependencies": { - "@orama/orama": "^3.1.16", + "@orama/orama": "^3.1.18", "@tanstack/react-router": "^1.134.12", - "@tanstack/react-router-devtools": "^1.134.12", "@tanstack/react-start": "^1.134.12", "@tanstack/start-static-server-functions": "^1.134.12", "fumadocs-core": "16.2.0", "fumadocs-mdx": "14.0.3", "fumadocs-ui": "16.1.0", "lucide-static": "^0.552.0", - "react": "^19.2.0", - "react-dom": "^19.2.0", - "tailwind-merge": "^3.3.1", - "vite": "^7.2.0" + "react": "^19.3.1", + "react-dom": "^19.3.1", + "vite": "^7.3.8" }, "devDependencies": { - "@tailwindcss/vite": "^4.1.16", - "@types/mdx": "^2.0.13", - "@types/node": "^24.10.0", - "@types/react": "^19.2.2", - "@types/react-dom": "^19.2.2", - "@vitejs/plugin-react": "^5.1.0", - "serve": "^14.2.5", - "tailwindcss": "^4.1.16", + "@tailwindcss/vite": "^4.3.5", + "@types/mdx": "^2.0.14", + "@types/node": "^24.19.4", + "@types/react": "^19.3.3", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^5.2.0", + "serve": "^14.2.8", + "tailwindcss": "^4.3.5", "typescript": "^5.9.3", "vite-tsconfig-paths": "^5.1.4" } diff --git a/packages/duron-dashboard/package.json b/packages/duron-dashboard/package.json index 68f961f..ea39da2 100644 --- a/packages/duron-dashboard/package.json +++ b/packages/duron-dashboard/package.json @@ -43,46 +43,43 @@ "@maskito/kit": "^4.0.1", "@maskito/react": "^4.0.1", "@monaco-editor/react": "^4.7.0", - "@radix-ui/react-accordion": "^1.2.12", - "@radix-ui/react-checkbox": "^1.3.3", - "@radix-ui/react-dialog": "^1.1.15", - "@radix-ui/react-dropdown-menu": "^2.1.16", - "@radix-ui/react-label": "^2.1.8", - "@radix-ui/react-popover": "^1.1.15", - "@radix-ui/react-scroll-area": "^1.2.10", - "@radix-ui/react-select": "^2.2.6", - "@radix-ui/react-separator": "^1.1.8", - "@radix-ui/react-slider": "^1.3.6", - "@radix-ui/react-slot": "^1.2.4", - "@radix-ui/react-tooltip": "^1.2.8", - "@tanstack/react-query": "^5.90.10", + "@radix-ui/react-accordion": "^1.3.1", + "@radix-ui/react-checkbox": "^1.4.1", + "@radix-ui/react-dialog": "^1.3.1", + "@radix-ui/react-dropdown-menu": "^2.2.1", + "@radix-ui/react-label": "^2.1.17", + "@radix-ui/react-popover": "^1.3.1", + "@radix-ui/react-scroll-area": "^1.4.0", + "@radix-ui/react-select": "^2.4.1", + "@radix-ui/react-separator": "^1.2.0", + "@radix-ui/react-slider": "^1.6.1", + "@radix-ui/react-slot": "^1.5.0", + "@radix-ui/react-tooltip": "^1.4.1", + "@tanstack/react-query": "^5.108.4", "@tanstack/react-table": "^8.21.3", - "@tanstack/react-virtual": "^3.13.18", + "@tanstack/react-virtual": "^3.14.30", "bun-plugin-tailwind": "^0.1.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", - "date-fns": "^4.1.0", - "jsonata": "^2.1.0", + "date-fns": "^4.4.0", "lucide-react": "^0.555.0", - "motion": "^12.23.24", - "nanoid": "^5.1.6", - "nuqs": "^2.8.0", - "radix-ui": "^1.4.3", - "react": "^19", - "react-day-picker": "^9.11.2", - "react-dom": "^19", - "react-resizable-panels": "^4.4.1", - "tailwind-merge": "^3.4.0", + "motion": "^12.43.0", + "nanoid": "^5.1.16", + "nuqs": "^2.10.3", + "react": "^19.3.1", + "react-day-picker": "^9.14.0", + "react-dom": "^19.3.1", + "react-resizable-panels": "^4.27.0", + "tailwind-merge": "^3.7.1", "usehooks-ts": "^3.1.1", - "zod": "^4.5.0" + "zod": "^4.6.7" }, "devDependencies": { "@types/bun": "latest", - "@types/react": "^19", - "@types/react-dom": "^19", - "elysia": "^1.4.16", - "tailwindcss": "^4.1.11", + "@types/react": "^19.3.3", + "@types/react-dom": "^19.3.0", + "tailwindcss": "^4.3.5", "tw-animate-css": "^1.4.0", "typescript": "^7" } diff --git a/packages/duron/README.md b/packages/duron/README.md index 256f087..c5ae57c 100644 --- a/packages/duron/README.md +++ b/packages/duron/README.md @@ -18,7 +18,7 @@ pnpm add duron postgres drizzle-orm@rc yarn add duron postgres drizzle-orm@rc ``` -Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.1.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. ## Quick Start diff --git a/packages/duron/package.json b/packages/duron/package.json index 27ecd7a..1ae0b39 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -81,28 +81,40 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@opentelemetry/api": "^1.9.0", - "@opentelemetry/resources": "^2.4.0", - "@opentelemetry/sdk-trace-base": "^2.4.0", - "@opentelemetry/sdk-trace-node": "^2.4.0", - "@opentelemetry/semantic-conventions": "^1.39.0", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/resources": "^2.12.1", + "@opentelemetry/sdk-trace-base": "^2.12.1", + "@opentelemetry/sdk-trace-node": "^2.12.1", + "@opentelemetry/semantic-conventions": "^1.45.0", "@standard-schema/spec": "^1.1.0", "@standard-schema/utils": "^0.3.0", - "elysia": "^1.4.22", - "fastq": "^1.19.1", - "jose": "^6.1.2", - "p-retry": "^7.1.0", - "pino": "^10.1.0", - "zod": "^4.5.0" + "elysia": "^1.4.32", + "fastq": "^1.20.3", + "jose": "^6.2.18", + "pino": "^10.4.0", + "zod": "^4.6.7" }, "devDependencies": { "@electric-sql/pglite": "^0.5.17", - "@opentelemetry/core": "^2.4.0", "@types/bun": "latest", - "@types/node": "^24.0.15", + "@types/node": "^24.19.4", "drizzle-kit": "1.0.0-rc.6", "drizzle-orm": "1.0.0-rc.6", - "postgres": "^4.1.1", + "p-retry": "^7.1.1", + "postgres": "^4.2.0", "typescript": "^7" + }, + "peerDependencies": { + "@electric-sql/pglite": "^0.5.17", + "drizzle-orm": "1.0.0-rc.6 || ^1.0.0", + "postgres": "^4.1.1" + }, + "peerDependenciesMeta": { + "@electric-sql/pglite": { + "optional": true + }, + "postgres": { + "optional": true + } } } diff --git a/packages/duron/test/prune-bootstrap.test.ts b/packages/duron/test/prune-bootstrap.test.ts index 127ec2e..e9ad981 100644 --- a/packages/duron/test/prune-bootstrap.test.ts +++ b/packages/duron/test/prune-bootstrap.test.ts @@ -1,13 +1,17 @@ import { expect, it } from 'bun:test' import pino from 'pino' -import postgres, { type Sql } from 'postgres' +import postgres, { type ReservedSql, type Sql } from 'postgres' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' import { getPostgresConnection } from './docker.js' import { PruneRelay } from './prune-relay.js' +// postgres 4.2 types reserve() as a cancellable Leasing. These stubs return a plain +// Promise, which is enough because PostgresPruneLock only awaits the reservation. +type ReserveStub = { reserve: () => Promise } + async function eventually(check: () => Promise, timeout = 7_000): Promise { const deadline = performance.now() + timeout for (;;) { @@ -52,7 +56,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { client.options.host[0] = '127.0.0.1' client.options.port[0] = relay.port const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { reserves++ const session = await reserve() reservedPid = (await session<{ pid: number }[]>`SELECT pg_backend_pid() AS pid`)[0]! @@ -300,7 +304,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { if (query.includes('pg_try_advisory_lock')) acquisitions++ } const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { reserves++ return reserve() } diff --git a/packages/duron/test/prune-ownership.test.ts b/packages/duron/test/prune-ownership.test.ts index ecb34f0..b89df5e 100644 --- a/packages/duron/test/prune-ownership.test.ts +++ b/packages/duron/test/prune-ownership.test.ts @@ -1,12 +1,16 @@ import { expect, it } from 'bun:test' import pino from 'pino' -import postgres, { type Sql } from 'postgres' +import postgres, { type ReservedSql, type Sql } from 'postgres' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' import { getPostgresConnection } from './docker.js' +// postgres 4.2 types reserve() as a cancellable Leasing. These stubs return a plain +// Promise, which is enough because PostgresPruneLock only awaits the reservation. +type ReserveStub = { reserve: () => Promise } + async function eventually(check: () => Promise, timeout = 7_000): Promise { const deadline = performance.now() + timeout for (;;) { @@ -140,7 +144,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { adapter.setId('failed-start-owned-lock') adapter.instrument = (client) => { const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { const session = await reserve() pid = (await session<{ pid: number }[]>`SELECT pg_backend_pid() AS pid`)[0]!.pid allocated.resolve() @@ -210,7 +214,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { adapter.setId('retained-session') adapter.instrument = (client) => { const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { reserves++ const session = await reserve() const release = session.release.bind(session) @@ -320,7 +324,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { adapter.setId(application) adapter.instrument = (client) => { const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { const session = await reserve() const release = session.release.bind(session) session.release = () => { @@ -387,7 +391,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { adapter.setId('uncertain-reserved-identity') adapter.instrument = (client) => { const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { reserveCalls++ const session = await reserve() const release = session.release.bind(session) @@ -464,7 +468,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { adapter.setId('shared-fault-close-deadline') adapter.instrument = (client) => { const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { const session = await reserve() const release = session.release.bind(session) session.release = () => { @@ -556,7 +560,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { closeCalls++ await end(options) } - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { const session = await reserve() const release = session.release.bind(session) // Native release is synchronous. This deliberately delays only its JS @@ -657,7 +661,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { adapter.setId('independent-return-close-errors') adapter.instrument = (client) => { const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { const session = await reserve() session.release = () => { returns++ @@ -739,7 +743,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { closeCalls++ await end(options) } - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { const session = await reserve() const release = session.release.bind(session) session.release = () => { diff --git a/packages/duron/test/prune-replies.test.ts b/packages/duron/test/prune-replies.test.ts index 7e6f641..8a18554 100644 --- a/packages/duron/test/prune-replies.test.ts +++ b/packages/duron/test/prune-replies.test.ts @@ -1,12 +1,16 @@ import { expect, it } from 'bun:test' import pino from 'pino' -import postgres, { type Sql } from 'postgres' +import postgres, { type ReservedSql, type Sql } from 'postgres' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' import { getPostgresConnection } from './docker.js' +// postgres 4.2 types reserve() as a cancellable Leasing. These stubs return a plain +// Promise, which is enough because PostgresPruneLock only awaits the reservation. +type ReserveStub = { reserve: () => Promise } + async function eventually(check: () => Promise): Promise { const deadline = performance.now() + 8_000 for (;;) { @@ -41,7 +45,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { installed = true const { client } = (this as unknown as { pruneLock: { client: Sql } }).pruneLock const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { const session = await reserve() const release = session.release.bind(session) session.release = () => { diff --git a/packages/duron/test/prune-transport.test.ts b/packages/duron/test/prune-transport.test.ts index 864eedb..df1b0d7 100644 --- a/packages/duron/test/prune-transport.test.ts +++ b/packages/duron/test/prune-transport.test.ts @@ -1,13 +1,17 @@ import { expect, it } from 'bun:test' import pino from 'pino' -import postgres, { type Sql } from 'postgres' +import postgres, { type ReservedSql, type Sql } from 'postgres' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' import { getPostgresConnection } from './docker.js' import { PruneRelay } from './prune-relay.js' +// postgres 4.2 types reserve() as a cancellable Leasing. These stubs return a plain +// Promise, which is enough because PostgresPruneLock only awaits the reservation. +type ReserveStub = { reserve: () => Promise } + async function eventually(check: () => Promise, timeout = 8_000): Promise { const deadline = performance.now() + timeout for (;;) { @@ -60,7 +64,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { relay.hold = () => true } const reserve = client.reserve.bind(client) - client.reserve = async () => { + ;(client as ReserveStub).reserve = async () => { reserves++ const session = await reserve() const release = session.release.bind(session) diff --git a/packages/examples/package.json b/packages/examples/package.json index 1f2248e..f2b8260 100644 --- a/packages/examples/package.json +++ b/packages/examples/package.json @@ -5,9 +5,6 @@ "basic": "bun --hot basic/start.ts", "multi-worker": "bun multi-worker/parent.ts" }, - "dependencies": { - "zod": "^4.1.12" - }, "devDependencies": { "@types/bun": "latest", "duron": "workspace:*", diff --git a/packages/shared-actions/package.json b/packages/shared-actions/package.json index 1858bf9..7b2c83a 100644 --- a/packages/shared-actions/package.json +++ b/packages/shared-actions/package.json @@ -2,13 +2,12 @@ "name": "shared-actions", "private": true, "dependencies": { - "@ai-sdk/openai": "^3.0.12", - "@opentelemetry/api": "^1.9.0", - "ai": "^6.0.42", - "zod": "^4.1.12" + "@ai-sdk/openai": "^3.0.147", + "@opentelemetry/api": "^1.10.0", + "ai": "^6.0.339", + "zod": "^4.6.7" }, "devDependencies": { - "@types/bun": "latest", "duron": "workspace:*" }, "peerDependencies": { From 003e149d58f5eda74edfc65f5e83b65a994f2b5f Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 09:10:08 -0300 Subject: [PATCH 036/100] fix(deps): keep @opentelemetry/api below 1.10, update multi-worker driver note - duron and shared-actions declare @opentelemetry/api ">=1.9.0 <1.10.0" and lock 1.9.1. OTel SDK 2.x peers api <1.10.0; with ^1.10.0, npm installs a second api copy and duron's context.with() no longer makes job/step spans active once the app registers the SDK. - multi-worker.mdx: tested with postgres.js 4.2.0, supports 4.1.1 or later; the 3.4.9 failure reproductions were checked on 4.1.1. --- bun.lock | 18 +++--------------- packages/docs/content/docs/multi-worker.mdx | 4 ++-- packages/duron/package.json | 2 +- packages/shared-actions/package.json | 2 +- 4 files changed, 7 insertions(+), 19 deletions(-) diff --git a/bun.lock b/bun.lock index 12cf445..0401e9f 100644 --- a/bun.lock +++ b/bun.lock @@ -45,7 +45,7 @@ "name": "duron", "version": "0.5.0-beta.0", "dependencies": { - "@opentelemetry/api": "^1.10.0", + "@opentelemetry/api": ">=1.9.0 <1.10.0", "@opentelemetry/resources": "^2.12.1", "@opentelemetry/sdk-trace-base": "^2.12.1", "@opentelemetry/sdk-trace-node": "^2.12.1", @@ -146,7 +146,7 @@ "name": "shared-actions", "dependencies": { "@ai-sdk/openai": "^3.0.147", - "@opentelemetry/api": "^1.10.0", + "@opentelemetry/api": ">=1.9.0 <1.10.0", "ai": "^6.0.339", "zod": "^4.6.7", }, @@ -313,7 +313,7 @@ "@oozcitak/util": ["@oozcitak/util@10.0.0", "", {}, "sha512-hAX0pT/73190NLqBPPWSdBVGtbY6VOhWYK3qqHqtXQ1gK7kS2yz4+ivsN07hpJ6I3aeMtKP6J6npsEKOAzuTLA=="], - "@opentelemetry/api": ["@opentelemetry/api@1.10.0", "", {}, "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ=="], + "@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], "@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@2.12.1", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-1+zgZyD7QvBr0/K6+FVx5UAzdGo0shnQf8pbWUFFbj43qZPIKTtfK4xX4J3bS7AmkifiZzAEMdk8dztiEfkgmg=="], @@ -1489,18 +1489,6 @@ "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], - "@opentelemetry/context-async-hooks/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - - "@opentelemetry/core/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - - "@opentelemetry/resources/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - - "@opentelemetry/sdk-trace/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - - "@opentelemetry/sdk-trace-base/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - - "@opentelemetry/sdk-trace-node/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], - "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 5fb42c3..8e2c613 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -232,11 +232,11 @@ Limits of this protection: - SQL `now()` in a claim is the claim transaction's start time, not the claim statement's. It determines which latest jobs supply limits, which active jobs count, and the claimed jobs' `startedAt` and `expiresAt`. - The limit governs admission under the existing latest-job and expiry rules. It is not a lease or fence on running work; expiry, recovery and limit changes keep their existing behavior. - If a claim's commit reply is lost, the outcome is uncertain. Duron does not run or replay that claim; existing liveness and recovery handle a job that was committed. -- Driver version: Duron is tested with postgres.js 4.1.1. Two driver failures reproduced with postgres.js 3.4.9 do not occur with 4.1.1 for the reproduced triggers. Applications that pin postgres.js 3.x keep both: +- Driver version: Duron is tested with postgres.js 4.2.0 and supports 4.1.1 or later. Two driver failures reproduced with postgres.js 3.4.9 do not occur with 4.1.1 for the reproduced triggers; those reproductions were not repeated on 4.2.0, where the native test suite passes. Applications that pin postgres.js 3.x keep both: - If the database connection closes while any built-in transaction is open, including a claim, the driver can throw an uncaught exception from its own rollback attempt and keep that pooled connection unusable until the adapter closes. Under Node.js's default handling, an uncaught exception terminates the process. The uncommitted claim is not returned. - After `stop()`, work still waiting for a pooled connection can open a new connection that the stopped adapter does not close. That idle session stays open until the driver's `max_lifetime` closes it (a random 30 to 60 minutes by default) or the process exits. - With 4.1.1, work queued while the adapter closes after a lost connection has not been verified. + With 4.1.1 and 4.2.0, work queued while the adapter closes after a lost connection has not been verified. - PGLite is a single-engine test backend; it runs claims one at a time and is not evidence of multi-process isolation. diff --git a/packages/duron/package.json b/packages/duron/package.json index 1ae0b39..00557f3 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -81,7 +81,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { - "@opentelemetry/api": "^1.10.0", + "@opentelemetry/api": ">=1.9.0 <1.10.0", "@opentelemetry/resources": "^2.12.1", "@opentelemetry/sdk-trace-base": "^2.12.1", "@opentelemetry/sdk-trace-node": "^2.12.1", diff --git a/packages/shared-actions/package.json b/packages/shared-actions/package.json index 7b2c83a..fb2cf9f 100644 --- a/packages/shared-actions/package.json +++ b/packages/shared-actions/package.json @@ -3,7 +3,7 @@ "private": true, "dependencies": { "@ai-sdk/openai": "^3.0.147", - "@opentelemetry/api": "^1.10.0", + "@opentelemetry/api": ">=1.9.0 <1.10.0", "ai": "^6.0.339", "zod": "^4.6.7" }, From ea8dc9ee9d4abdf6e56d199a885d2106f4b3b042 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 09:30:35 -0300 Subject: [PATCH 037/100] chore(fmt): upgrade oxfmt to 0.80, rename experimentalSortImports to sortImports oxfmt 0.80's configuration schema only documents sortImports. The old key is still accepted as an alias (verified: same import order with either key). --- .oxfmtrc.json | 2 +- bun.lock | 44 ++++++++++++++++++++++---------------------- package.json | 2 +- 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/.oxfmtrc.json b/.oxfmtrc.json index cd233a6..85d8408 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -10,7 +10,7 @@ "arrowParens": "always", "endOfLine": "lf", "ignorePatterns": ["dist", "build", "node_modules", ".wrangler", "**/drizzle", "**/*.gen.ts"], - "experimentalSortImports": { + "sortImports": { "order": "asc", "groups": [ ["side_effect"], diff --git a/bun.lock b/bun.lock index 0401e9f..badb4fb 100644 --- a/bun.lock +++ b/bun.lock @@ -5,7 +5,7 @@ "": { "name": "duron-workspace", "devDependencies": { - "oxfmt": "^0.59.0", + "oxfmt": "^0.80.0", "oxlint": "^1.95.0", "typescript": "^7.0.2", }, @@ -355,43 +355,43 @@ "@oven/bun-windows-x64": ["@oven/bun-windows-x64@1.4.5", "", { "os": "win32", "cpu": "x64" }, "sha512-FNvply651vcE/GHgNWz6mZvhmkwBuu8Hw54oNzA+CQog+HW+542rXQmZqNHRkFxazD9L3xi+iTtvO3engAgJfw=="], - "@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.59.0", "", { "os": "android", "cpu": "arm" }, "sha512-bNTnfbuG7sAwb2PakMNaDukx5kXeW9duXOBeWtTOiLz3fXz3q2DlWguufPZ+c2IHEVrRXHD+M4aUgEWm841LDA=="], + "@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.80.0", "", { "os": "android", "cpu": "arm" }, "sha512-IKgbKL684l/0zb1yAIr7YkqmUsZmO6O02ELkb+78SLFsDJAJxCtPtLypHGUGNpeOrsdIHXIZMxYGo/9QYSHuhg=="], - "@oxfmt/binding-android-arm64": ["@oxfmt/binding-android-arm64@0.59.0", "", { "os": "android", "cpu": "arm64" }, "sha512-R/Sn7z52QtdAKNqQLLY0EK7hVMjXiz3XUlvoCFCm/60jgIzAnQtiqLKBCFaBkimCQL5rs2ezPMcicpjCsrl54Q=="], + "@oxfmt/binding-android-arm64": ["@oxfmt/binding-android-arm64@0.80.0", "", { "os": "android", "cpu": "arm64" }, "sha512-fGqMAgBeKlE1CsnpKNuIlahJmJgYxLrOiwacsYdqK0fv8hu7flDAQN0MTa5joCoc0gfLV/RJKAKp0b6FsODGYQ=="], - "@oxfmt/binding-darwin-arm64": ["@oxfmt/binding-darwin-arm64@0.59.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-vm/ynUqE4HjC0ZIEjmXv1UJu1/GngccQ+T+TJudTMxUxm6r+GQTg1TO3E5jJfI71pBaXxSzs1+vWHIwuilGHhw=="], + "@oxfmt/binding-darwin-arm64": ["@oxfmt/binding-darwin-arm64@0.80.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-6EyFZdBrB+86OK/C4CqqqRwRPnp/sLxzFf1vWg8Ghd369zAyNLkxAu9JMXnzkXoW491j7X7cRNs/ayuFs7hMwg=="], - "@oxfmt/binding-darwin-x64": ["@oxfmt/binding-darwin-x64@0.59.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-uTtYDpLN/obfKVWGpgEc8BqYlLZBQTPz2uYEvLRy3HPZxjZ34wiFzukUBU2bf64JuCYZI//GTV1EOMmWlPjf/w=="], + "@oxfmt/binding-darwin-x64": ["@oxfmt/binding-darwin-x64@0.80.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-ZZEKe4O/3qrRTYcMWVBpfBN3+ANDwwEGt5FijDw4Q31zqXDj8WXfnytWsTGu0sh3nJ7tLbIzypY+oYRCfb9ffg=="], - "@oxfmt/binding-freebsd-x64": ["@oxfmt/binding-freebsd-x64@0.59.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-e2UnxL/ifStSPy8ffBCDbdy595SYsGy+U1pur4G65TuMmWxAMBzYGG7atZo/3mp515p8rZdsflxVD/E1FAdPLQ=="], + "@oxfmt/binding-freebsd-x64": ["@oxfmt/binding-freebsd-x64@0.80.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-yBTHy84SOBhag+A/KRMp0vctB0t5Vn6PjlVHfYWpqzWhWgvgktzdFplTSSV8Lu9oXY4Xr8EU+01N88J1S2tNCg=="], - "@oxfmt/binding-linux-arm-gnueabihf": ["@oxfmt/binding-linux-arm-gnueabihf@0.59.0", "", { "os": "linux", "cpu": "arm" }, "sha512-LtdeZ1l0urxte3VNi3g8cocZwv1xGM1NKHSgF/fJEEVhyQmlgGh7WFWKFd/pNuO7djfvPNtNO1+MS+FEWkgVSA=="], + "@oxfmt/binding-linux-arm-gnueabihf": ["@oxfmt/binding-linux-arm-gnueabihf@0.80.0", "", { "os": "linux", "cpu": "arm" }, "sha512-HwSZYzbNF04nwduBcn0KZZ2kwnCuzEf8hCfsZ4bkRbDIzjIjhTsI6O3l+0sIKpU2F718szvkEfVPMkIksZ/NYQ=="], - "@oxfmt/binding-linux-arm-musleabihf": ["@oxfmt/binding-linux-arm-musleabihf@0.59.0", "", { "os": "linux", "cpu": "arm" }, "sha512-dBTciSsj9GTMl7p+h2gMSI0hoPn2ijfc/dUsbnWsP0RbwgPl2r0C/5zkMb3Pb+gGj17LH7f1o4qLo9aes/pAvA=="], + "@oxfmt/binding-linux-arm-musleabihf": ["@oxfmt/binding-linux-arm-musleabihf@0.80.0", "", { "os": "linux", "cpu": "arm" }, "sha512-rVPpw9dRTiBLgxdfySNhKihMTPy1SPb1+y+EDrVK0aUj/k8pm51zTANKfFr9bMgVxcDuGO227QwzZRhT0WQcHQ=="], - "@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/binding-linux-arm64-gnu@0.59.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-tXVdJ/JINsNWdponPHN0OuKHtC+HdpyoS9sd6IDPNiiEYsRki8b7tefRZ1iMnRkdbyT4SEbguWsr6o+5awvbPQ=="], + "@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/binding-linux-arm64-gnu@0.80.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-1yZ3eWD9X2TcwpMt/SaQjlclyZqVVmBNh+62svgGBRZJIzWz4EIBq0ZMj5Unn20gzm3y9OLEnWdmJ4b9/izmLw=="], - "@oxfmt/binding-linux-arm64-musl": ["@oxfmt/binding-linux-arm64-musl@0.59.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-RRTq38i2zT5fnw6XGHjvT6w2mh6x/G3m6AZcAZ56OTDTT/lsOeYnG3SVjwmH40z5kPqF+lf+o35e6m6PpKy9Dw=="], + "@oxfmt/binding-linux-arm64-musl": ["@oxfmt/binding-linux-arm64-musl@0.80.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-FTCv1p32lqfXNmicCXvluPACYrqqMChrI4bVJWh8UrvwlaxO9YkF3toLu6MaESav0e3X/GA7BkK2c7wyok7qyQ=="], - "@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/binding-linux-ppc64-gnu@0.59.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-lD3k7glAJSaXW0D6xzu8VOZbYbosvy+0ktOVkfLEoQF5HJlMSxTQ2KNW0JO+08ccP/1ElOKktVEMI0fqRbVB4w=="], + "@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/binding-linux-ppc64-gnu@0.80.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-jl0ivd2WpjlWbe/sgcvW3E4CbJyxVXNBc9vVTSv1mNN28phPXczG97nXxWhdQu+oAikpXtyf5VAP41P4OT+48A=="], - "@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/binding-linux-riscv64-gnu@0.59.0", "", { "os": "linux", "cpu": "none" }, "sha512-WH5ZP1RbuHKBO/yfPRQKpNO/ijHcEDNbnmC4VPf/Bcd3+mbMAZpRiJWRa1PL5bREdIZZHo343mk3sqlc9x7Usw=="], + "@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/binding-linux-riscv64-gnu@0.80.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-Iu6q6EsvYtGag7pxQl9HV/k+lEv9SbatZb4fyrWYwIFeAivAl9NNh7o4kizpzsfDOIFKWSmEPkbhzKrucSdQZg=="], - "@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/binding-linux-riscv64-musl@0.59.0", "", { "os": "linux", "cpu": "none" }, "sha512-743wOiaI9RZY4QVGkWkfGRavD5ZJUJ6gscFjVrVu1dP8AZh9jM+a6v3NhlR+OIzHdS6DhLM96w+gcVskskz7rw=="], + "@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/binding-linux-riscv64-musl@0.80.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-e6QIq9l1yHQuNp1u8+veTkQGOHBeayekax5ZfWoi2gwBGJoFVaq9Klovdt8wg/I8R+3eHQVB7yzhXekfMXozQw=="], - "@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/binding-linux-s390x-gnu@0.59.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-xjRXQsRnrRZCcCkIEnbd2lmsQNobtwwkJxdy2bWXhZ1lIN0ouZwsBXRsoovW3yATuziAYwr9HMiQuR/Cc75NIw=="], + "@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/binding-linux-s390x-gnu@0.80.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-Fqs2/RNU3MaHvGvLinaRIhZbXJV6MwloGnyK0COfHbF4oTmfgfmdXzrMgk/04DD+0RfdZvdF/82DoaWbYWgfqA=="], - "@oxfmt/binding-linux-x64-gnu": ["@oxfmt/binding-linux-x64-gnu@0.59.0", "", { "os": "linux", "cpu": "x64" }, "sha512-4hNjqq/Rbr9B+StY9zMMAfm72+mtM4v80xYL5Qkb59Qd72g2vJMI0iFlPj3kf6miMsie/yJ7rt4urJT292HBgA=="], + "@oxfmt/binding-linux-x64-gnu": ["@oxfmt/binding-linux-x64-gnu@0.80.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-5ZZBWDHwGYsqprHma9UwFXNJfkTo4IXu/obbxhz8y/qsQfl/k00HQsXZYBnIlytEWjE1tZZmSimjIObqj8Jyog=="], - "@oxfmt/binding-linux-x64-musl": ["@oxfmt/binding-linux-x64-musl@0.59.0", "", { "os": "linux", "cpu": "x64" }, "sha512-NH579iN8EVQYsWowUB8B5vFchcylJtwPVJ7NmUAqEQHNLfhPbDT3K56KrECNAkUN4QpF4qiMgN2vsfZwVvjm7g=="], + "@oxfmt/binding-linux-x64-musl": ["@oxfmt/binding-linux-x64-musl@0.80.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-3hbDeK3hijv3zyoZm0kONLkqJbfd4nr0cfFL/veo1chgcnovp9lyiuFiFltCqFKs0qnuEz7qA99mee0Pcm+fXw=="], - "@oxfmt/binding-openharmony-arm64": ["@oxfmt/binding-openharmony-arm64@0.59.0", "", { "os": "none", "cpu": "arm64" }, "sha512-mzZy3Z5Aj1D75Aq9FVlmoRQH5ei8Ga4o/NZmlXkKyeZ5EmPrUXRR7c6BMBteV1ZuZ/356UYDuLRLjAMxTDTiBA=="], + "@oxfmt/binding-openharmony-arm64": ["@oxfmt/binding-openharmony-arm64@0.80.0", "", { "os": "none", "cpu": "arm64" }, "sha512-5ThMiM6QKqfWaOxtzq+HaYyrWe48MGg49pDc9ll5KFvPEPo2Hqagz0JSk6hhZ3vOF/7tIhGIGu3mVnVuulwMQA=="], - "@oxfmt/binding-win32-arm64-msvc": ["@oxfmt/binding-win32-arm64-msvc@0.59.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-0CpDJ1gE3jN1Gk6xms1Ie6LPfPcOtY4FAtoOmVLHQoAf8DvO2wd0DW2dIX2f7YTp5dxrr0ND8JeUEjm3DP3k5g=="], + "@oxfmt/binding-win32-arm64-msvc": ["@oxfmt/binding-win32-arm64-msvc@0.80.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-YEPyJo02Wc9fzHBqp8OofJVmb9i92PtYTfpUJ5oXmCOGjfiDoqVlIh7vGVts91LnKL8UZ3cyXuM3tuqPKoZ40g=="], - "@oxfmt/binding-win32-ia32-msvc": ["@oxfmt/binding-win32-ia32-msvc@0.59.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-zwdKBu3pt87uW0bRcywZb0oGMS7C6n87qogwRYFUgmk44T90ZzYlPjtlFYXs/DnBFrgNCvlHwCuWKfVWLeE7kw=="], + "@oxfmt/binding-win32-ia32-msvc": ["@oxfmt/binding-win32-ia32-msvc@0.80.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-vimQJkghBVQO/+YEe6ybFaqUd2oMl2srd/jJFGgVlpdSOIWmOVIsBv9dn9SyjzSFXJnhDrBCtU0pnTutjNWnSg=="], - "@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.59.0", "", { "os": "win32", "cpu": "x64" }, "sha512-dUUbZkKgWrmAeI/puzv4bxN8lzcYaFnQVwFTFtwO2Gp8M7lZGSE2qJjC58g518+1bltJ8mizjYwD0BGHym0l/w=="], + "@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.80.0", "", { "os": "win32", "cpu": "x64" }, "sha512-kfJaMYppxdcTfZe+4Ify0uAVCgwEMFg/yp9WDnZ2Vh4KFd09dN5dgsomYDWN0UhzSTb9/OqDY3S7IczL+XOmaA=="], "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.95.0", "", { "os": "android", "cpu": "arm" }, "sha512-hJna6w3COWJjfMPxomjZL82klTdrITm56PEpCsfO/xMkzQw/fNtJWauQ/YEwQqVttj0L5vDIa8rCcuhfAE3L4w=="], @@ -1233,7 +1233,7 @@ "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], - "oxfmt": ["oxfmt@0.59.0", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.59.0", "@oxfmt/binding-android-arm64": "0.59.0", "@oxfmt/binding-darwin-arm64": "0.59.0", "@oxfmt/binding-darwin-x64": "0.59.0", "@oxfmt/binding-freebsd-x64": "0.59.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.59.0", "@oxfmt/binding-linux-arm-musleabihf": "0.59.0", "@oxfmt/binding-linux-arm64-gnu": "0.59.0", "@oxfmt/binding-linux-arm64-musl": "0.59.0", "@oxfmt/binding-linux-ppc64-gnu": "0.59.0", "@oxfmt/binding-linux-riscv64-gnu": "0.59.0", "@oxfmt/binding-linux-riscv64-musl": "0.59.0", "@oxfmt/binding-linux-s390x-gnu": "0.59.0", "@oxfmt/binding-linux-x64-gnu": "0.59.0", "@oxfmt/binding-linux-x64-musl": "0.59.0", "@oxfmt/binding-openharmony-arm64": "0.59.0", "@oxfmt/binding-win32-arm64-msvc": "0.59.0", "@oxfmt/binding-win32-ia32-msvc": "0.59.0", "@oxfmt/binding-win32-x64-msvc": "0.59.0" }, "peerDependencies": { "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-Xqk6cPZS1yMvVa7OAuenaDZUsgMDutvvbZ9/L5gSvAfW64+WN4HVhgipLj5rVERbYQt8fLs9TopyZ1rU1XEG/w=="], + "oxfmt": ["oxfmt@0.80.0", "", { "dependencies": { "tinypool": "2.2.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.80.0", "@oxfmt/binding-android-arm64": "0.80.0", "@oxfmt/binding-darwin-arm64": "0.80.0", "@oxfmt/binding-darwin-x64": "0.80.0", "@oxfmt/binding-freebsd-x64": "0.80.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.80.0", "@oxfmt/binding-linux-arm-musleabihf": "0.80.0", "@oxfmt/binding-linux-arm64-gnu": "0.80.0", "@oxfmt/binding-linux-arm64-musl": "0.80.0", "@oxfmt/binding-linux-ppc64-gnu": "0.80.0", "@oxfmt/binding-linux-riscv64-gnu": "0.80.0", "@oxfmt/binding-linux-riscv64-musl": "0.80.0", "@oxfmt/binding-linux-s390x-gnu": "0.80.0", "@oxfmt/binding-linux-x64-gnu": "0.80.0", "@oxfmt/binding-linux-x64-musl": "0.80.0", "@oxfmt/binding-openharmony-arm64": "0.80.0", "@oxfmt/binding-win32-arm64-msvc": "0.80.0", "@oxfmt/binding-win32-ia32-msvc": "0.80.0", "@oxfmt/binding-win32-x64-msvc": "0.80.0" }, "peerDependencies": { "@astrojs/compiler-rs": "^0.5.0", "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["@astrojs/compiler-rs", "svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-jy8/kYEomtC6g1LqXDl1LEXk5Ih+c7a1jB5wxqEp8qBmDoOD7Ei+XCxU2jGEjGUdBfoPef6rDiSENVLJ5gWq+Q=="], "oxlint": ["oxlint@1.95.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.95.0", "@oxlint/binding-android-arm64": "1.95.0", "@oxlint/binding-darwin-arm64": "1.95.0", "@oxlint/binding-darwin-x64": "1.95.0", "@oxlint/binding-freebsd-x64": "1.95.0", "@oxlint/binding-linux-arm-gnueabihf": "1.95.0", "@oxlint/binding-linux-arm-musleabihf": "1.95.0", "@oxlint/binding-linux-arm64-gnu": "1.95.0", "@oxlint/binding-linux-arm64-musl": "1.95.0", "@oxlint/binding-linux-ppc64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-musl": "1.95.0", "@oxlint/binding-linux-s390x-gnu": "1.95.0", "@oxlint/binding-linux-x64-gnu": "1.95.0", "@oxlint/binding-linux-x64-musl": "1.95.0", "@oxlint/binding-openharmony-arm64": "1.95.0", "@oxlint/binding-win32-arm64-msvc": "1.95.0", "@oxlint/binding-win32-ia32-msvc": "1.95.0", "@oxlint/binding-win32-x64-msvc": "1.95.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2008", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-eNzjFjm1TU02/+ohAJjOB7aekRQgTXhOWxMGscEm8VJMokNnnix+PCZn7kqIuGIqxAoBnHxatqlN3Chz3N6PKA=="], @@ -1403,7 +1403,7 @@ "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], - "tinypool": ["tinypool@2.1.0", "", {}, "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw=="], + "tinypool": ["tinypool@2.2.0", "", {}, "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ=="], "token-types": ["token-types@6.2.0", "", { "dependencies": { "@borewit/text-codec": "^0.2.3", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-s9euYHM//T3loJtbNUYdbAzsMlvKBeRS+XCLFy+UGosMQH19Hwjap5k19i4PPAEJJBsVIpMpVTxl4fIqCuNfUg=="], diff --git a/package.json b/package.json index a51ac66..d62f4c4 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ }, "dependencies": {}, "devDependencies": { - "oxfmt": "^0.59.0", + "oxfmt": "^0.80.0", "oxlint": "^1.95.0", "typescript": "^7.0.2" } From a5d83008a245edaac469deecd3b0a0ed0c657846 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 09:30:41 -0300 Subject: [PATCH 038/100] style: reformat with oxfmt 0.80 Formatting only, generated by `bun run fmt`. Sort-imports now breaks ties for one source by subgroup (value import before type import). Markdown and TS layout changes come from the newer formatter. --- README.md | 2 +- packages/duron-dashboard/README.md | 11 ++-- .../src/hooks/use-jobs-polling.ts | 2 +- .../src/hooks/use-steps-polling.ts | 2 +- packages/duron-dashboard/src/init.tsx | 2 +- .../duron-dashboard/src/views/jobs-table.tsx | 2 +- packages/duron/src/adapters/adapter.ts | 58 +++++++++---------- packages/duron/src/lifecycle.ts | 7 ++- 8 files changed, 44 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index b884745..21c9c32 100644 --- a/README.md +++ b/README.md @@ -149,8 +149,8 @@ const jobId = await client.runAction('sendEmail', { The server includes authentication and can serve the dashboard as standalone HTML: ```typescript -import { createServer } from 'duron/server' import { getHTML } from 'duron-dashboard/get-html' +import { createServer } from 'duron/server' import { Elysia } from 'elysia' // Define variables (same type used in defineAction) diff --git a/packages/duron-dashboard/README.md b/packages/duron-dashboard/README.md index 5dda746..f191af4 100644 --- a/packages/duron-dashboard/README.md +++ b/packages/duron-dashboard/README.md @@ -25,9 +25,10 @@ yarn add duron-dashboard Import and use the `DuronDashboard` component in your React application: ```tsx -import { DuronDashboard } from 'duron-dashboard' import 'duron-dashboard/index.css' +import { DuronDashboard } from 'duron-dashboard' + function App() { return } @@ -42,8 +43,8 @@ Use the `getHTML` function to render a fully inlined HTML application. This is u #### Elysia ```ts -import { Elysia } from 'elysia' import { getHTML } from 'duron-dashboard/get-html' +import { Elysia } from 'elysia' const app = new Elysia() @@ -60,8 +61,8 @@ app.listen(3000) #### Hono ```ts -import { Hono } from 'hono' import { getHTML } from 'duron-dashboard/get-html' +import { Hono } from 'hono' const app = new Hono() @@ -74,8 +75,8 @@ app.get('/dashboard', async (c) => { #### Express ```ts -import express from 'express' import { getHTML } from 'duron-dashboard/get-html' +import express from 'express' const app = express() @@ -88,8 +89,8 @@ app.get('/dashboard', async (req, res) => { #### Fastify ```ts -import Fastify from 'fastify' import { getHTML } from 'duron-dashboard/get-html' +import Fastify from 'fastify' const app = Fastify() diff --git a/packages/duron-dashboard/src/hooks/use-jobs-polling.ts b/packages/duron-dashboard/src/hooks/use-jobs-polling.ts index 0d4dd4b..8a0c2a0 100644 --- a/packages/duron-dashboard/src/hooks/use-jobs-polling.ts +++ b/packages/duron-dashboard/src/hooks/use-jobs-polling.ts @@ -2,8 +2,8 @@ import { useQueryClient } from '@tanstack/react-query' import { useEffect, useRef, useState } from 'react' import { usePollingInterval } from '@/contexts/polling-context' -import type { GetJobsResponse } from '@/lib/api' import { useApiRequest } from '@/lib/api' +import type { GetJobsResponse } from '@/lib/api' /** * Hook to poll for job updates and trigger refetch when updates are detected. diff --git a/packages/duron-dashboard/src/hooks/use-steps-polling.ts b/packages/duron-dashboard/src/hooks/use-steps-polling.ts index f0198e6..764c71b 100644 --- a/packages/duron-dashboard/src/hooks/use-steps-polling.ts +++ b/packages/duron-dashboard/src/hooks/use-steps-polling.ts @@ -2,8 +2,8 @@ import { useQueryClient } from '@tanstack/react-query' import { useEffect, useRef, useState } from 'react' import { usePollingInterval } from '@/contexts/polling-context' -import type { GetJobStepsResponse } from '@/lib/api' import { useApiRequest } from '@/lib/api' +import type { GetJobStepsResponse } from '@/lib/api' /** * Hook to poll for step updates for a specific job and trigger refetch when updates are detected. diff --git a/packages/duron-dashboard/src/init.tsx b/packages/duron-dashboard/src/init.tsx index 1ce775a..6d315b6 100644 --- a/packages/duron-dashboard/src/init.tsx +++ b/packages/duron-dashboard/src/init.tsx @@ -3,8 +3,8 @@ import './index.css' import { StrictMode } from 'react' import { createRoot, type Root } from 'react-dom/client' -import type { DuronDashboardProps } from './DuronDashboard' import { DuronDashboard } from './DuronDashboard' +import type { DuronDashboardProps } from './DuronDashboard' export interface InitDuronOptions extends DuronDashboardProps {} diff --git a/packages/duron-dashboard/src/views/jobs-table.tsx b/packages/duron-dashboard/src/views/jobs-table.tsx index d17ba78..4866d10 100644 --- a/packages/duron-dashboard/src/views/jobs-table.tsx +++ b/packages/duron-dashboard/src/views/jobs-table.tsx @@ -13,8 +13,8 @@ import { useLayout } from '@/contexts/layout-context' import { useDataTable } from '@/hooks/use-data-table' import { useJobParams } from '@/hooks/use-job-params' import { useJobsPolling } from '@/hooks/use-jobs-polling' -import type { ActionStats, Job, JobStatus } from '@/lib/api' import { useActions, useJobs } from '@/lib/api' +import type { ActionStats, Job, JobStatus } from '@/lib/api' import { formatExpirationWindow, formatMs } from '@/lib/duration' import { formatDate } from '@/lib/format' diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index 7805e6d..1d2941a 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -11,35 +11,6 @@ import { } from '../constants.js' import { lifecycleFor } from '../lifecycle.js' -import type { - ArchiveStats, - CancelJobOptions, - CancelJobStepOptions, - CompleteJobOptions, - CompleteJobStepOptions, - CreateJobOptions, - CreateOrRecoverJobStepOptions, - CreateOrRecoverJobStepResult, - DelayJobStepOptions, - DeleteJobOptions, - DeleteJobsOptions, - FailJobOptions, - FailJobStepOptions, - FetchOptions, - GetActionsResult, - GetJobStepsOptions, - GetJobStepsResult, - GetJobsOptions, - GetJobsResult, - Job, - JobStatusResult, - JobStep, - JobStepStatusResult, - PruneArchiveOptions, - RecoverJobsOptions, - RetryJobOptions, - TimeTravelJobOptions, -} from './schemas.js' import { ArchiveStatsSchema, BooleanResultSchema, @@ -73,6 +44,35 @@ import { RetryJobOptionsSchema, TimeTravelJobOptionsSchema, } from './schemas.js' +import type { + ArchiveStats, + CancelJobOptions, + CancelJobStepOptions, + CompleteJobOptions, + CompleteJobStepOptions, + CreateJobOptions, + CreateOrRecoverJobStepOptions, + CreateOrRecoverJobStepResult, + DelayJobStepOptions, + DeleteJobOptions, + DeleteJobsOptions, + FailJobOptions, + FailJobStepOptions, + FetchOptions, + GetActionsResult, + GetJobStepsOptions, + GetJobStepsResult, + GetJobsOptions, + GetJobsResult, + Job, + JobStatusResult, + JobStep, + JobStepStatusResult, + PruneArchiveOptions, + RecoverJobsOptions, + RetryJobOptions, + TimeTravelJobOptions, +} from './schemas.js' // Re-export types from schemas for backward compatibility export type { diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index 1be5806..8dc4b8e 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -329,9 +329,10 @@ export class Lifecycle { this.#drained = await this.#settlePhase('admitted-work drain', this.#work, failures) this.#ordinaryOpen = false failures.push( - ...this.#quiesceFailures.map( - (error): LifecycleFailure => ({ error, phase: 'admitted-work drain' }), - ), + ...this.#quiesceFailures.map((error): LifecycleFailure => ({ + error, + phase: 'admitted-work drain', + })), ) for (const phase of ['database cleanup', 'owned close'] as const) { const obligations = [...this.#obligations].filter( From e61db6e77d922b49e2d68688bd640a6a635a21cd Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 09:31:35 -0300 Subject: [PATCH 039/100] chore(ts): TypeScript 7 in docs and shared-actions, @types/node 26 - docs devDependency typescript ^5.9.3 -> ^7.0.2; shared-actions peer ^5 -> ^7, matching root, duron, dashboard and examples. - @types/node ^24 -> ^26.6.11 in docs and duron. - TS 7 removed baseUrl: drop it from the docs and shared-actions tsconfigs. All paths entries are now relative (fumadocs-mdx:collections -> ./.source/*). No import resolved through baseUrl. --- bun.lock | 16 ++++++++-------- packages/docs/package.json | 4 ++-- packages/docs/tsconfig.json | 3 +-- packages/duron/package.json | 2 +- packages/shared-actions/package.json | 2 +- packages/shared-actions/tsconfig.json | 1 - 6 files changed, 13 insertions(+), 15 deletions(-) diff --git a/bun.lock b/bun.lock index badb4fb..8e172d1 100644 --- a/bun.lock +++ b/bun.lock @@ -31,13 +31,13 @@ "devDependencies": { "@tailwindcss/vite": "^4.3.5", "@types/mdx": "^2.0.14", - "@types/node": "^24.19.4", + "@types/node": "^26.6.11", "@types/react": "^19.3.3", "@types/react-dom": "^19.3.0", "@vitejs/plugin-react": "^5.2.0", "serve": "^14.2.8", "tailwindcss": "^4.3.5", - "typescript": "^5.9.3", + "typescript": "^7.0.2", "vite-tsconfig-paths": "^5.1.4", }, }, @@ -61,7 +61,7 @@ "devDependencies": { "@electric-sql/pglite": "^0.5.17", "@types/bun": "latest", - "@types/node": "^24.19.4", + "@types/node": "^26.6.11", "drizzle-kit": "1.0.0-rc.6", "drizzle-orm": "1.0.0-rc.6", "p-retry": "^7.1.1", @@ -154,7 +154,7 @@ "duron": "workspace:*", }, "peerDependencies": { - "typescript": "^5", + "typescript": "^7", }, }, }, @@ -705,7 +705,7 @@ "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], - "@types/node": ["@types/node@24.19.4", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-s04odlR3ksJrLu7QLi+pddkWLD0RmSbcP9KuWn2/ozQKAp/YgwBC/6x9kJj8yAzZnGPfxePm7zm7nysVPCRagw=="], + "@types/node": ["@types/node@26.6.11", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ=="], "@types/react": ["@types/react@19.3.3", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-K8uWpJc4teiuOPdiP1umjeA9rGMgVPiXuoL66fcS1QlwBT1WMqY8PORmub9FadopIs+RCW6siYEs7Lpq+vDlog=="], @@ -1427,7 +1427,7 @@ "undici": ["undici@6.29.1", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="], - "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], + "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], "unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="], @@ -1509,14 +1509,14 @@ "ansi-align/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + "bun-types/undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], + "chalk-template/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], "compression/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], "compression/negotiator": ["negotiator@0.6.4", "", {}, "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w=="], - "docs/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], - "fumadocs-ui/fumadocs-core": ["fumadocs-core@16.1.0", "", { "dependencies": { "@formatjs/intl-localematcher": "^0.6.2", "@orama/orama": "^3.1.16", "@shikijs/rehype": "^3.15.0", "@shikijs/transformers": "^3.15.0", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "hast-util-to-estree": "^3.1.3", "hast-util-to-jsx-runtime": "^2.3.6", "image-size": "^2.0.2", "negotiator": "^1.0.0", "npm-to-yarn": "^3.0.1", "path-to-regexp": "^8.3.0", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-rehype": "^11.1.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^3.15.0", "unist-util-visit": "^5.0.0" }, "peerDependencies": { "@mixedbread/sdk": "^0.19.0", "@orama/core": "1.x.x", "@tanstack/react-router": "1.x.x", "@types/react": "*", "algoliasearch": "5.x.x", "lucide-react": "*", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "react-router": "7.x.x", "waku": "^0.26.0 || ^0.27.0" }, "optionalPeers": ["@mixedbread/sdk", "@orama/core", "@tanstack/react-router", "@types/react", "algoliasearch", "lucide-react", "next", "react", "react-dom", "react-router", "waku"] }, "sha512-5pbO2bOGc/xlb2yLQSy6Oag8mvD5CNf5HzQIG80HjZzLXYWEOHW8yovRKnWKRF9gAibn6WHnbssj3YPAlitV/A=="], "mime-types/mime-db": ["mime-db@1.33.0", "", {}, "sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ=="], diff --git a/packages/docs/package.json b/packages/docs/package.json index 087af53..5268f36 100644 --- a/packages/docs/package.json +++ b/packages/docs/package.json @@ -26,13 +26,13 @@ "devDependencies": { "@tailwindcss/vite": "^4.3.5", "@types/mdx": "^2.0.14", - "@types/node": "^24.19.4", + "@types/node": "^26.6.11", "@types/react": "^19.3.3", "@types/react-dom": "^19.3.0", "@vitejs/plugin-react": "^5.2.0", "serve": "^14.2.8", "tailwindcss": "^4.3.5", - "typescript": "^5.9.3", + "typescript": "^7.0.2", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/packages/docs/tsconfig.json b/packages/docs/tsconfig.json index 9671f82..54eb777 100644 --- a/packages/docs/tsconfig.json +++ b/packages/docs/tsconfig.json @@ -14,11 +14,10 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "@/*": ["./src/*"], "@assets/*": ["../assets/*"], - "fumadocs-mdx:collections/*": [".source/*"] + "fumadocs-mdx:collections/*": ["./.source/*"] }, "noEmit": true }, diff --git a/packages/duron/package.json b/packages/duron/package.json index 00557f3..84dbab6 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -97,7 +97,7 @@ "devDependencies": { "@electric-sql/pglite": "^0.5.17", "@types/bun": "latest", - "@types/node": "^24.19.4", + "@types/node": "^26.6.11", "drizzle-kit": "1.0.0-rc.6", "drizzle-orm": "1.0.0-rc.6", "p-retry": "^7.1.1", diff --git a/packages/shared-actions/package.json b/packages/shared-actions/package.json index fb2cf9f..65eafd2 100644 --- a/packages/shared-actions/package.json +++ b/packages/shared-actions/package.json @@ -11,6 +11,6 @@ "duron": "workspace:*" }, "peerDependencies": { - "typescript": "^5" + "typescript": "^7" } } diff --git a/packages/shared-actions/tsconfig.json b/packages/shared-actions/tsconfig.json index 82399f2..24dce00 100644 --- a/packages/shared-actions/tsconfig.json +++ b/packages/shared-actions/tsconfig.json @@ -26,7 +26,6 @@ "noUnusedParameters": false, "noPropertyAccessFromIndexSignature": false, "customConditions": ["dev-source"], - "baseUrl": ".", "paths": { "duron/*": ["../duron/src/*"] } From e69a400b0a37b96d5f4e4165a70de9f94c49b2ff Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 09:32:57 -0300 Subject: [PATCH 040/100] chore(ts): type check with bun check instead of tsc --noEmit - duron and duron-dashboard: "typecheck": "bun check --no-script" (the script name stays the same, so CI and AGENTS.md still run bun run typecheck). docs types:check: fumadocs-mdx && bun check --no-script. - --no-script makes bun check always run the checker. Without it, a future "check" script would run instead, and could recurse into typecheck. - tsc still emits duron's dist (build/dev). - Parity: on scratch copies with injected errors (TS2322, TS4111, TS2532, TS2554, TS2307, a JSX prop error, and an error in a file imported from another package), tsc 7.0.2 and bun check report identical lines. They also match on examples' existing error, and clean runs pass under both. The stable Bun 1.4.5 used by CI includes bun check. --- AGENTS.md | 4 ++-- packages/docs/package.json | 2 +- packages/duron-dashboard/package.json | 2 +- packages/duron/package.json | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2497977..1726455 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,7 @@ bun run dev:dashboard # dashboard dev server bun run dev:examples:basic # basic example # Verification (CI runs in this order) -bun run typecheck # tsc --noEmit across packages +bun run typecheck # bun check across packages (Bun's built-in type checker) bun run lint # oxlint check bun run lint:fix # oxlint fix bun run fmt:check # oxfmt check @@ -76,7 +76,7 @@ bun run build:docs # docs only ## Build Details -- `packages/duron`: `tsc --project tsconfig.node.json` +- `packages/duron`: `tsc --project tsconfig.node.json` (tsc only emits `dist`; type checking uses `bun check --no-script`) - `packages/duron-dashboard`: `NODE_ENV=production bun run build.ts && bun run build:get-html` - Docs: `vite build` diff --git a/packages/docs/package.json b/packages/docs/package.json index 5268f36..c63c0a6 100644 --- a/packages/docs/package.json +++ b/packages/docs/package.json @@ -7,7 +7,7 @@ "dev": "vite dev", "build": "vite build", "start": "serve dist/client", - "types:check": "fumadocs-mdx && tsc --noEmit", + "types:check": "fumadocs-mdx && bun check --no-script", "postinstall": "fumadocs-mdx" }, "dependencies": { diff --git a/packages/duron-dashboard/package.json b/packages/duron-dashboard/package.json index ea39da2..f48e570 100644 --- a/packages/duron-dashboard/package.json +++ b/packages/duron-dashboard/package.json @@ -32,7 +32,7 @@ "build": "NODE_ENV=production bun run build.ts && bun run build:get-html", "build:get-html": "tsc --project tsconfig.node.json", "prepublishOnly": "bun run build", - "typecheck": "tsc --noEmit" + "typecheck": "bun check --no-script" }, "dependencies": { "@dnd-kit/core": "^6.3.1", diff --git a/packages/duron/package.json b/packages/duron/package.json index 84dbab6..6e0b105 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -78,7 +78,7 @@ "prepublishOnly": "bun run build", "test": "bun test --concurrent", "generate:postgres": "bunx --bun drizzle-kit generate --config ./src/adapters/postgres/drizzle.config.ts", - "typecheck": "tsc --noEmit" + "typecheck": "bun check --no-script" }, "dependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0", From 8426e62eab559c94db883a915bde13677182e865 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 09:33:36 -0300 Subject: [PATCH 041/100] build(duron): clean dist before building, stop publishing drizzle.config - build: rm -rf dist && tsc. prepublishOnly runs build, so a publish no longer ships stale files from earlier builds (e.g. the old dist/src/**). - Move drizzle.config.ts from src/adapters/postgres/ to the package root. It is the drizzle-kit dev config for generate:postgres. In src/ it was compiled to dist/adapters/postgres/drizzle.config.js (importing drizzle-kit) and published in both dist/ and src/, but no export reaches it. tsconfig.json includes it explicitly so it is still type checked. - Pack dry-run: 109 files, no drizzle.config; dist has no drizzle-kit import. --- packages/duron/{src/adapters/postgres => }/drizzle.config.ts | 0 packages/duron/package.json | 4 ++-- packages/duron/tsconfig.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename packages/duron/{src/adapters/postgres => }/drizzle.config.ts (100%) diff --git a/packages/duron/src/adapters/postgres/drizzle.config.ts b/packages/duron/drizzle.config.ts similarity index 100% rename from packages/duron/src/adapters/postgres/drizzle.config.ts rename to packages/duron/drizzle.config.ts diff --git a/packages/duron/package.json b/packages/duron/package.json index 6e0b105..f9559e5 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -73,11 +73,11 @@ } }, "scripts": { - "build": "tsc --project tsconfig.node.json", + "build": "rm -rf dist && tsc --project tsconfig.node.json", "dev": "tsc --watch --project tsconfig.node.json", "prepublishOnly": "bun run build", "test": "bun test --concurrent", - "generate:postgres": "bunx --bun drizzle-kit generate --config ./src/adapters/postgres/drizzle.config.ts", + "generate:postgres": "bunx --bun drizzle-kit generate --config ./drizzle.config.ts", "typecheck": "bun check --no-script" }, "dependencies": { diff --git a/packages/duron/tsconfig.json b/packages/duron/tsconfig.json index bb2a4cd..42d868f 100644 --- a/packages/duron/tsconfig.json +++ b/packages/duron/tsconfig.json @@ -27,6 +27,6 @@ "isolatedModules": true, "types": ["bun"] }, - "include": ["src/**/*", "test/**/*"], + "include": ["src/**/*", "test/**/*", "drizzle.config.ts"], "exclude": ["**/dist/**", "**/node_modules/**"] } From 37d89097878e5998333815c8a550801fd8b4de53 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 09:38:53 -0300 Subject: [PATCH 042/100] fix(lint): resolve the 12 oxlint 1.95 warnings - errors.ts (unicorn/no-useless-error-capture-stack-trace): drop Error.captureStackTrace(this, this.constructor) from DuronError. Error subclass stacks already start at the caller: V8 skips frames up to new.target, and a Bun check shows the same first frames and name header with and without the call, for a subclass and a sub-subclass. - dashboard step-list.tsx (import/no-named-as-default): import { clsx }, as src/lib/utils.ts does. - tests (unicorn/consistent-function-scoping, 10): hoist each function one scope up, to where the variables it uses live. endedEarly (3 copies) leaves the db.transaction replacement; run leaves the action handler; withAdapter (2), withStore and claimAs move out of their describe callbacks; createListingJobs and seedListingJob move above describe('Query Methods') with their comments. Code moves only, no logic changes. --- .../duron-dashboard/src/views/step-list.tsx | 2 +- packages/duron/src/errors.ts | 4 -- packages/duron/test/adapter.test.ts | 60 +++++++++---------- .../duron/test/cancel-storage-shared.test.ts | 24 ++++---- packages/duron/test/cancel-storage.test.ts | 2 +- packages/duron/test/lifecycle.test.ts | 12 ++-- .../duron/test/local-cancellation.test.ts | 2 +- packages/duron/test/recover-own-jobs.test.ts | 34 +++++------ packages/duron/test/recover-snapshot.test.ts | 40 ++++++------- 9 files changed, 88 insertions(+), 92 deletions(-) diff --git a/packages/duron-dashboard/src/views/step-list.tsx b/packages/duron-dashboard/src/views/step-list.tsx index 86b7a95..c62172b 100644 --- a/packages/duron-dashboard/src/views/step-list.tsx +++ b/packages/duron-dashboard/src/views/step-list.tsx @@ -1,6 +1,6 @@ 'use client' -import clsx from 'clsx' +import { clsx } from 'clsx' import { Clock, GitBranch, History, List, Search } from 'lucide-react' import { useCallback, useMemo, useState } from 'react' import { useDebounceValue } from 'usehooks-ts' diff --git a/packages/duron/src/errors.ts b/packages/duron/src/errors.ts index 796c04e..62d4a9b 100644 --- a/packages/duron/src/errors.ts +++ b/packages/duron/src/errors.ts @@ -69,10 +69,6 @@ export abstract class DuronError extends Error { this.metadata = options?.metadata ?? {} // Set the name to the class name this.name = this.constructor.name - // Ensure stack trace points to the error location - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor) - } } /** diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index 617e351..bf7dccc 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -620,41 +620,41 @@ function runAdapterTests(adapterFactory: AdapterFactory) { }) }) + // Native fixture seam for listing precision/order cases. All IDs come from public creation; + // archives use public cancellation. SQL seeds are labeled at each test, never public-only. + async function createListingJobs(count: number) { + const ids: string[] = [] + for (let index = 0; index < count; index++) { + const id = await adapter.createJob({ + queue: 'listing-order', + groupKey: 'test-group', + input: { marker: 'input', payload: 'i'.repeat(16_384) }, + timeoutMs: 60_000, + checksum: 'abc123', + concurrencyLimit: 10, + concurrencyStepLimit: 1, + }) + expectToBeDefined(id) + ids.push(id) + } + // Rank fixture IDs, never sort the returned listing before asserting it. + return ids.toSorted() + } + + // Seed JSON as `${text}::text::jsonb`: postgres.js serializes a jsonb-typed string parameter again. + async function seedListingJob(id: string, storage: 'active' | 'archive', fields: SQL) { + const { db } = adapter as unknown as { + db: { execute: (query: SQL) => Promise } + } + await db.execute(sql`UPDATE duron.${sql.identifier(`jobs_${storage}`)} + SET ${fields} WHERE id = ${id}`) + } + describe('Query Methods', () => { beforeEach(async () => { await adapter.start() }) - // Native fixture seam for listing precision/order cases. All IDs come from public creation; - // archives use public cancellation. SQL seeds are labeled at each test, never public-only. - async function createListingJobs(count: number) { - const ids: string[] = [] - for (let index = 0; index < count; index++) { - const id = await adapter.createJob({ - queue: 'listing-order', - groupKey: 'test-group', - input: { marker: 'input', payload: 'i'.repeat(16_384) }, - timeoutMs: 60_000, - checksum: 'abc123', - concurrencyLimit: 10, - concurrencyStepLimit: 1, - }) - expectToBeDefined(id) - ids.push(id) - } - // Rank fixture IDs, never sort the returned listing before asserting it. - return ids.toSorted() - } - - // Seed JSON as `${text}::text::jsonb`: postgres.js serializes a jsonb-typed string parameter again. - async function seedListingJob(id: string, storage: 'active' | 'archive', fields: SQL) { - const { db } = adapter as unknown as { - db: { execute: (query: SQL) => Promise } - } - await db.execute(sql`UPDATE duron.${sql.identifier(`jobs_${storage}`)} - SET ${fields} WHERE id = ${id}`) - } - it('should paginate the globally interleaved population (seeded creation times)', async () => { const ids = await createListingJobs(6) for (const [rank, id] of ids.entries()) { diff --git a/packages/duron/test/cancel-storage-shared.test.ts b/packages/duron/test/cancel-storage-shared.test.ts index 2640dc7..09df988 100644 --- a/packages/duron/test/cancel-storage-shared.test.ts +++ b/packages/duron/test/cancel-storage-shared.test.ts @@ -33,20 +33,20 @@ async function stepStatuses(adapter: Adapter, jobId: string): Promise { - async function withAdapter(test: (adapter: Adapter) => Promise): Promise { - const instance = await factory.create() - instance.adapter.setId('cancel-shared') - try { - await instance.adapter.start() - await test(instance.adapter) - } finally { - // A failed stop retains the database rather than dropping it. - await instance.adapter.stop() - await instance.deleteDb() - } + async function withAdapter(test: (adapter: Adapter) => Promise): Promise { + const instance = await factory.create() + instance.adapter.setId('cancel-shared') + try { + await instance.adapter.start() + await test(instance.adapter) + } finally { + // A failed stop retains the database rather than dropping it. + await instance.adapter.stop() + await instance.deleteDb() } + } + describe(`Cancellation storage with ${factory.name}`, () => { it('archives every step cancelled and rejects later writes with the existing results', async () => { await withAdapter(async (adapter) => { const jobId = await createClaimedJob(adapter) diff --git a/packages/duron/test/cancel-storage.test.ts b/packages/duron/test/cancel-storage.test.ts index 3fdba53..f20c4bc 100644 --- a/packages/duron/test/cancel-storage.test.ts +++ b/packages/duron/test/cancel-storage.test.ts @@ -83,6 +83,7 @@ function gateNextTransaction(adapter: PostgresAdapter, pause: StatementPause | ' reached.resolve() await open.promise } + const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) db.transaction = (work: (tx: unknown) => Promise, config: unknown) => { db.transaction = guarded const transaction = guarded.call( @@ -97,7 +98,6 @@ function gateNextTransaction(adapter: PostgresAdapter, pause: StatementPause | ' }, config, ) - const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) transaction.then(endedEarly, endedEarly) return transaction } diff --git a/packages/duron/test/lifecycle.test.ts b/packages/duron/test/lifecycle.test.ts index 62104a4..8341afe 100644 --- a/packages/duron/test/lifecycle.test.ts +++ b/packages/duron/test/lifecycle.test.ts @@ -501,15 +501,15 @@ for (const factory of [ const release = Promise.withResolvers() let finished = false let timer: ReturnType | undefined + const run = async () => { + entered.resolve() + await release.promise + finished = true + return { done: true } + } const action = defineAction()({ name: `held-${kind}`, handler: async (ctx) => { - const run = async () => { - entered.resolve() - await release.promise - finished = true - return { done: true } - } return kind === 'step' ? ctx.step('held-step', run) : run() }, }) diff --git a/packages/duron/test/local-cancellation.test.ts b/packages/duron/test/local-cancellation.test.ts index be825c0..00e2d40 100644 --- a/packages/duron/test/local-cancellation.test.ts +++ b/packages/duron/test/local-cancellation.test.ts @@ -1196,6 +1196,7 @@ function gateNextTransaction(adapter: PostgresAdapter, pause: StatementPause | ' reached.resolve() await open.promise } + const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) db.transaction = (work: (tx: unknown) => Promise, config: unknown) => { db.transaction = guarded const transaction = guarded.call( @@ -1210,7 +1211,6 @@ function gateNextTransaction(adapter: PostgresAdapter, pause: StatementPause | ' }, config, ) - const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) transaction.then(endedEarly, endedEarly) return transaction } diff --git a/packages/duron/test/recover-own-jobs.test.ts b/packages/duron/test/recover-own-jobs.test.ts index 7be7bd2..314c1b6 100644 --- a/packages/duron/test/recover-own-jobs.test.ts +++ b/packages/duron/test/recover-own-jobs.test.ts @@ -100,25 +100,25 @@ function failNextTransaction(adapter: Adapter, error: Error): void { } for (const engine of engines) { - describe(`Own-id recovery scope with ${engine.name}`, () => { - // Each test owns its store and adapters (tests in a file may run concurrently). - async function withStore(test: (start: () => Promise) => Promise) { - const store = await engine.store() - const adapters: Adapter[] = [] - try { - await test(async () => { - const adapter = store.open() - adapter.setId(OWN) - adapters.push(adapter) - expect(await adapter.start()).toBe(true) - return adapter - }) - } finally { - for (const adapter of adapters) await adapter.stop() - await store.cleanup() - } + // Each test owns its store and adapters (tests in a file may run concurrently). + async function withStore(test: (start: () => Promise) => Promise) { + const store = await engine.store() + const adapters: Adapter[] = [] + try { + await test(async () => { + const adapter = store.open() + adapter.setId(OWN) + adapters.push(adapter) + expect(await adapter.start()).toBe(true) + return adapter + }) + } finally { + for (const adapter of adapters) await adapter.stop() + await store.cleanup() } + } + describe(`Own-id recovery scope with ${engine.name}`, () => { it( 'the first recovery after start requeues own running jobs and archives own expired jobs', () => diff --git a/packages/duron/test/recover-snapshot.test.ts b/packages/duron/test/recover-snapshot.test.ts index 9b2a834..9b09fc6 100644 --- a/packages/duron/test/recover-snapshot.test.ts +++ b/packages/duron/test/recover-snapshot.test.ts @@ -103,6 +103,7 @@ function gateRecovery( reached.promise.catch(() => undefined) open.promise.catch(() => undefined) let transactions = 0 + const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) db.transaction = (work, config) => { if (++transactions < pause.transaction) return guarded.call(db, work, config) db.transaction = guarded @@ -130,7 +131,6 @@ function gateRecovery( }, config, ) - const endedEarly = () => reached.reject(new Error('Transaction ended before the barrier')) transaction.then(endedEarly, endedEarly) return transaction } @@ -1075,28 +1075,28 @@ const engines: AdapterFactory[] = [ ] for (const factory of engines) { - describe(`Recovery selection and binding with ${factory.name}`, () => { - async function withAdapter(test: (adapter: Adapter) => Promise): Promise { - const instance = await factory.create() - instance.adapter.setId('r') - try { - await instance.adapter.start() - await test(instance.adapter) - } finally { - // A failed stop retains the database rather than dropping it. - await instance.adapter.stop() - await instance.deleteDb() - } + async function withAdapter(test: (adapter: Adapter) => Promise): Promise { + const instance = await factory.create() + instance.adapter.setId('r') + try { + await instance.adapter.start() + await test(instance.adapter) + } finally { + // A failed stop retains the database rather than dropping it. + await instance.adapter.stop() + await instance.deleteDb() } + } - async function claimAs(adapter: Adapter, owner: string, timeoutMs: number, checksum: string) { - adapter.setId(owner) - const jobId = await createJob(adapter, { timeoutMs, checksum }) - expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) - const step = (await createStep(adapter, jobId, 's1'))! - return { jobId, stepId: step.id } - } + async function claimAs(adapter: Adapter, owner: string, timeoutMs: number, checksum: string) { + adapter.setId(owner) + const jobId = await createJob(adapter, { timeoutMs, checksum }) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + const step = (await createStep(adapter, jobId, 's1'))! + return { jobId, stepId: step.id } + } + describe(`Recovery selection and binding with ${factory.name}`, () => { it( 'KR6: keeps selection, counts, checksum retention and written fields', async () => { From 7726aa631885f4cb4a6ab499e112c5efe4999bb5 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 10:53:59 -0300 Subject: [PATCH 043/100] chore(dashboard): upgrade lucide-react 1, motion 14, nanoid 6, react-day-picker 10, maskito 5, TanStack Table 9 - TanStack Table 8 -> 9: useReactTable -> useTable with an explicit features object (lib/data-table-features.ts). It registers the features the data tables use: filtering, faceting, sorting, pagination, selection, visibility, ordering, pinning, sizing and resizing. It also registers the row models v8 always ran (bypassed by manual pagination, sorting and filtering) and the built-in filter functions that 'auto' resolves to; setColumnFilters uses their autoRemove hooks, as in v8. Other changes: - TFeatures is the first type argument everywhere, and TData extends RowData. - TableMeta/ColumnMeta augmentations take the v9 type parameters. - table.getState() -> table.store.state. - Column pinning left/right -> start/end, and columnPinning now sets both keys. - VisibilityState -> ColumnVisibilityState. - react-day-picker 10 removed the deprecated `table` classNames key, so ui/calendar.tsx uses month_grid. This is the one forced edit to a shadcn file, and it matches the current shadcn registry calendar line for line. - lucide-react 1, motion 14, nanoid 6, maskito 5: no code changes. lucide 1 redraws some icons (GitBranch, Calendar, CircleCheck). --- bun.lock | 50 +++++++------- packages/duron-dashboard/package.json | 16 ++--- .../data-table/data-table-action-bar.tsx | 19 ++++-- .../data-table-advanced-toolbar.tsx | 9 +-- .../data-table/data-table-column-header.tsx | 9 +-- .../data-table/data-table-date-filter.tsx | 9 +-- .../data-table/data-table-faceted-filter.tsx | 9 +-- .../data-table/data-table-filter-list.tsx | 23 ++++--- .../data-table/data-table-filter-menu.tsx | 38 +++++++---- .../data-table/data-table-pagination.tsx | 15 ++-- .../data-table/data-table-range-filter.tsx | 9 +-- .../data-table/data-table-slider-filter.tsx | 12 ++-- .../data-table/data-table-sort-list.tsx | 16 +++-- .../data-table/data-table-toolbar.tsx | 21 +++--- .../data-table/data-table-view-options.tsx | 14 ++-- .../src/components/data-table/data-table.tsx | 36 ++++++---- .../src/components/ui/calendar.tsx | 2 +- .../src/contexts/layout-context.tsx | 10 +-- .../src/hooks/use-data-table.ts | 41 ++++------- .../src/lib/data-table-features.ts | 68 +++++++++++++++++++ .../duron-dashboard/src/lib/data-table.ts | 21 +++--- .../duron-dashboard/src/types/data-table.ts | 15 ++-- .../duron-dashboard/src/views/jobs-table.tsx | 26 +++---- 23 files changed, 304 insertions(+), 184 deletions(-) create mode 100644 packages/duron-dashboard/src/lib/data-table-features.ts diff --git a/bun.lock b/bun.lock index 8e172d1..c248822 100644 --- a/bun.lock +++ b/bun.lock @@ -86,9 +86,9 @@ "@dnd-kit/modifiers": "^9.0.0", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", - "@maskito/core": "^4.0.1", - "@maskito/kit": "^4.0.1", - "@maskito/react": "^4.0.1", + "@maskito/core": "^5.6.1", + "@maskito/kit": "^5.6.1", + "@maskito/react": "^5.6.1", "@monaco-editor/react": "^4.7.0", "@radix-ui/react-accordion": "^1.3.1", "@radix-ui/react-checkbox": "^1.4.1", @@ -103,19 +103,19 @@ "@radix-ui/react-slot": "^1.5.0", "@radix-ui/react-tooltip": "^1.4.1", "@tanstack/react-query": "^5.108.4", - "@tanstack/react-table": "^8.21.3", + "@tanstack/react-table": "^9.3.1", "@tanstack/react-virtual": "^3.14.30", "bun-plugin-tailwind": "^0.1.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", "date-fns": "^4.4.0", - "lucide-react": "^0.555.0", - "motion": "^12.43.0", - "nanoid": "^5.1.16", + "lucide-react": "^1.84.0", + "motion": "^14.14.0", + "nanoid": "^6.0.2", "nuqs": "^2.10.3", "react": "^19.3.1", - "react-day-picker": "^9.14.0", + "react-day-picker": "^10.0.2", "react-dom": "^19.3.1", "react-resizable-panels": "^4.27.0", "tailwind-merge": "^3.7.1", @@ -293,11 +293,11 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], - "@maskito/core": ["@maskito/core@4.0.1", "", {}, "sha512-0ewYXnr8X7as/n57duk1DDqjAKF0m32XbFiAhKdd9OX83eMBzO2+4xgUFxh6WZJ18oSw6y2nWjCTDFAFc5JbhA=="], + "@maskito/core": ["@maskito/core@5.6.1", "", {}, "sha512-P5XKR1wwkTLagzyH79ZE6TfQI20IR+eHeP8hoKrfqlr99luLo1QYTux9OFPvIH+o2GGzCkIBbgwYaquunZlC1Q=="], - "@maskito/kit": ["@maskito/kit@4.0.1", "", { "peerDependencies": { "@maskito/core": "^4.0.1" } }, "sha512-GHxK65y5sBwCO0Retl80NvB37uDaIY9g5hezyOe9EG7+zjGRUqDjYc3b04ofJHlGgPtpreOiBDq5bqEr0I/OMw=="], + "@maskito/kit": ["@maskito/kit@5.6.1", "", { "peerDependencies": { "@maskito/core": "^5.6.1" } }, "sha512-iFGbJpXkagGzLPgxnneTZaV5YAUfSNBAc+y3SgdSYWY4fGJpZvzwVTLmHIngyEHPsd0VzIV9DcXKuzFnIkZfiA=="], - "@maskito/react": ["@maskito/react@4.0.1", "", { "peerDependencies": { "@maskito/core": "^4.0.1", "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-h9Ebmb2gEi1yUFvQdn+kDuKA7BijWuT5Wgx2lASgTbeBi6HM0SE2BB0y2a19wX1Tur7DqHZIFSiYzQy6plWU/A=="], + "@maskito/react": ["@maskito/react@5.6.1", "", { "peerDependencies": { "@maskito/core": "^5.6.1", "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-Q1NZkt5yVHy+5Zx7/l/Nzk5I8NU0r8QT9F88i8dBu3v6/XcyxpGWLBifhPlM86DZpBUn2HSrADzVMrRM3WtaIw=="], "@mdx-js/mdx": ["@mdx-js/mdx@3.1.1", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdx": "^2.0.0", "acorn": "^8.0.0", "collapse-white-space": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "estree-util-scope": "^1.0.0", "estree-walker": "^3.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "markdown-extensions": "^2.0.0", "recma-build-jsx": "^1.0.0", "recma-jsx": "^1.0.0", "recma-stringify": "^1.0.0", "rehype-recma": "^1.0.0", "remark-mdx": "^3.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "source-map": "^0.7.0", "unified": "^11.0.0", "unist-util-position-from-estree": "^2.0.0", "unist-util-stringify-position": "^4.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ=="], @@ -595,8 +595,6 @@ "@standard-schema/utils": ["@standard-schema/utils@0.3.0", "", {}, "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="], - "@tabby_ai/hijri-converter": ["@tabby_ai/hijri-converter@1.0.5", "", {}, "sha512-r5bClKrcIusDoo049dSL8CawnHR6mRdDwhlQuIgZRNty68q0x8k3Lf1BtPAMxRf/GgnHBnIO4ujd3+GQdLWzxQ=="], - "@tailwindcss/node": ["@tailwindcss/node@4.3.5", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.5", "jiti": "^2.7.0", "lightningcss": "1.33.0", "magic-string": "^1.1.0", "source-map-js": "^1.2.1", "tailwindcss": "4.3.5" } }, "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g=="], "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.5", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.5", "@tailwindcss/oxide-darwin-arm64": "4.3.5", "@tailwindcss/oxide-darwin-x64": "4.3.5", "@tailwindcss/oxide-freebsd-x64": "4.3.5", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", "@tailwindcss/oxide-linux-x64-musl": "4.3.5", "@tailwindcss/oxide-wasm32-wasi": "4.3.5", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" } }, "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg=="], @@ -645,7 +643,7 @@ "@tanstack/react-store": ["@tanstack/react-store@0.9.3", "", { "dependencies": { "@tanstack/store": "0.9.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg=="], - "@tanstack/react-table": ["@tanstack/react-table@8.21.3", "", { "dependencies": { "@tanstack/table-core": "8.21.3" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww=="], + "@tanstack/react-table": ["@tanstack/react-table@9.3.1", "", { "dependencies": { "@tanstack/react-store": "^0.11.2", "@tanstack/table-core": "9.3.1" }, "peerDependencies": { "react": ">=18" } }, "sha512-E6Ya5TnY6EaGyZYIUqig/29Lr/gJSAubQkLJFqiWkUl5nRCr0Xr9hvJot+NiRTtG+TzGxHTiqUW3bnLtQxlHug=="], "@tanstack/react-virtual": ["@tanstack/react-virtual@3.14.30", "", { "dependencies": { "@tanstack/virtual-core": "3.19.15" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-vVq9U2WahGWue0RVPrzGuBM8QxhGKq6WV7AOUyXWR17F3kYNxHMZekYZdKm0X63/S4QZGCDlBqASvAukpXQ8GQ=="], @@ -671,7 +669,7 @@ "@tanstack/store": ["@tanstack/store@0.9.3", "", {}, "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw=="], - "@tanstack/table-core": ["@tanstack/table-core@8.21.3", "", {}, "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg=="], + "@tanstack/table-core": ["@tanstack/table-core@9.3.1", "", { "dependencies": { "@tanstack/store": "^0.11.2" } }, "sha512-zQvlxSNi2qGM3L4jh85Z6hqMfdIR5qOfD9KHOU32nuKFJGN0RlJ7UvV1lsPb1fPVhpFYI0VP3jJGxLdLDpTKjQ=="], "@tanstack/virtual-core": ["@tanstack/virtual-core@3.19.15", "", {}, "sha512-XL0RLw2Y1Qm5IrtIuz0cmX2nDc2hjtKr0J+7S+xHaDHcy19u8Fg1o17nCBMIKlrCgmMcgnViexlHGDx8SniuBw=="], @@ -873,8 +871,6 @@ "date-fns": ["date-fns@4.4.0", "", {}, "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w=="], - "date-fns-jalali": ["date-fns-jalali@4.1.0-0", "", {}, "sha512-hTIP/z+t+qKwBDcmmsnmjWTduxCg+5KfdqWQvb2X/8C9+knYY6epN/pfxdDuyVlSVeFz0sM5eEfwIUQ70U4ckg=="], - "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="], @@ -965,7 +961,7 @@ "file-type": ["file-type@22.3.0", "", { "dependencies": { "@tokenizer/inflate": "^0.6.0", "strtok3": "^10.6.3", "token-types": "^6.1.2", "uint8array-extras": "^1.6.0" } }, "sha512-PrPedgnnWl5bWz3JHgar0QSzRvzeyFh7dZ9JpYOgcPZu4KALS9zw4MMa6qXRYyjeBsAlpaWB2boLuG991+0HIQ=="], - "framer-motion": ["framer-motion@12.43.0", "", { "dependencies": { "motion-dom": "^12.43.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g=="], + "framer-motion": ["framer-motion@14.14.0", "", { "dependencies": { "motion-dom": "14.14.0", "motion-utils": "14.7.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "remix": "^3.1.0" }, "optionalPeers": ["react", "react-dom", "remix"] }, "sha512-fidRX0VzkZdA9OovFiBSzJtt9/jLcJpna78Z+KCqQQZIWoIpN3tOhEXAhhAw/FObUUh+o3Y18yx1F4BP0mVJ8Q=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -1075,7 +1071,7 @@ "lru-cache": ["lru-cache@11.5.4", "", {}, "sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw=="], - "lucide-react": ["lucide-react@0.555.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-D8FvHUGbxWBRQM90NZeIyhAvkFfsh3u9ekrMvJ30Z6gnpBHS6HC6ldLg7tL45hwiIz/u66eKDtdA23gwwGsAHA=="], + "lucide-react": ["lucide-react@1.84.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-kTIK/SVxMHW/d7hpjgleufRON3s6iWOvv7w9C8AeGQDYM4tDyWp58xltDHzlh7+x2uydNevrr7FgiAv0/dynLA=="], "lucide-static": ["lucide-static@0.552.0", "", {}, "sha512-wL+9EAx8k/4i/w9qGuAwHrrV8SryVsJk+Ug9SErtg18Zq95FMwMXlu4Dhl4RS8C2b1oxFu66p7YK96yrNsm6cg=="], @@ -1203,15 +1199,15 @@ "monaco-editor": ["monaco-editor@0.58.0", "", { "dependencies": { "@vscode/diff": "0.0.2-145", "dompurify": "3.4.17", "marked": "14.0.0" } }, "sha512-Lj5hlfT4zdM5GSG9VxTHslWnwibGBvO6d9Mq/+9zmb1CkTZnib4+uAZUKl1zg+tMHRgY2OGax6hHKZNBtldR1g=="], - "motion": ["motion@12.43.0", "", { "dependencies": { "framer-motion": "^12.43.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-BQgQbSa9Hn3/mtbib0MK53y6JSANa+YKUKlaYnWzAVDH424RYQ5LVpV3pNiWH00BA2z4ojsSdMzqT7g2FQwjuQ=="], + "motion": ["motion@14.14.0", "", { "dependencies": { "framer-motion": "14.14.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "remix": "^3.1.0" }, "optionalPeers": ["react", "react-dom", "remix"] }, "sha512-a306U6sV5VKq1abtzKiinB+UQjiY88jrsvQzWORP3WPv/DFANyoYVlPbdnmJPMEbusyPXB4GyQJVANaq/pSIYQ=="], - "motion-dom": ["motion-dom@12.43.0", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag=="], + "motion-dom": ["motion-dom@14.14.0", "", { "dependencies": { "motion-utils": "14.7.0" } }, "sha512-IAxcKhYkuQA2W0Tlx1AvVgImfqEoF3/t3IovbPQJlYkefmGsmrXjn967lMII5VmFmLpQEab4+ZkHo/ijJ4Esig=="], - "motion-utils": ["motion-utils@12.39.0", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="], + "motion-utils": ["motion-utils@14.7.0", "", {}, "sha512-woO0/Nb7ys75f94fjvQi/6leiHGvZUYkeHUPEZ3vxsV+9OpEVhkxp01x8MlRwX0zt31EqgXsKDAoBoJLC148Tw=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "nanoid": ["nanoid@5.1.16", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="], + "nanoid": ["nanoid@6.0.2", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-hIvVOb9Qr1p/9CNNLOe0OlWvgx/ziTsVwKN/GDSsuArN2K0wDiafP3s0SWmsm7o2BdnyS8Z9Z64NFBUbn6ziBg=="], "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], @@ -1277,7 +1273,7 @@ "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], - "react-day-picker": ["react-day-picker@9.14.0", "", { "dependencies": { "@date-fns/tz": "^1.4.1", "@tabby_ai/hijri-converter": "1.0.5", "date-fns": "^4.1.0", "date-fns-jalali": "4.1.0-0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-tBaoDWjPwe0M5pGrum4H0SR6Lyk+BO9oHnp9JbKpGKW2mlraNPgP9BMfsg5pWpwrssARmeqk7YBl2oXutZTaHA=="], + "react-day-picker": ["react-day-picker@10.0.2", "", { "dependencies": { "@date-fns/tz": "^1.4.1", "date-fns": "^4.1.0" }, "peerDependencies": { "@types/react": ">=16.8.0", "react": ">=16.8.0" }, "optionalPeers": ["@types/react"] }, "sha512-QetiKtZWE9Uaw/pM/SYNv6WPYOTRnSJ2puL0GgwkmUFMIwiY0dtjH1W4B7DOVXVNQM0ZOClGpH/heOfBSzWeiA=="], "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], @@ -1501,12 +1497,16 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.9.1", "", { "bundled": true }, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + "@tanstack/react-table/@tanstack/react-store": ["@tanstack/react-store@0.11.4", "", { "dependencies": { "@tanstack/store": "0.11.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-JAQz7LcABVRbxZ6qCd4u/KqDaqBc1qmcOWz7XBTdav1Ib363HQdihCQF1A755nDhoi9VEd6UqZ5thWVKTwIIXw=="], + "@tanstack/router-generator/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], "@tanstack/router-plugin/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], "@tanstack/start-plugin-core/@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], + "@tanstack/table-core/@tanstack/store": ["@tanstack/store@0.11.3", "", {}, "sha512-/Mt3h2Qe67HmRMc5SJ+8jM2Fp7O4fBbwOlS0ujUvx34KgAvkvdLSHrJatv0PJG5fbvlDsACTawMMY4ptCpVI8w=="], + "ansi-align/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], "bun-types/undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], @@ -1533,6 +1533,8 @@ "unplugin/@rolldown/pluginutils": ["@rolldown/pluginutils@1.1.1", "", {}, "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA=="], + "@tanstack/react-table/@tanstack/react-store/@tanstack/store": ["@tanstack/store@0.11.3", "", {}, "sha512-/Mt3h2Qe67HmRMc5SJ+8jM2Fp7O4fBbwOlS0ujUvx34KgAvkvdLSHrJatv0PJG5fbvlDsACTawMMY4ptCpVI8w=="], + "@tanstack/router-plugin/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], "ansi-align/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], diff --git a/packages/duron-dashboard/package.json b/packages/duron-dashboard/package.json index f48e570..cb351dc 100644 --- a/packages/duron-dashboard/package.json +++ b/packages/duron-dashboard/package.json @@ -39,9 +39,9 @@ "@dnd-kit/modifiers": "^9.0.0", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", - "@maskito/core": "^4.0.1", - "@maskito/kit": "^4.0.1", - "@maskito/react": "^4.0.1", + "@maskito/core": "^5.6.1", + "@maskito/kit": "^5.6.1", + "@maskito/react": "^5.6.1", "@monaco-editor/react": "^4.7.0", "@radix-ui/react-accordion": "^1.3.1", "@radix-ui/react-checkbox": "^1.4.1", @@ -56,19 +56,19 @@ "@radix-ui/react-slot": "^1.5.0", "@radix-ui/react-tooltip": "^1.4.1", "@tanstack/react-query": "^5.108.4", - "@tanstack/react-table": "^8.21.3", + "@tanstack/react-table": "^9.3.1", "@tanstack/react-virtual": "^3.14.30", "bun-plugin-tailwind": "^0.1.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "cmdk": "^1.1.1", "date-fns": "^4.4.0", - "lucide-react": "^0.555.0", - "motion": "^12.43.0", - "nanoid": "^5.1.16", + "lucide-react": "^1.84.0", + "motion": "^14.14.0", + "nanoid": "^6.0.2", "nuqs": "^2.10.3", "react": "^19.3.1", - "react-day-picker": "^9.14.0", + "react-day-picker": "^10.0.2", "react-dom": "^19.3.1", "react-resizable-panels": "^4.27.0", "tailwind-merge": "^3.7.1", diff --git a/packages/duron-dashboard/src/components/data-table/data-table-action-bar.tsx b/packages/duron-dashboard/src/components/data-table/data-table-action-bar.tsx index 5215ea5..7e73fe3 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-action-bar.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-action-bar.tsx @@ -1,6 +1,6 @@ 'use client' -import type { Table } from '@tanstack/react-table' +import type { RowData, Table } from '@tanstack/react-table' import { Loader, X } from 'lucide-react' import { AnimatePresence, motion } from 'motion/react' import * as React from 'react' @@ -9,15 +9,18 @@ import * as ReactDOM from 'react-dom' import { Button } from '@/components/ui/button' import { Separator } from '@/components/ui/separator' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import type { DataTableFeatures } from '@/lib/data-table-features' import { cn } from '@/lib/utils' -interface DataTableActionBarProps extends React.ComponentProps { - table: Table +interface DataTableActionBarProps extends React.ComponentProps< + typeof motion.div +> { + table: Table visible?: boolean portalContainer?: Element | DocumentFragment | null } -function DataTableActionBar({ +function DataTableActionBar({ table, visible: visibleProp, portalContainer: portalContainerProp, @@ -117,11 +120,13 @@ function DataTableActionBarAction({ ) } -interface DataTableActionBarSelectionProps { - table: Table +interface DataTableActionBarSelectionProps { + table: Table } -function DataTableActionBarSelection({ table }: DataTableActionBarSelectionProps) { +function DataTableActionBarSelection({ + table, +}: DataTableActionBarSelectionProps) { const onClearSelection = React.useCallback(() => { table.toggleAllRowsSelected(false) }, [table]) diff --git a/packages/duron-dashboard/src/components/data-table/data-table-advanced-toolbar.tsx b/packages/duron-dashboard/src/components/data-table/data-table-advanced-toolbar.tsx index cb42aa1..9c344f5 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-advanced-toolbar.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-advanced-toolbar.tsx @@ -1,16 +1,17 @@ 'use client' -import type { Table } from '@tanstack/react-table' +import type { RowData, Table } from '@tanstack/react-table' import type * as React from 'react' import { DataTableViewOptions } from '@/components/data-table/data-table-view-options' +import type { DataTableFeatures } from '@/lib/data-table-features' import { cn } from '@/lib/utils' -interface DataTableAdvancedToolbarProps extends React.ComponentProps<'div'> { - table: Table +interface DataTableAdvancedToolbarProps extends React.ComponentProps<'div'> { + table: Table } -export function DataTableAdvancedToolbar({ +export function DataTableAdvancedToolbar({ table, children, className, diff --git a/packages/duron-dashboard/src/components/data-table/data-table-column-header.tsx b/packages/duron-dashboard/src/components/data-table/data-table-column-header.tsx index 2513009..d9bf7c2 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-column-header.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-column-header.tsx @@ -1,6 +1,6 @@ 'use client' -import type { Column } from '@tanstack/react-table' +import type { Column, RowData } from '@tanstack/react-table' import { ChevronDown, ChevronsUpDown, ChevronUp, EyeOff, X } from 'lucide-react' import { @@ -10,16 +10,17 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu' +import type { DataTableFeatures } from '@/lib/data-table-features' import { cn } from '@/lib/utils' -interface DataTableColumnHeaderProps extends React.ComponentProps< +interface DataTableColumnHeaderProps extends React.ComponentProps< typeof DropdownMenuTrigger > { - column: Column + column: Column label: string } -export function DataTableColumnHeader({ +export function DataTableColumnHeader({ column, label, className, diff --git a/packages/duron-dashboard/src/components/data-table/data-table-date-filter.tsx b/packages/duron-dashboard/src/components/data-table/data-table-date-filter.tsx index d04a28f..bca892e 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-date-filter.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-date-filter.tsx @@ -1,6 +1,6 @@ 'use client' -import type { Column } from '@tanstack/react-table' +import type { Column, RowData } from '@tanstack/react-table' import { CalendarIcon, XCircle } from 'lucide-react' import * as React from 'react' import type { DateRange } from 'react-day-picker' @@ -9,6 +9,7 @@ import InputDateTime from '@/components/input-date-time' import { Button } from '@/components/ui/button' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Separator } from '@/components/ui/separator' +import type { DataTableFeatures } from '@/lib/data-table-features' import { formatDate } from '@/lib/format' type DateSelection = Date[] | DateRange @@ -45,13 +46,13 @@ function parseColumnFilterValue(value: unknown) { return [] } -interface DataTableDateFilterProps { - column: Column +interface DataTableDateFilterProps { + column: Column title?: string multiple?: boolean } -export function DataTableDateFilter({ +export function DataTableDateFilter({ column, title, multiple, diff --git a/packages/duron-dashboard/src/components/data-table/data-table-faceted-filter.tsx b/packages/duron-dashboard/src/components/data-table/data-table-faceted-filter.tsx index 753eb93..b747099 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-faceted-filter.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-faceted-filter.tsx @@ -1,6 +1,6 @@ 'use client' -import type { Column } from '@tanstack/react-table' +import type { Column, RowData } from '@tanstack/react-table' import { Check, PlusCircle, XCircle } from 'lucide-react' import * as React from 'react' @@ -17,17 +17,18 @@ import { } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Separator } from '@/components/ui/separator' +import type { DataTableFeatures } from '@/lib/data-table-features' import { cn } from '@/lib/utils' import type { Option } from '@/types/data-table' -interface DataTableFacetedFilterProps { - column?: Column +interface DataTableFacetedFilterProps { + column?: Column title?: string options: Option[] multiple?: boolean } -export function DataTableFacetedFilter({ +export function DataTableFacetedFilter({ column, title, options, diff --git a/packages/duron-dashboard/src/components/data-table/data-table-filter-list.tsx b/packages/duron-dashboard/src/components/data-table/data-table-filter-list.tsx index 8e1852b..4e9e125 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-filter-list.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-filter-list.tsx @@ -1,6 +1,6 @@ 'use client' -import type { Column, ColumnMeta, Table } from '@tanstack/react-table' +import type { Column, ColumnMeta, RowData, Table } from '@tanstack/react-table' import { CalendarIcon, Check, ChevronsUpDown, GripVertical, ListFilter, Trash2 } from 'lucide-react' import { parseAsStringEnum, useQueryState } from 'nuqs' import * as React from 'react' @@ -47,6 +47,7 @@ import { import { dataTableConfig } from '@/config/data-table' import { useDebouncedCallback } from '@/hooks/use-debounced-callback' import { getDefaultFilterOperator, getFilterOperators } from '@/lib/data-table' +import type { DataTableFeatures } from '@/lib/data-table-features' import { formatDate } from '@/lib/format' import { generateId } from '@/lib/id' import { getFiltersStateParser } from '@/lib/parsers' @@ -58,14 +59,16 @@ const THROTTLE_MS = 50 const FILTER_SHORTCUT_KEY = 'f' const REMOVE_FILTER_SHORTCUTS = ['backspace', 'delete'] -interface DataTableFilterListProps extends React.ComponentProps { - table: Table +interface DataTableFilterListProps extends React.ComponentProps< + typeof PopoverContent +> { + table: Table debounceMs?: number throttleMs?: number shallow?: boolean } -export function DataTableFilterList({ +export function DataTableFilterList({ table, debounceMs = DEBOUNCE_MS, throttleMs = THROTTLE_MS, @@ -265,13 +268,13 @@ export function DataTableFilterList({ ) } -interface DataTableFilterItemProps { +interface DataTableFilterItemProps { filter: ExtendedColumnFilter index: number filterItemId: string joinOperator: JoinOperator setJoinOperator: (value: JoinOperator) => void - columns: Column[] + columns: Column[] onFilterUpdate: ( filterId: string, updates: Partial, 'filterId'>>, @@ -279,7 +282,7 @@ interface DataTableFilterItemProps { onFilterRemove: (filterId: string) => void } -function DataTableFilterItem({ +function DataTableFilterItem({ filter, index, filterItemId, @@ -469,7 +472,7 @@ function DataTableFilterItem({ ) } -function onFilterInputRender({ +function onFilterInputRender({ filter, inputId, column, @@ -480,8 +483,8 @@ function onFilterInputRender({ }: { filter: ExtendedColumnFilter inputId: string - column: Column - columnMeta?: ColumnMeta + column: Column + columnMeta?: ColumnMeta onFilterUpdate: ( filterId: string, updates: Partial, 'filterId'>>, diff --git a/packages/duron-dashboard/src/components/data-table/data-table-filter-menu.tsx b/packages/duron-dashboard/src/components/data-table/data-table-filter-menu.tsx index ead23c3..7482d0c 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-filter-menu.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-filter-menu.tsx @@ -1,6 +1,6 @@ 'use client' -import type { Column, Table } from '@tanstack/react-table' +import type { Column, RowData, Table } from '@tanstack/react-table' import { BadgeCheck, CalendarIcon, Check, ListFilter, Text, X } from 'lucide-react' import { useQueryState } from 'nuqs' import * as React from 'react' @@ -27,6 +27,7 @@ import { } from '@/components/ui/select' import { useDebouncedCallback } from '@/hooks/use-debounced-callback' import { getDefaultFilterOperator, getFilterOperators } from '@/lib/data-table' +import type { DataTableFeatures } from '@/lib/data-table-features' import { formatDate } from '@/lib/format' import { generateId } from '@/lib/id' import { getFiltersStateParser } from '@/lib/parsers' @@ -38,14 +39,16 @@ const THROTTLE_MS = 50 const FILTER_SHORTCUT_KEY = 'f' const REMOVE_FILTER_SHORTCUTS = ['backspace', 'delete'] -interface DataTableFilterMenuProps extends React.ComponentProps { - table: Table +interface DataTableFilterMenuProps extends React.ComponentProps< + typeof PopoverContent +> { + table: Table debounceMs?: number throttleMs?: number shallow?: boolean } -export function DataTableFilterMenu({ +export function DataTableFilterMenu({ table, debounceMs = DEBOUNCE_MS, throttleMs = THROTTLE_MS, @@ -60,7 +63,10 @@ export function DataTableFilterMenu({ }, [table]) const [open, setOpen] = React.useState(false) - const [selectedColumn, setSelectedColumn] = React.useState | null>(null) + const [selectedColumn, setSelectedColumn] = React.useState | null>(null) const [inputValue, setInputValue] = React.useState('') const triggerRef = React.useRef(null) const inputRef = React.useRef(null) @@ -103,7 +109,7 @@ export function DataTableFilterMenu({ const debouncedSetFilters = useDebouncedCallback(setFilters, debounceMs) const onFilterAdd = React.useCallback( - (column: Column, value: string) => { + (column: Column, value: string) => { if (!value.trim() && column.columnDef.meta?.variant !== 'boolean') { return } @@ -292,10 +298,10 @@ export function DataTableFilterMenu({ ) } -interface DataTableFilterItemProps { +interface DataTableFilterItemProps { filter: ExtendedColumnFilter filterItemId: string - columns: Column[] + columns: Column[] onFilterUpdate: ( filterId: string, updates: Partial, 'filterId'>>, @@ -303,7 +309,7 @@ interface DataTableFilterItemProps { onFilterRemove: (filterId: string) => void } -function DataTableFilterItem({ +function DataTableFilterItem({ filter, filterItemId, columns, @@ -448,13 +454,17 @@ function DataTableFilterItem({ } } -interface FilterValueSelectorProps { - column: Column +interface FilterValueSelectorProps { + column: Column value: string onSelect: (value: string) => void } -function FilterValueSelector({ column, value, onSelect }: FilterValueSelectorProps) { +function FilterValueSelector({ + column, + value, + onSelect, +}: FilterValueSelectorProps) { const variant = column.columnDef.meta?.variant ?? 'text' switch (variant) { @@ -524,7 +534,7 @@ function FilterValueSelector({ column, value, onSelect }: FilterValueSele } } -function onFilterInputRender({ +function onFilterInputRender({ filter, column, inputId, @@ -533,7 +543,7 @@ function onFilterInputRender({ setShowValueSelector, }: { filter: ExtendedColumnFilter - column: Column + column: Column inputId: string onFilterUpdate: ( filterId: string, diff --git a/packages/duron-dashboard/src/components/data-table/data-table-pagination.tsx b/packages/duron-dashboard/src/components/data-table/data-table-pagination.tsx index c20dd59..bef33bb 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-pagination.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-pagination.tsx @@ -1,4 +1,4 @@ -import type { Table } from '@tanstack/react-table' +import type { RowData, Table } from '@tanstack/react-table' import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react' import { Button } from '@/components/ui/button' @@ -9,14 +9,15 @@ import { SelectTrigger, SelectValue, } from '@/components/ui/select' +import type { DataTableFeatures } from '@/lib/data-table-features' import { cn } from '@/lib/utils' -interface DataTablePaginationProps extends React.ComponentProps<'div'> { - table: Table +interface DataTablePaginationProps extends React.ComponentProps<'div'> { + table: Table pageSizeOptions?: number[] } -export function DataTablePagination({ +export function DataTablePagination({ table, pageSizeOptions = [10, 20, 30, 40, 50], className, @@ -34,13 +35,13 @@ export function DataTablePagination({

Rows per page

- Page {table.getState().pagination.pageIndex + 1} of {table.getPageCount()} + Page {table.store.state.pagination.pageIndex + 1} of {table.getPageCount()}
@@ -154,11 +155,13 @@ export function DataTableToolbar({ ) } -interface DataTableToolbarFilterProps { - column: Column +interface DataTableToolbarFilterProps { + column: Column } -function DataTableToolbarFilter({ column }: DataTableToolbarFilterProps) { +function DataTableToolbarFilter({ + column, +}: DataTableToolbarFilterProps) { { const columnMeta = column.columnDef.meta diff --git a/packages/duron-dashboard/src/components/data-table/data-table-view-options.tsx b/packages/duron-dashboard/src/components/data-table/data-table-view-options.tsx index c628db8..5adefe8 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-view-options.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-view-options.tsx @@ -1,6 +1,6 @@ 'use client' -import type { Table } from '@tanstack/react-table' +import type { RowData, Table } from '@tanstack/react-table' import { Check, Settings2 } from 'lucide-react' import * as React from 'react' @@ -14,13 +14,19 @@ import { CommandList, } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' +import type { DataTableFeatures } from '@/lib/data-table-features' import { cn } from '@/lib/utils' -interface DataTableViewOptionsProps extends React.ComponentProps { - table: Table +interface DataTableViewOptionsProps extends React.ComponentProps< + typeof PopoverContent +> { + table: Table } -export function DataTableViewOptions({ table, ...props }: DataTableViewOptionsProps) { +export function DataTableViewOptions({ + table, + ...props +}: DataTableViewOptionsProps) { const columns = React.useMemo( () => table diff --git a/packages/duron-dashboard/src/components/data-table/data-table.tsx b/packages/duron-dashboard/src/components/data-table/data-table.tsx index 3e23efd..5c0bb40 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table.tsx @@ -1,4 +1,9 @@ -import { flexRender, type Header, type Table as TanstackTable } from '@tanstack/react-table' +import { + flexRender, + type Header, + type RowData, + type Table as TanstackTable, +} from '@tanstack/react-table' import type * as React from 'react' import { DataTablePagination } from '@/components/data-table/data-table-pagination' @@ -11,9 +16,14 @@ import { TableHeader, TableRow, } from '@/components/ui/table' +import type { DataTableFeatures } from '@/lib/data-table-features' import { cn } from '@/lib/utils' -function ColumnResizer({ header }: { header: Header }) { +function ColumnResizer({ + header, +}: { + header: Header +}) { if (!header.column.getCanResize()) { return null } @@ -36,8 +46,8 @@ function ColumnResizer({ header }: { header: Header }) { ) } -interface DataTableProps extends React.ComponentProps<'div'> { - table: TanstackTable +interface DataTableProps extends React.ComponentProps<'div'> { + table: TanstackTable actionBar?: React.ReactNode /** * When true, the table will expand to fill available height with: @@ -48,7 +58,7 @@ interface DataTableProps extends React.ComponentProps<'div'> { fillHeight?: boolean } -export function DataTable({ +export function DataTable({ table, actionBar, children, @@ -78,9 +88,9 @@ export function DataTable({ colSpan={header.colSpan} className={cn( 'relative', - isPinned === 'right' && + isPinned === 'end' && 'sticky right-0 z-20 bg-background shadow-[-4px_0_8px_-4px_rgba(0,0,0,0.1)]', - isPinned === 'left' && 'sticky left-0 z-20 bg-background', + isPinned === 'start' && 'sticky left-0 z-20 bg-background', )} style={{ width: header.getSize() }} > @@ -112,11 +122,11 @@ export function DataTable({ key={cell.id} className={cn( 'overflow-hidden', - isPinned === 'right' && [ + isPinned === 'end' && [ 'sticky right-0 shadow-[-4px_0_8px_-4px_rgba(0,0,0,0.1)]', isSelected ? 'bg-primary/10' : 'bg-background', ], - isPinned === 'left' && [ + isPinned === 'start' && [ 'sticky left-0', isSelected ? 'bg-primary/10' : 'bg-background', ], @@ -177,9 +187,9 @@ export function DataTable({ colSpan={header.colSpan} className={cn( 'relative', - isPinned === 'right' && + isPinned === 'end' && 'sticky right-0 z-20 bg-background shadow-[-4px_0_8px_-4px_rgba(0,0,0,0.1)]', - isPinned === 'left' && 'sticky left-0 z-20 bg-background', + isPinned === 'start' && 'sticky left-0 z-20 bg-background', )} style={{ width: header.getSize() }} > @@ -211,11 +221,11 @@ export function DataTable({ key={cell.id} className={cn( 'overflow-hidden', - isPinned === 'right' && [ + isPinned === 'end' && [ 'sticky right-0 shadow-[-4px_0_8px_-4px_rgba(0,0,0,0.1)]', isSelected ? 'bg-primary/10' : 'bg-background', ], - isPinned === 'left' && [ + isPinned === 'start' && [ 'sticky left-0', isSelected ? 'bg-primary/10' : 'bg-background', ], diff --git a/packages/duron-dashboard/src/components/ui/calendar.tsx b/packages/duron-dashboard/src/components/ui/calendar.tsx index a7b8edf..e144758 100644 --- a/packages/duron-dashboard/src/components/ui/calendar.tsx +++ b/packages/duron-dashboard/src/components/ui/calendar.tsx @@ -73,7 +73,7 @@ function Calendar({ : 'rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5', defaultClassNames.caption_label, ), - table: 'w-full border-collapse', + month_grid: cn('w-full border-collapse', defaultClassNames.month_grid), weekdays: cn('flex', defaultClassNames.weekdays), weekday: cn( 'text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none', diff --git a/packages/duron-dashboard/src/contexts/layout-context.tsx b/packages/duron-dashboard/src/contexts/layout-context.tsx index 520b06c..b82bc87 100644 --- a/packages/duron-dashboard/src/contexts/layout-context.tsx +++ b/packages/duron-dashboard/src/contexts/layout-context.tsx @@ -1,6 +1,6 @@ 'use client' -import type { ColumnSizingState, VisibilityState } from '@tanstack/react-table' +import type { ColumnSizingState, ColumnVisibilityState } from '@tanstack/react-table' import { createContext, type ReactNode, @@ -27,7 +27,7 @@ interface MobileLayout { interface JobsTableConfig { /** Column visibility state */ - columnVisibility: VisibilityState + columnVisibility: ColumnVisibilityState /** Column sizing state */ columnSizing: ColumnSizingState } @@ -49,14 +49,14 @@ interface LayoutContextValue { setDesktopHorizontalSizes: (sizes: number[]) => void setDesktopVerticalSizes: (sizes: number[]) => void setMobileVerticalSizes: (sizes: number[]) => void - setJobsTableColumnVisibility: (visibility: VisibilityState) => void + setJobsTableColumnVisibility: (visibility: ColumnVisibilityState) => void setJobsTableColumnSizing: (sizing: ColumnSizingState) => void } const STORAGE_KEY = 'duron-layout-config' /** Default column visibility for the jobs table */ -const DEFAULT_JOBS_TABLE_COLUMN_VISIBILITY: VisibilityState = { +const DEFAULT_JOBS_TABLE_COLUMN_VISIBILITY: ColumnVisibilityState = { 'Client ID': false, } @@ -191,7 +191,7 @@ export function LayoutProvider({ children }: { children: ReactNode }) { }) }, []) - const setJobsTableColumnVisibility = useCallback((visibility: VisibilityState) => { + const setJobsTableColumnVisibility = useCallback((visibility: ColumnVisibilityState) => { setConfig((prev) => { const next = { ...prev, jobsTable: { ...prev.jobsTable, columnVisibility: visibility } } saveConfig(next) diff --git a/packages/duron-dashboard/src/hooks/use-data-table.ts b/packages/duron-dashboard/src/hooks/use-data-table.ts index d1635bf..4a63e0e 100644 --- a/packages/duron-dashboard/src/hooks/use-data-table.ts +++ b/packages/duron-dashboard/src/hooks/use-data-table.ts @@ -3,20 +3,14 @@ import { type ColumnFiltersState, type ColumnSizingState, - getCoreRowModel, - getFacetedMinMaxValues, - getFacetedRowModel, - getFacetedUniqueValues, - getFilteredRowModel, - getPaginationRowModel, - getSortedRowModel, + type ColumnVisibilityState, type PaginationState, + type RowData, type SortingState, type TableOptions, type TableState, type Updater, - useReactTable, - type VisibilityState, + useTable, } from '@tanstack/react-table' import { parseAsArrayOf, @@ -30,6 +24,7 @@ import { import * as React from 'react' import { useDebouncedCallback } from '@/hooks/use-debounced-callback' +import { type DataTableFeatures, dataTableFeatures } from '@/lib/data-table-features' import { getSortingStateParser } from '@/lib/parsers' import type { ExtendedColumnSort, QueryKeys } from '@/types/data-table' @@ -42,20 +37,20 @@ const ARRAY_SEPARATOR = ',' const DEBOUNCE_MS = 300 const THROTTLE_MS = 50 -interface UseDataTableProps +interface UseDataTableProps extends Omit< - TableOptions, + TableOptions, + | 'features' | 'pageCount' - | 'getCoreRowModel' | 'manualFiltering' | 'manualPagination' | 'manualSorting' | 'onColumnVisibilityChange' | 'onColumnSizingChange' >, - Required, 'pageCount'>> { - initialState?: Omit, 'sorting'> & { + Required, 'pageCount'>> { + initialState?: Omit>, 'sorting'> & { sorting?: ExtendedColumnSort[] } queryKeys?: Partial @@ -68,12 +63,12 @@ interface UseDataTableProps shallow?: boolean startTransition?: React.TransitionStartFunction /** Callback when column visibility changes */ - onColumnVisibilityChange?: (visibility: VisibilityState) => void + onColumnVisibilityChange?: (visibility: ColumnVisibilityState) => void /** Callback when column sizing changes */ onColumnSizingChange?: (sizing: ColumnSizingState) => void } -export function useDataTable(props: UseDataTableProps) { +export function useDataTable(props: UseDataTableProps) { const { columns, pageCount = -1, @@ -110,12 +105,12 @@ export function useDataTable(props: UseDataTableProps) { [history, scroll, shallow, throttleMs, debounceMs, clearOnDefault, startTransition], ) - const [columnVisibility, setColumnVisibilityState] = React.useState( + const [columnVisibility, setColumnVisibilityState] = React.useState( initialState?.columnVisibility ?? {}, ) const setColumnVisibility = React.useCallback( - (updaterOrValue: React.SetStateAction) => { + (updaterOrValue: React.SetStateAction) => { setColumnVisibilityState((prev) => { const next = typeof updaterOrValue === 'function' ? updaterOrValue(prev) : updaterOrValue // Defer callback to avoid updating parent during render @@ -300,8 +295,9 @@ export function useDataTable(props: UseDataTableProps) { [debouncedSetFilterValues, filterableColumns, enableAdvancedFilter], ) - const table = useReactTable({ + const table = useTable({ ...tableProps, + features: dataTableFeatures, columns, initialState, pageCount, @@ -326,13 +322,6 @@ export function useDataTable(props: UseDataTableProps) { onColumnFiltersChange, onColumnVisibilityChange: setColumnVisibility, onColumnSizingChange: setColumnSizing, - getCoreRowModel: getCoreRowModel(), - getFilteredRowModel: getFilteredRowModel(), - getPaginationRowModel: getPaginationRowModel(), - getSortedRowModel: getSortedRowModel(), - getFacetedRowModel: getFacetedRowModel(), - getFacetedUniqueValues: getFacetedUniqueValues(), - getFacetedMinMaxValues: getFacetedMinMaxValues(), manualPagination: true, manualSorting: true, manualFiltering: true, diff --git a/packages/duron-dashboard/src/lib/data-table-features.ts b/packages/duron-dashboard/src/lib/data-table-features.ts new file mode 100644 index 0000000..c555551 --- /dev/null +++ b/packages/duron-dashboard/src/lib/data-table-features.ts @@ -0,0 +1,68 @@ +import { + columnFacetingFeature, + columnFilteringFeature, + columnOrderingFeature, + columnPinningFeature, + columnResizingFeature, + columnSizingFeature, + columnVisibilityFeature, + createFacetedMinMaxValues, + createFacetedRowModel, + createFacetedUniqueValues, + createFilteredRowModel, + createPaginatedRowModel, + createSortedRowModel, + filterFn_arrIncludes, + filterFn_equals, + filterFn_includesString, + filterFn_inDateRange, + filterFn_inNumberRange, + filterFn_weakEquals, + rowPaginationFeature, + rowSelectionFeature, + rowSortingFeature, + tableFeatures, +} from '@tanstack/react-table' + +/** + * TanStack Table v9 features used by the dashboard data tables. + * + * The table runs with manual pagination, sorting and filtering (the server does that work), + * so the filtered, sorted and paginated row models pass rows through unchanged. They are + * registered to keep the v8 setup, where the faceted row models read the filtered one. + * + * filterFns holds the built-ins that a column's 'auto' filter resolves to. Nothing filters on + * the client, but setColumnFilters/setFilterValue ask the resolved function's autoRemove hook + * whether a value clears the filter (v8 always had these built-ins; without them v9 warns and + * only removes undefined or empty strings). No sort functions are needed: sorting is manual. + * + * columnOrderingFeature provides column.getIsFirstColumn/getIsLastColumn (pinning styles). + */ +export const dataTableFeatures = tableFeatures({ + columnFilteringFeature, + columnFacetingFeature, + rowSortingFeature, + rowPaginationFeature, + rowSelectionFeature, + columnVisibilityFeature, + columnOrderingFeature, + columnPinningFeature, + columnSizingFeature, + columnResizingFeature, + filteredRowModel: createFilteredRowModel(), + sortedRowModel: createSortedRowModel(), + paginatedRowModel: createPaginatedRowModel(), + facetedRowModel: createFacetedRowModel(), + facetedUniqueValues: createFacetedUniqueValues(), + facetedMinMaxValues: createFacetedMinMaxValues(), + filterFns: { + includesString: filterFn_includesString, + inNumberRange: filterFn_inNumberRange, + equals: filterFn_equals, + arrIncludes: filterFn_arrIncludes, + inDateRange: filterFn_inDateRange, + weakEquals: filterFn_weakEquals, + }, +}) + +export type DataTableFeatures = typeof dataTableFeatures diff --git a/packages/duron-dashboard/src/lib/data-table.ts b/packages/duron-dashboard/src/lib/data-table.ts index eba15cb..c4f5681 100644 --- a/packages/duron-dashboard/src/lib/data-table.ts +++ b/packages/duron-dashboard/src/lib/data-table.ts @@ -1,29 +1,30 @@ -import type { Column } from '@tanstack/react-table' +import type { Column, RowData } from '@tanstack/react-table' import { dataTableConfig } from '@/config/data-table.ts' +import type { DataTableFeatures } from '@/lib/data-table-features' import type { ExtendedColumnFilter, FilterOperator, FilterVariant } from '@/types/data-table.ts' -export function getCommonPinningStyles({ +export function getCommonPinningStyles({ column, withBorder = false, }: { - column: Column + column: Column withBorder?: boolean }): React.CSSProperties { const isPinned = column.getIsPinned() - const isLastLeftPinnedColumn = isPinned === 'left' && column.getIsLastColumn('left') - const isFirstRightPinnedColumn = isPinned === 'right' && column.getIsFirstColumn('right') + const isLastStartPinnedColumn = isPinned === 'start' && column.getIsLastColumn('start') + const isFirstEndPinnedColumn = isPinned === 'end' && column.getIsFirstColumn('end') return { boxShadow: withBorder - ? isLastLeftPinnedColumn + ? isLastStartPinnedColumn ? '-4px 0 4px -4px var(--border) inset' - : isFirstRightPinnedColumn + : isFirstEndPinnedColumn ? '4px 0 4px -4px var(--border) inset' : undefined : undefined, - left: isPinned === 'left' ? `${column.getStart('left')}px` : undefined, - right: isPinned === 'right' ? `${column.getAfter('right')}px` : undefined, + left: isPinned === 'start' ? `${column.getStart('start')}px` : undefined, + right: isPinned === 'end' ? `${column.getAfter('end')}px` : undefined, position: isPinned ? 'sticky' : 'relative', background: isPinned ? 'hsl(var(--background))' : undefined, width: column.getSize(), @@ -52,7 +53,7 @@ export function getDefaultFilterOperator(filterVariant: FilterVariant) { return operators[0]?.value ?? (filterVariant === 'text' ? 'iLike' : 'eq') } -export function getValidFilters( +export function getValidFilters( filters: ExtendedColumnFilter[], ): ExtendedColumnFilter[] { return filters.filter( diff --git a/packages/duron-dashboard/src/types/data-table.ts b/packages/duron-dashboard/src/types/data-table.ts index 821b582..9aa54d9 100644 --- a/packages/duron-dashboard/src/types/data-table.ts +++ b/packages/duron-dashboard/src/types/data-table.ts @@ -1,16 +1,21 @@ -import type { ColumnSort, Row, RowData } from '@tanstack/react-table' +import type { CellData, ColumnSort, Row, RowData, TableFeatures } from '@tanstack/react-table' import type { DataTableConfig } from '@/config/data-table' +import type { DataTableFeatures } from '@/lib/data-table-features' import type { FilterItemSchema } from '@/lib/parsers' declare module '@tanstack/react-table' { // oxlint-disable-next-line no-unused-vars - interface TableMeta { + interface TableMeta { queryKeys?: QueryKeys } // oxlint-disable-next-line no-unused-vars - interface ColumnMeta { + interface ColumnMeta< + in out TFeatures extends TableFeatures, + in out TData extends RowData, + TValue extends CellData = CellData, + > { label?: string placeholder?: string variant?: FilterVariant @@ -48,7 +53,7 @@ export interface ExtendedColumnFilter extends FilterItemSchema { id: Extract } -export interface DataTableRowAction { - row: Row +export interface DataTableRowAction { + row: Row variant: 'update' | 'delete' } diff --git a/packages/duron-dashboard/src/views/jobs-table.tsx b/packages/duron-dashboard/src/views/jobs-table.tsx index 4866d10..614664d 100644 --- a/packages/duron-dashboard/src/views/jobs-table.tsx +++ b/packages/duron-dashboard/src/views/jobs-table.tsx @@ -15,6 +15,7 @@ import { useJobParams } from '@/hooks/use-job-params' import { useJobsPolling } from '@/hooks/use-jobs-polling' import { useActions, useJobs } from '@/lib/api' import type { ActionStats, Job, JobStatus } from '@/lib/api' +import type { DataTableFeatures } from '@/lib/data-table-features' import { formatExpirationWindow, formatMs } from '@/lib/duration' import { formatDate } from '@/lib/format' @@ -45,12 +46,12 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { })) }, [actionsData]) - const columns = useMemo[]>( + const columns = useMemo[]>( () => [ { id: 'ID', accessorKey: 'id', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell }) => { @@ -73,7 +74,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'actionName', accessorKey: 'actionName', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell }) =>
{cell.getValue()}
, @@ -88,7 +89,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'description', accessorKey: 'description', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell }) => { @@ -117,7 +118,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'status', accessorKey: 'status', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell }) => { @@ -141,7 +142,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'startedAt', accessorKey: 'startedAt', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell }) => { @@ -158,7 +159,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'finishedAt', accessorKey: 'finishedAt', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell }) => { @@ -175,7 +176,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'duration', accessorKey: 'durationMs', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ row }) => { @@ -203,7 +204,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'Expires At', accessorKey: 'expiresAt', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell, row }) => { @@ -232,7 +233,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'Client ID', accessorKey: 'clientId', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell }) => { @@ -245,7 +246,7 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { { id: 'createdAt', accessorKey: 'createdAt', - header: ({ column }: { column: Column }) => ( + header: ({ column }: { column: Column }) => ( ), cell: ({ cell }) => { @@ -293,7 +294,8 @@ export function JobsTable({ onJobSelect, selectedJobId }: JobsTableProps) { columnVisibility: config.jobsTable.columnVisibility, columnSizing: config.jobsTable.columnSizing, columnPinning: { - right: ['select'], + start: [], + end: ['select'], }, }, state: { From b8012d3102b7a390016e54633708af1afe34a047 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 11:46:57 -0300 Subject: [PATCH 044/100] chore(docs): vite 8, TanStack Start 1.170, fumadocs 16.19/mdx 15, lucide-static 1 - vite 7 -> 8, @vitejs/plugin-react 5 -> 6, TanStack Start/Router/ static-server-functions 1.168/1.170.18/1.167.19 -> 1.170.0/1.170.46/ 1.167.44 (Start >= 1.169 requires Vite 8), fumadocs-core/ui 16.2.0/16.1.0 -> 16.19.8 (exact; ui pins core exactly), fumadocs-mdx 14.0.3 -> 15.6.4, lucide-static 0.552 -> 1.84 (all 13 frontmatter icons still resolve). - vite-tsconfig-paths removed: Vite 8 resolves tsconfig paths natively (resolve.tsconfigPaths) and warns when the plugin is present. - vite.config: import.meta.dirname and an explicit ./source.config.ts extension (Vite 8 native config loader warnings); tsconfig enables allowImportingTsExtensions for that import (noEmit). - Start 1.169 removed createServerFn().inputValidator(): use .validator(). - fumadocs-mdx 15: createClientLoader so type-checks; page tree cast to PageTree.Root. - fumadocs-core 16.14 moved built-in search from Orama to ZBSearch and 16.17 deprecated useDocsSearch: the dialog uses useStaticSearch() and @orama/orama is no longer a dependency. - fumadocs-ui HomeLayout's root now contains the navbar, so the home page centers its content in a flex-1 wrapper (as the upstream template does). Styling HomeLayout itself centered the navbar into the page. --- bun.lock | 346 +++++++++++------------- packages/docs/package.json | 22 +- packages/docs/src/components/search.tsx | 23 +- packages/docs/src/routes/docs/$.tsx | 7 +- packages/docs/src/routes/index.tsx | 30 +- packages/docs/tsconfig.json | 1 + packages/docs/vite.config.ts | 10 +- 7 files changed, 205 insertions(+), 234 deletions(-) diff --git a/bun.lock b/bun.lock index c248822..c4dc4b7 100644 --- a/bun.lock +++ b/bun.lock @@ -16,17 +16,16 @@ "packages/docs": { "name": "docs", "dependencies": { - "@orama/orama": "^3.1.18", - "@tanstack/react-router": "^1.134.12", - "@tanstack/react-start": "^1.134.12", - "@tanstack/start-static-server-functions": "^1.134.12", - "fumadocs-core": "16.2.0", - "fumadocs-mdx": "14.0.3", - "fumadocs-ui": "16.1.0", - "lucide-static": "^0.552.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-start": "^1.170.0", + "@tanstack/start-static-server-functions": "^1.167.44", + "fumadocs-core": "16.19.8", + "fumadocs-mdx": "15.6.4", + "fumadocs-ui": "16.19.8", + "lucide-static": "^1.84.0", "react": "^19.3.1", "react-dom": "^19.3.1", - "vite": "^7.3.8", + "vite": "^8.4.0", }, "devDependencies": { "@tailwindcss/vite": "^4.3.5", @@ -34,11 +33,10 @@ "@types/node": "^26.6.11", "@types/react": "^19.3.3", "@types/react-dom": "^19.3.0", - "@vitejs/plugin-react": "^5.2.0", + "@vitejs/plugin-react": "^6.3.0", "serve": "^14.2.8", "tailwindcss": "^4.3.5", "typescript": "^7.0.2", - "vite-tsconfig-paths": "^5.1.4", }, }, "packages/duron": { @@ -183,8 +181,6 @@ "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.16", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.16" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-jzdW9nRNJXbNAfcbtfZA75vcQK8c/PRniwNL1KIQukiptryb5JlCl+nwi3idOSj611tMgiZxb9PuKg1FI0BvVQ=="], - "@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@7.29.7", "", {}, "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw=="], - "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.15", "", {}, "sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w=="], "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], @@ -195,10 +191,6 @@ "@babel/parser": ["@babel/parser@7.29.15", "", { "dependencies": { "@babel/types": "^7.29.15" }, "bin": "./bin/babel-parser.js" }, "sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA=="], - "@babel/plugin-transform-react-jsx-self": ["@babel/plugin-transform-react-jsx-self@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw=="], - - "@babel/plugin-transform-react-jsx-source": ["@babel/plugin-transform-react-jsx-source@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q=="], - "@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="], "@babel/traverse": ["@babel/traverse@7.29.16", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.16", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.15", "@babel/template": "^7.29.7", "@babel/types": "^7.29.15", "debug": "^4.3.1" } }, "sha512-a16ah9dTLOLUq5BL7NElJ7keefg/276vgfTfExDf1PizddYboqRnQXDTooVPb0VArIqrKe8KLlghnTxlZFEZtQ=="], @@ -221,57 +213,57 @@ "@electric-sql/pglite": ["@electric-sql/pglite@0.5.17", "", {}, "sha512-8SvKjiUjaU+0O0dbxjOfN+jXz14TEqDWbwDkYOW1aQ11y/ph2JvFVI27ABBo5nfw+ZfSqy4hKCNlbnbB1TDE+g=="], - "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="], + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], - "@esbuild/android-arm": ["@esbuild/android-arm@0.27.7", "", { "os": "android", "cpu": "arm" }, "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ=="], + "@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="], - "@esbuild/android-arm64": ["@esbuild/android-arm64@0.27.7", "", { "os": "android", "cpu": "arm64" }, "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ=="], + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.2", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="], - "@esbuild/android-x64": ["@esbuild/android-x64@0.27.7", "", { "os": "android", "cpu": "x64" }, "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg=="], + "@esbuild/android-x64": ["@esbuild/android-x64@0.28.2", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="], - "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.27.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw=="], + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="], - "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.27.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ=="], + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="], - "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.27.7", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w=="], + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="], - "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.27.7", "", { "os": "freebsd", "cpu": "x64" }, "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ=="], + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="], - "@esbuild/linux-arm": ["@esbuild/linux-arm@0.27.7", "", { "os": "linux", "cpu": "arm" }, "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA=="], + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.2", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="], - "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.27.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A=="], + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="], - "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.27.7", "", { "os": "linux", "cpu": "ia32" }, "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg=="], + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.2", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="], - "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q=="], + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="], - "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw=="], + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="], - "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.27.7", "", { "os": "linux", "cpu": "ppc64" }, "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ=="], + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="], - "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ=="], + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="], - "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.27.7", "", { "os": "linux", "cpu": "s390x" }, "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw=="], + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="], - "@esbuild/linux-x64": ["@esbuild/linux-x64@0.27.7", "", { "os": "linux", "cpu": "x64" }, "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA=="], + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.2", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="], - "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.27.7", "", { "os": "none", "cpu": "arm64" }, "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w=="], + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="], - "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.27.7", "", { "os": "none", "cpu": "x64" }, "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw=="], + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.2", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="], - "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.27.7", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A=="], + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="], - "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.27.7", "", { "os": "openbsd", "cpu": "x64" }, "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg=="], + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="], - "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.27.7", "", { "os": "none", "cpu": "arm64" }, "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw=="], + "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="], - "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.27.7", "", { "os": "sunos", "cpu": "x64" }, "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA=="], + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="], - "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.27.7", "", { "os": "win32", "cpu": "arm64" }, "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA=="], + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="], - "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.27.7", "", { "os": "win32", "cpu": "ia32" }, "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw=="], + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="], - "@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.7", "", { "os": "win32", "cpu": "x64" }, "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg=="], + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], "@floating-ui/core": ["@floating-ui/core@1.8.0", "", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="], @@ -281,7 +273,11 @@ "@floating-ui/utils": ["@floating-ui/utils@0.2.12", "", {}, "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww=="], - "@formatjs/intl-localematcher": ["@formatjs/intl-localematcher@0.6.2", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA=="], + "@fuma-translate/react": ["@fuma-translate/react@1.0.2", "", { "peerDependencies": { "@types/react": "*", "react": "^19.2.0", "react-dom": "^19.2.0" }, "optionalPeers": ["@types/react"] }, "sha512-uOiOtBx3nRXR8Nu1GzBf1tApgF1FErDBTHxRIAQeyQdyOoZbrNRN6H4kDCWObY4qyGeGbHydG0DHzgeUgFDMIw=="], + + "@fumadocs/tailwind": ["@fumadocs/tailwind@0.1.5", "", { "peerDependencies": { "tailwindcss": "^4.0.0" }, "optionalPeers": ["tailwindcss"] }, "sha512-ohzmuLTfNNRvP6B/Xx31lWJ58xu40NcmI+6mc/jivYeOoofnmdxBKu5gCErTgOE/mUqyVv4GvYeqd9FhoLHphg=="], + + "@fumari/image-size": ["@fumari/image-size@0.1.1", "", {}, "sha512-iaiV2wyzJ4mW358NX4CX3yGit+WjKYzpaQ+rldK9BjL/5jFpeV6ruWnZVq7MEyMn3Gd0DLi8g/79NZAAQaGscw=="], "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], @@ -329,8 +325,6 @@ "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.45.0", "", {}, "sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw=="], - "@orama/orama": ["@orama/orama@3.1.18", "", {}, "sha512-a61ljmRVVyG5MC/698C8/FfFDw5a8LOIvyOLW5fztgUXqUpc1jOfQzOitSCbge657OgXXThmY3Tk8fpiDb4UcA=="], - "@oven/bun-darwin-aarch64": ["@oven/bun-darwin-aarch64@1.4.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4MIFXHmctH2EhAxLXm2/qxNtv17dFtLJylvaOCsrgq6KSqHTs6eW5YSrJjRbJxYUJaR901fsN8JfZOa+CsWpWQ=="], "@oven/bun-darwin-x64": ["@oven/bun-darwin-x64@1.4.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-qkLPMGHZM9NI6CeHTWwVezzmlo6cC4Ta7yUAjYIWXS366qQcOlcp75t2uZyiuVRBMPS0h9qE0tCcvCHGaFqjJg=="], @@ -355,6 +349,8 @@ "@oven/bun-windows-x64": ["@oven/bun-windows-x64@1.4.5", "", { "os": "win32", "cpu": "x64" }, "sha512-FNvply651vcE/GHgNWz6mZvhmkwBuu8Hw54oNzA+CQog+HW+542rXQmZqNHRkFxazD9L3xi+iTtvO3engAgJfw=="], + "@oxc-project/types": ["@oxc-project/types@0.160.0", "", {}, "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA=="], + "@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.80.0", "", { "os": "android", "cpu": "arm" }, "sha512-IKgbKL684l/0zb1yAIr7YkqmUsZmO6O02ELkb+78SLFsDJAJxCtPtLypHGUGNpeOrsdIHXIZMxYGo/9QYSHuhg=="], "@oxfmt/binding-android-arm64": ["@oxfmt/binding-android-arm64@0.80.0", "", { "os": "android", "cpu": "arm64" }, "sha512-fGqMAgBeKlE1CsnpKNuIlahJmJgYxLrOiwacsYdqK0fv8hu7flDAQN0MTa5joCoc0gfLV/RJKAKp0b6FsODGYQ=="], @@ -517,75 +513,53 @@ "@radix-ui/rect": ["@radix-ui/rect@1.1.3", "", {}, "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw=="], - "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.3", "", {}, "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q=="], - - "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.69.1", "", { "os": "android", "cpu": "arm" }, "sha512-sCxEAuzIiiqKvOqniRjG7hA5XdxnjGI75fizhb8WoycNP+HIKtO/BQGtVCxtlWZD8+xI+WvtHYXKDiwlf8skDg=="], - - "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.69.1", "", { "os": "android", "cpu": "arm64" }, "sha512-jXds5O/FbKFEblo7pZzaiqJk8mK0A2jH3sxZy0t8XyyGT0L6NGPkURBlCySOQj7usO7o8F1oeKdcGISQjIC4rA=="], - - "@rollup/rollup-android-x64": ["@rollup/rollup-android-x64@4.69.1", "", { "os": "android", "cpu": "x64" }, "sha512-OsNys8AqzoeyfCCHxB8yyOGOlg2IsCqB6jZG3V7lP1k42n96+D/5weBUxAfDr4F9VgvDaT1KQZCpCokw4n6+pw=="], - - "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.69.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-lMId5BFhUyDt/PsbeNkuU5mRz8pT8z3uH7UEVNEognzAcCeURGE6wPHCYDGJxk26DEs+hMLgHorbcAVKGctCNg=="], - - "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.69.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-LXGbkadbp+YtMyeFz4+OUtEU9jJs/DFtlWb6+xXig1OnM6UQBmHAO1TxKsO1prbWB8/bKzGZl0dusz3hdASZxg=="], - - "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.69.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-1TqVjgaRHdf9Lt8VDUrGGp0jnRcDPz+bQzXinLec8b45HdE+xhMWQCfL69aLhGZcPGXLQ/d5GW0Hubl/7CSSzQ=="], - - "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.69.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-BiHfDJHCa2esEDIOJCI2uyakP8Ln9iaUrKdVb0+nUMWXcaoTvJT5ZURhe86pVp8G7QQ3iNQfHWOfBDLJeOZVgQ=="], - - "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.69.1", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-/JYdUwNaWv+qFZEtxBUrbM5eiJx1DplFtTqN0Buc9gdOJBw7aKX5vqpCk4823BoLP0s4A9DYg2qEhOZDwsw/Lg=="], - - "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.69.1", "", { "os": "linux", "cpu": "arm", "libc": "musl" }, "sha512-7AATkTU0K8z8sIguTsUKO2i7OL8Q/r//1FfWxtwE5c6CzoIp03k0LP9JAAjXl7L520jbWt7TcnJ897e1XBumYw=="], - - "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.69.1", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-fgcL+1NuR6sc1W48xMoDe0wyAWGrbMazJr0XWkr2HmFf4RX/D5nI7H6qx63juiJd3h72qfxIXaLHcTszMq1XxQ=="], + "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.3.4", "", { "os": "android", "cpu": "arm" }, "sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg=="], - "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.69.1", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-QEQcLTo84tZ1Z9s8vwuCT9KsQmxy+WGBssFTZU8BODHR4f9uywy0R7veeAipnY9JPAI+V45ZDJ89ceoYLLX4SA=="], + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.3.4", "", { "os": "android", "cpu": "arm64" }, "sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ=="], - "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.69.1", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-102cDq5JJvbxdtUDb5LwzOEjq0yStgKHda9SEg3d33oZGC5xkNIdLKUDqYGtR1SJN1vGV3QtQiBxUZdNopC1Hw=="], + "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.3.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q=="], - "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.69.1", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-u3Stzh5CjPKmLnrdCoxk6EALdkAlxic6TSvgl/+VWMUgdOw12iq1FtTlmbDkxsZKmyKz/c/MxW5Qjqbf8oz+nw=="], + "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.3.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q=="], - "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.69.1", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-swxB3KVxsUisFEIltDUi9TzdfeJcDfK+UPAtSwYMxL2Vb66GenjayIMkwZ/63E6c/YXXLlD5XWrAlvQwzwVopg=="], + "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.3.4", "", { "os": "freebsd", "cpu": "x64" }, "sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg=="], - "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.69.1", "", { "os": "linux", "cpu": "ppc64", "libc": "musl" }, "sha512-PjZLbzl5r+nzSwxqY01lTxB3BjfsuExdBmBGKR1ZVZkXGaYSovLtfMmWzmUid6wmfJB8kXAkBruNxZ3TsSNQ9w=="], + "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.3.4", "", { "os": "linux", "cpu": "arm" }, "sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA=="], - "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.69.1", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-jfxumKunDjw0loeYY8UROvqlHj387mi+uTX17GNoJW6tNVR27Bsdo5tFT+DuK3gwVSTqRbLiI8WdeQ9ToBo/rQ=="], + "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.3.4", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw=="], - "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.69.1", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-mAq8rMA5WzZR3SssDWsYuytH+N81PN8QajlkX9fMz6HVJk8V3oYTchtsM9XLLCmg8h3/ApKo+X64+HQbOjWxyA=="], + "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.3.4", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw=="], - "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.69.1", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-pRZh+DrTUS83CYGLDkAFX9QigC9C2AwCQ93jxcZfq17W6F99LuUqwFHA9AhgZcpV9mg+2L1DiSlpX4vh/jU2jg=="], + "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.3.4", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w=="], - "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.69.1", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-Kbm4FoPozFvVHKMXzvgorwSMy7wdA2mDY/dk3gsoHNxmNz9cslSmxf1V3KgvT99v62MNOqUYS+3ospRZ2l+hoA=="], + "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.3.4", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q=="], - "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.69.1", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-RNstQiIU1ViUIrrK9irG/jA3TD2w9o9OCgcavyR0GyzM9B6KvqbCc2tnSfwY5q0f6rS2ZWpe74tZX3Q7iAsCpg=="], + "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.3.4", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ=="], - "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.69.1", "", { "os": "openbsd", "cpu": "x64" }, "sha512-tpm4c2fYArjIFYQlhXzchMT8ex9egIZuqa8L68YLIOPsPOA7Q+h+vU6Y6yf/asODtPToSJGDtUYNELPx56YsTg=="], + "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.3.4", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q=="], - "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.69.1", "", { "os": "none", "cpu": "arm64" }, "sha512-bTk0Q4MazBUJiAatuiB94cxEsh1R6SdBG8W7lxUQEoYoI+lrZK2173lImxWa1hZ8SGXCnN4TASxQj8Q5iqdGaw=="], + "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.3.4", "", { "os": "none", "cpu": "arm64" }, "sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug=="], - "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.69.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-bUDnKDQTlUWAZ+FME2Tn6MoEW2xmcfROZrqr0BKSTL4lXfepqNI0aXZVFuQb4P1KzUHnOPNesSjjALzY/fZWGg=="], + "@rolldown/binding-wasm32-wasi": ["@rolldown/binding-wasm32-wasi@1.3.4", "", { "dependencies": { "@oxc-project/types": "0.160.0" }, "cpu": "none" }, "sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA=="], - "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.69.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-jEkve8EoQY2CB8W99GM4bbi1/aAncAOIgd/d2uCf2bE1wReqyvEz11rvuq5CkXsh3MfWNF6yFVBCQRz6Do53jw=="], + "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.3.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA=="], - "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.69.1", "", { "os": "win32", "cpu": "x64" }, "sha512-xdR6tc+o1eH1EhG0dSZECD2NVGmdZE9Xobw0Fbw+K0HiiN4ZIxNbvbcsGRJjtX9cc/wRyudPKFw9n/uuRi/eYw=="], + "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.3.4", "", { "os": "win32", "cpu": "x64" }, "sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg=="], - "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.69.1", "", { "os": "win32", "cpu": "x64" }, "sha512-cD0egoYNA3Lx+HH+Eo76kr9aBvgd46fCKRU77BHIJCR2dMs01YD6HPpjUDiLc5ssdXhYQGEHt5PGn6oltVTL9Q=="], + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.1.1", "", {}, "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA=="], - "@shikijs/core": ["@shikijs/core@3.23.0", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-NSWQz0riNb67xthdm5br6lAkvpDJRTgB36fxlo37ZzM2yq0PQFFzbd8psqC2XMPgCzo1fW6cVi18+ArJ44wqgA=="], + "@shikijs/core": ["@shikijs/core@4.6.0", "", { "dependencies": { "@shikijs/primitive": "4.6.0", "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5", "hast-util-to-html": "^9.0.6" } }, "sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw=="], - "@shikijs/engine-javascript": ["@shikijs/engine-javascript@3.23.0", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-aHt9eiGFobmWR5uqJUViySI1bHMqrAgamWE1TYSUoftkAeCCAiGawPMwM+VCadylQtF4V3VNOZ5LmfItH5f3yA=="], + "@shikijs/engine-javascript": ["@shikijs/engine-javascript@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "oniguruma-to-es": "^4.3.6" } }, "sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg=="], - "@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@3.23.0", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g=="], + "@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0" } }, "sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w=="], - "@shikijs/langs": ["@shikijs/langs@3.23.0", "", { "dependencies": { "@shikijs/types": "3.23.0" } }, "sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg=="], + "@shikijs/langs": ["@shikijs/langs@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0" } }, "sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg=="], - "@shikijs/rehype": ["@shikijs/rehype@3.23.0", "", { "dependencies": { "@shikijs/types": "3.23.0", "@types/hast": "^3.0.4", "hast-util-to-string": "^3.0.1", "shiki": "3.23.0", "unified": "^11.0.5", "unist-util-visit": "^5.1.0" } }, "sha512-GepKJxXHbXFfAkiZZZ+4V7x71Lw3s0ALYmydUxJRdvpKjSx9FOMSaunv6WRLFBXR6qjYerUq1YZQno+2gLEPwA=="], + "@shikijs/primitive": ["@shikijs/primitive@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag=="], - "@shikijs/themes": ["@shikijs/themes@3.23.0", "", { "dependencies": { "@shikijs/types": "3.23.0" } }, "sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA=="], + "@shikijs/themes": ["@shikijs/themes@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0" } }, "sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ=="], - "@shikijs/transformers": ["@shikijs/transformers@3.23.0", "", { "dependencies": { "@shikijs/core": "3.23.0", "@shikijs/types": "3.23.0" } }, "sha512-F9msZVxdF+krQNSdQ4V+Ja5QemeAoTQ2jxt7nJCwhDsdF1JWS3KxIQXA3lQbyKwS3J61oHRUSv4jYWv3CkaKTQ=="], - - "@shikijs/types": ["@shikijs/types@3.23.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="], + "@shikijs/types": ["@shikijs/types@4.6.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw=="], "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.1.0", "", {}, "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ=="], @@ -625,49 +599,49 @@ "@tailwindcss/vite": ["@tailwindcss/vite@4.3.5", "", { "dependencies": { "@tailwindcss/node": "4.3.5", "@tailwindcss/oxide": "4.3.5", "tailwindcss": "4.3.5" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ=="], - "@tanstack/history": ["@tanstack/history@1.162.0", "", {}, "sha512-79pf/RkhteYZTRgcR4F9kbk84P2N8rugQJswxfIqovlbRiT3yI7eBE+5QorIrZaOKktsgzRlXh1l/du/xpl4iA=="], + "@tanstack/history": ["@tanstack/history@1.162.5", "", {}, "sha512-w1+YvwmTkwt5n8yUqEH3IWZ9DsmorCZW/EQ3KYHnqEgIkOZpH54NvW6/Epq3Dzb8H0ifIeYX8PExvrNLIH5FIA=="], "@tanstack/query-core": ["@tanstack/query-core@5.108.4", "", {}, "sha512-2Ks5dlLWz4eXJrthOyG0qW3SLt3xx0RrQmAmN0rnmogiaaOYuWiAe6HAm9KE2b2v8nig+vraNz8fsfZ6fF6zFg=="], "@tanstack/react-query": ["@tanstack/react-query@5.108.4", "", { "dependencies": { "@tanstack/query-core": "5.108.4" }, "peerDependencies": { "@types/react": "^18 || ^19", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-GlTa94kfEKTVsbzXe58rFA3GZ0ZE7N1aFtbZAfOS3XxMv8YNn4C+8rsz40LorHLazdm5PsqCroWaYAR+ZkMXMQ=="], - "@tanstack/react-router": ["@tanstack/react-router@1.170.18", "", { "dependencies": { "@tanstack/history": "1.162.0", "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "1.171.15", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-wpbGYZEp/fmz1q4bn7BD8VZ+/VZ7GBqSJv5V969pU+chP8y7dquWDmKTFMohvUegb9lg12m1uPVvD6kB2wORvQ=="], + "@tanstack/react-router": ["@tanstack/react-router@1.170.46", "", { "dependencies": { "@tanstack/history": "1.162.5", "@tanstack/react-store": "^0.11.2", "@tanstack/router-core": "1.171.39", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-ez1iNIhsPjGlaDHg3BXWs67EWVIYzB2tbopEHYDESdkO7owgkGb5de52+5Kv2v1fxdkggcNzo35bdk4arTVGQw=="], - "@tanstack/react-start": ["@tanstack/react-start@1.168.31", "", { "dependencies": { "@tanstack/react-router": "1.170.18", "@tanstack/react-start-client": "1.168.16", "@tanstack/react-start-rsc": "0.1.30", "@tanstack/react-start-server": "1.167.22", "@tanstack/router-utils": "1.162.2", "@tanstack/start-client-core": "1.170.14", "@tanstack/start-plugin-core": "1.171.23", "@tanstack/start-server-core": "1.169.17", "pathe": "^2.0.3" }, "peerDependencies": { "@rsbuild/core": "^2.0.0", "@vitejs/plugin-rsc": "*", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", "vite": ">=7.0.0" }, "optionalPeers": ["@rsbuild/core", "@vitejs/plugin-rsc", "vite"] }, "sha512-8uzryvrFQTE+N8Mw5Egzgstmo+E5FhLYknIvBuiz1vOhCAga0MGWwYS0GAMLlpySBmxc+eH1tfUJ6ZbImjgk0A=="], + "@tanstack/react-start": ["@tanstack/react-start@1.170.0", "", { "dependencies": { "@tanstack/react-router": "1.170.46", "@tanstack/react-start-client": "1.168.45", "@tanstack/react-start-rsc": "0.1.69", "@tanstack/react-start-server": "1.167.52", "@tanstack/router-utils": "1.163.0", "@tanstack/start-client-core": "1.170.39", "@tanstack/start-plugin-core": "1.173.0", "@tanstack/start-server-core": "1.169.45", "pathe": "^2.0.3" }, "peerDependencies": { "@rsbuild/core": "^2.0.5", "@vitejs/plugin-rsc": "*", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", "vite": ">=8.0.0" }, "optionalPeers": ["@rsbuild/core", "@vitejs/plugin-rsc", "vite"] }, "sha512-x0P9J8fuW5I2XtzIMIYP74Q+B/lhTPbJ8KIv88jtyxCaqcLwqBZNhxSKMpVjygGSkMt0FtiDrbItplwUlnFfDQ=="], - "@tanstack/react-start-client": ["@tanstack/react-start-client@1.168.16", "", { "dependencies": { "@tanstack/react-router": "1.170.18", "@tanstack/router-core": "1.171.15", "@tanstack/start-client-core": "1.170.14" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-1OfHgy0wpHwe2tlB3FxMeA+IMX6Il/QAMf+8UdXuimReIc2Lz3BkMLBL38k4GIxBguX9sI8EMLO5jlTZ4e1olw=="], + "@tanstack/react-start-client": ["@tanstack/react-start-client@1.168.45", "", { "dependencies": { "@tanstack/react-router": "1.170.46", "@tanstack/router-core": "1.171.39", "@tanstack/start-client-core": "1.170.39" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-DzTCJS+TVFIEs08w9RQGOEp7dtVCEIUU3y6Oay+mXOqoRk62T0olohHbNR9A4Z1my2b3hVdMjg9KG18WOckQYg=="], - "@tanstack/react-start-rsc": ["@tanstack/react-start-rsc@0.1.30", "", { "dependencies": { "@tanstack/react-router": "1.170.18", "@tanstack/router-core": "1.171.15", "@tanstack/router-utils": "1.162.2", "@tanstack/start-client-core": "1.170.14", "@tanstack/start-fn-stubs": "1.162.0", "@tanstack/start-plugin-core": "1.171.23", "@tanstack/start-server-core": "1.169.17", "@tanstack/start-storage-context": "1.167.17", "pathe": "^2.0.3" }, "peerDependencies": { "@rspack/core": ">=2.0.0-0", "@vitejs/plugin-rsc": ">=0.5.20", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", "react-server-dom-rspack": ">=0.0.2" }, "optionalPeers": ["@rspack/core", "@vitejs/plugin-rsc", "react-server-dom-rspack"] }, "sha512-JH9eUiXoXgDoSaeOMLTfa6cW7Wh/rvlqbyOH2E3ofHafkOUA8e3jyFK1fmxK7pnHPNXVTRPtsNXIGMDcek7CiQ=="], + "@tanstack/react-start-rsc": ["@tanstack/react-start-rsc@0.1.69", "", { "dependencies": { "@tanstack/react-router": "1.170.46", "@tanstack/router-core": "1.171.39", "@tanstack/router-utils": "1.163.0", "@tanstack/start-client-core": "1.170.39", "@tanstack/start-fn-stubs": "1.162.0", "@tanstack/start-plugin-core": "1.173.0", "@tanstack/start-storage-context": "1.167.41", "pathe": "^2.0.3" }, "peerDependencies": { "@rspack/core": ">=2.0.0-0", "@vitejs/plugin-rsc": ">=0.5.38", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", "react-server-dom-rspack": ">=0.1.1" }, "optionalPeers": ["@rspack/core", "@vitejs/plugin-rsc", "react-server-dom-rspack"] }, "sha512-05+5j5FXIzoh81jZzowwR9W7Cfztgy6OL+I7tZbE3C7DBv91PJu3hnpyPv5YesaVhhP216dFP8avg2i0teIalQ=="], - "@tanstack/react-start-server": ["@tanstack/react-start-server@1.167.22", "", { "dependencies": { "@tanstack/react-router": "1.170.18", "@tanstack/router-core": "1.171.15", "@tanstack/start-server-core": "1.169.17" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-eH2PeHuLfL3R5YzE9+y2FfcE4Ld1LNV2ZfrCNVPJMMJFt+9nXDaRHg9BsEmc+JkTAGzz3FKLyQEoWwpbG6Ehqg=="], + "@tanstack/react-start-server": ["@tanstack/react-start-server@1.167.52", "", { "dependencies": { "@tanstack/react-router": "1.170.46", "@tanstack/router-core": "1.171.39", "@tanstack/start-server-core": "1.169.45" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-131olF9oWx1CqZg8JYmIJbLNKqS/vN3UbYuc9a++pRtvfY67tpPmPzuYj4OXSxRAYalGW3f1yYlFozxqE1LE7w=="], - "@tanstack/react-store": ["@tanstack/react-store@0.9.3", "", { "dependencies": { "@tanstack/store": "0.9.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg=="], + "@tanstack/react-store": ["@tanstack/react-store@0.11.4", "", { "dependencies": { "@tanstack/store": "0.11.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-JAQz7LcABVRbxZ6qCd4u/KqDaqBc1qmcOWz7XBTdav1Ib363HQdihCQF1A755nDhoi9VEd6UqZ5thWVKTwIIXw=="], "@tanstack/react-table": ["@tanstack/react-table@9.3.1", "", { "dependencies": { "@tanstack/react-store": "^0.11.2", "@tanstack/table-core": "9.3.1" }, "peerDependencies": { "react": ">=18" } }, "sha512-E6Ya5TnY6EaGyZYIUqig/29Lr/gJSAubQkLJFqiWkUl5nRCr0Xr9hvJot+NiRTtG+TzGxHTiqUW3bnLtQxlHug=="], "@tanstack/react-virtual": ["@tanstack/react-virtual@3.14.30", "", { "dependencies": { "@tanstack/virtual-core": "3.19.15" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-vVq9U2WahGWue0RVPrzGuBM8QxhGKq6WV7AOUyXWR17F3kYNxHMZekYZdKm0X63/S4QZGCDlBqASvAukpXQ8GQ=="], - "@tanstack/router-core": ["@tanstack/router-core@1.171.15", "", { "dependencies": { "@tanstack/history": "1.162.0", "cookie-es": "^3.0.0", "seroval": "^1.5.4", "seroval-plugins": "^1.5.4" } }, "sha512-IILCDcLaItMZQ2jEmCABHY1Nhjjn5XUvwpQp3e4Nmu+vfg0BgYFuu/QASz2SwE2ZNbVMrvt8X/wxa+Gg5aErxA=="], + "@tanstack/router-core": ["@tanstack/router-core@1.171.39", "", { "dependencies": { "@tanstack/history": "1.162.5", "cookie-es": "^3.0.0", "seroval": "^1.6.7", "seroval-plugins": "^1.6.7" } }, "sha512-qUhoJ0meuSUqGYQbHbcJYdASr06YtK+bulbj6vtrhKYFkLgkSsZ6tXmMyym7sFxiSJSPYgasgozrL01LyyR/6A=="], - "@tanstack/router-generator": ["@tanstack/router-generator@1.167.21", "", { "dependencies": { "@babel/types": "^7.28.5", "@tanstack/router-core": "1.171.15", "@tanstack/router-utils": "1.162.2", "@tanstack/virtual-file-routes": "1.162.0", "jiti": "^2.7.0", "magic-string": "^0.30.21", "prettier": "^3.5.0", "zod": "^4.4.3" } }, "sha512-m3oXZyienj8owialdyoZ0txHQrnEx/Ra+D9kWtar5fC2cWZr5Pvxl86VY2mX5RRLC5QLKLeRGT1x4HV95wHVDQ=="], + "@tanstack/router-generator": ["@tanstack/router-generator@1.169.0", "", { "dependencies": { "@babel/types": "^7.29.8", "@tanstack/router-core": "1.171.39", "@tanstack/router-utils": "1.163.0", "@tanstack/virtual-file-routes": "1.162.0", "jiti": "^2.7.0", "magic-string": "^0.30.21", "prettier": "^3.9.6", "zod": "^4.5.4" } }, "sha512-M/ihGpncR+lngaePkk3LNA4fJFPWyfOaz/apRC7Um9QoE6rTgVBq4Tnj0q1ePBzXLUQ53gvvU5rgeDd9R32e0w=="], - "@tanstack/router-plugin": ["@tanstack/router-plugin@1.168.22", "", { "dependencies": { "@babel/core": "^7.28.5", "@babel/template": "^7.27.2", "@babel/types": "^7.28.5", "@tanstack/router-core": "1.171.15", "@tanstack/router-generator": "1.167.21", "@tanstack/router-utils": "1.162.2", "chokidar": "^5.0.0", "unplugin": "^3.0.0", "zod": "^4.4.3" }, "peerDependencies": { "@rsbuild/core": ">=1.0.2 || ^2.0.0", "@tanstack/react-router": "^1.170.18", "vite": ">=5.0.0 || >=6.0.0 || >=7.0.0 || >=8.0.0", "vite-plugin-solid": "^2.11.10 || ^3.0.0-0", "webpack": ">=5.92.0" }, "optionalPeers": ["@rsbuild/core", "@tanstack/react-router", "vite", "vite-plugin-solid", "webpack"] }, "sha512-+iBkwRWQ7dlTcL4TIKrphcToJf95DAd75FY9duiel7OFfDt8oT4tlfn713TKlgSHpZ9PVLQQQHe8ijcEseM39Q=="], + "@tanstack/router-plugin": ["@tanstack/router-plugin@1.170.0", "", { "dependencies": { "@babel/core": "^7.29.7", "@babel/template": "^7.29.7", "@babel/types": "^7.29.8", "@tanstack/router-core": "1.171.39", "@tanstack/router-generator": "1.169.0", "@tanstack/router-utils": "1.163.0", "chokidar": "^5.0.0", "unplugin": "^3.5.0", "zod": "^4.5.4" }, "peerDependencies": { "@rsbuild/core": ">=1.0.2 || ^2.0.0", "@tanstack/react-router": "^1.170.46", "vite": ">=6.0.0", "vite-plugin-solid": "^2.11.10 || ^3.0.0-0", "webpack": ">=5.92.0" }, "optionalPeers": ["@rsbuild/core", "@tanstack/react-router", "vite", "vite-plugin-solid", "webpack"] }, "sha512-F5+NputdOEdh3hGGc8bUpBTROcIM9Gx17gS4yP9OVN3eP/nfed5R1ZH75Vusutg1i6JgD8l7Pe1X4Zf8eACoGg=="], - "@tanstack/router-utils": ["@tanstack/router-utils@1.162.2", "", { "dependencies": { "@babel/generator": "^7.28.5", "@babel/parser": "^7.28.5", "@babel/types": "^7.28.5", "ansis": "^4.1.0", "babel-dead-code-elimination": "^1.0.12", "diff": "^8.0.2", "pathe": "^2.0.3", "tinyglobby": "^0.2.15" } }, "sha512-hTWqJtqIFFdvuCl8WXNyrodp2L9zo2G37xKRrcVmVRWpAB2h+U1LuRAfS4tsFTiWOIoE/B+WDVFB8JpoEdw6jQ=="], + "@tanstack/router-utils": ["@tanstack/router-utils@1.163.0", "", { "dependencies": { "@babel/generator": "^7.29.8", "@babel/parser": "^7.29.8", "@babel/types": "^7.29.8", "ansis": "^4.3.1", "babel-dead-code-elimination": "^1.0.12", "diff": "^9.0.0", "pathe": "^2.0.3", "tinyglobby": "^0.2.17" } }, "sha512-OMeFv8aRwk9Xtf3JhRmQrjtMxCj7qqfnsueASuL8xUgItoblIL9eCIyt4Zv0hk3LBp/s7NqviZgQhiAfDhJb/A=="], - "@tanstack/start-client-core": ["@tanstack/start-client-core@1.170.14", "", { "dependencies": { "@tanstack/router-core": "1.171.15", "@tanstack/start-fn-stubs": "1.162.0", "@tanstack/start-storage-context": "1.167.17", "seroval": "^1.5.4" } }, "sha512-yasBgEIFSWysL4EiFIGwp638nCoXXKiTqkc48EP2oty4OyNsZPTC1yfJ82zjq2KGkTAYtIaeMl7otqqRl1n85Q=="], + "@tanstack/start-client-core": ["@tanstack/start-client-core@1.170.39", "", { "dependencies": { "@tanstack/router-core": "1.171.39", "@tanstack/start-fn-stubs": "1.162.0", "@tanstack/start-storage-context": "1.167.41", "seroval": "^1.6.7" } }, "sha512-G0VJbZFf9/dYomQjZkWapaTjkjEI4vbk1jnxhhVtQ3nTRb3sIRc196j+S+qZcySfEV5W9TJHu4KatjSzjZZQwQ=="], "@tanstack/start-fn-stubs": ["@tanstack/start-fn-stubs@1.162.0", "", {}, "sha512-QWfUZ3Yo923tdQn38LyKMU8rcTw69zc+T4dAvgTWV4O56SqFRsGfS0lSWIMhJRwXIx/bvdi7nTUBDdZtTHtpTQ=="], - "@tanstack/start-plugin-core": ["@tanstack/start-plugin-core@1.171.23", "", { "dependencies": { "@babel/code-frame": "7.27.1", "@babel/core": "^7.28.5", "@babel/types": "^7.28.5", "@tanstack/router-core": "1.171.15", "@tanstack/router-generator": "1.167.21", "@tanstack/router-plugin": "1.168.22", "@tanstack/router-utils": "1.162.2", "@tanstack/start-server-core": "1.169.17", "exsolve": "^1.0.7", "lightningcss": "^1.32.0", "pathe": "^2.0.3", "picomatch": "^4.0.3", "seroval": "^1.5.4", "source-map": "^0.7.6", "srvx": "^0.11.9", "tinyglobby": "^0.2.15", "ufo": "^1.5.4", "vitefu": "^1.1.1", "xmlbuilder2": "^4.0.3", "zod": "^4.4.3" }, "peerDependencies": { "@rsbuild/core": "^2.0.0", "vite": ">=7.0.0" }, "optionalPeers": ["@rsbuild/core", "vite"] }, "sha512-yrt5WKW6G3miAgJR1lw9KX8qeiRhsOtKYVY7Pq4USyC0jHnSkyyModo3whEk00obCq5C1eHQMErLaPYQF57F3g=="], + "@tanstack/start-plugin-core": ["@tanstack/start-plugin-core@1.173.0", "", { "dependencies": { "@babel/code-frame": "7.29.7", "@babel/core": "^7.29.7", "@babel/types": "^7.29.8", "@jridgewell/remapping": "^2.3.5", "@tanstack/router-core": "1.171.39", "@tanstack/router-generator": "1.169.0", "@tanstack/router-plugin": "1.170.0", "@tanstack/router-utils": "1.163.0", "@tanstack/start-server-core": "1.169.45", "exsolve": "^1.1.3", "lightningcss": "^1.33.0", "pathe": "^2.0.3", "picomatch": "^4.0.7", "seroval": "^1.6.7", "source-map": "^0.7.6", "srvx": "^1.0.0", "tinyglobby": "^0.2.17", "ufo": "^1.6.4", "vitefu": "^1.1.3", "xmlbuilder2": "^4.0.3", "zod": "^4.5.4" }, "peerDependencies": { "@rsbuild/core": "^2.0.5", "vite": ">=8.0.0" }, "optionalPeers": ["@rsbuild/core", "vite"] }, "sha512-YVRc7gR+H/O93sflAvauK8IcVtxt662U6I7ZwtVCv/Uox/vGDKBGtg/Prqi/mQdWRLmY74xNILpmDx3TO9gI7g=="], - "@tanstack/start-server-core": ["@tanstack/start-server-core@1.169.17", "", { "dependencies": { "@tanstack/history": "1.162.0", "@tanstack/router-core": "1.171.15", "@tanstack/start-client-core": "1.170.14", "@tanstack/start-storage-context": "1.167.17", "fetchdts": "^0.1.6", "h3-v2": "npm:h3@2.0.1-rc.20", "seroval": "^1.5.4" } }, "sha512-u0N+PHJhMHnzfnlXYI9F+A/qweDe3E2X0mfkORPGIEkNQgvS548RA9fjwvixR2en5b848CfpEqUzwFhm/tQ40Q=="], + "@tanstack/start-server-core": ["@tanstack/start-server-core@1.169.45", "", { "dependencies": { "@tanstack/history": "1.162.5", "@tanstack/router-core": "1.171.39", "@tanstack/start-client-core": "1.170.39", "@tanstack/start-storage-context": "1.167.41", "cookie-es": "^3.0.0", "fetchdts": "^0.2.0", "seroval": "^1.6.7" } }, "sha512-fKySLUGIy7aVYR6ZRgjC19TQdsZ+q/54M9hVfHrJQQVpM/T5qq5djZ3gsqhugmrWP+gyd9qpa9D6cxRtR6CJvg=="], - "@tanstack/start-static-server-functions": ["@tanstack/start-static-server-functions@1.167.19", "", { "dependencies": { "@tanstack/start-client-core": "1.170.14", "seroval": "^1.5.4" }, "peerDependencies": { "@tanstack/react-start": "^1.168.28", "@tanstack/solid-start": "^1.168.28" }, "optionalPeers": ["@tanstack/react-start", "@tanstack/solid-start"] }, "sha512-NxzGG39VBnCbhKSJqpzM4bLCSLicPRR1HPTU/2e1AYwHPCYbYKicE1M81MDX4J/KfTyJrqXpObi2cVl9laBhPg=="], + "@tanstack/start-static-server-functions": ["@tanstack/start-static-server-functions@1.167.44", "", { "dependencies": { "@tanstack/start-client-core": "1.170.39", "seroval": "^1.6.7" }, "peerDependencies": { "@tanstack/react-start": "^1.169.4", "@tanstack/solid-start": "^1.169.4" }, "optionalPeers": ["@tanstack/react-start", "@tanstack/solid-start"] }, "sha512-E9VUC7k4Al//0VeUYBmqRIbvOU3QTdxeTeDlnlmuj3fbttlD5bLCroQC9of4ZhUUPZ3r8yhLS+9lSGsk6OTL7A=="], - "@tanstack/start-storage-context": ["@tanstack/start-storage-context@1.167.17", "", { "dependencies": { "@tanstack/router-core": "1.171.15" } }, "sha512-ntkDyGx0PE0opIlWNAMpkMb8qkjR4uyCUOfC0CiT0STM25+EcwPuwYNfDXXeVObMrTAPgsQ4yOj3xdY0Xr4ptw=="], + "@tanstack/start-storage-context": ["@tanstack/start-storage-context@1.167.41", "", { "dependencies": { "@tanstack/router-core": "1.171.39" } }, "sha512-MY+Z4cZBPbH7hjORcROMX7K3kV1X25ArFKmRbks+EukPP9UVwCXbZFVzYkTt1u0AHthvQTcpa4J9B9i0o6fEnA=="], - "@tanstack/store": ["@tanstack/store@0.9.3", "", {}, "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw=="], + "@tanstack/store": ["@tanstack/store@0.11.3", "", {}, "sha512-/Mt3h2Qe67HmRMc5SJ+8jM2Fp7O4fBbwOlS0ujUvx34KgAvkvdLSHrJatv0PJG5fbvlDsACTawMMY4ptCpVI8w=="], "@tanstack/table-core": ["@tanstack/table-core@9.3.1", "", { "dependencies": { "@tanstack/store": "^0.11.2" } }, "sha512-zQvlxSNi2qGM3L4jh85Z6hqMfdIR5qOfD9KHOU32nuKFJGN0RlJ7UvV1lsPb1fPVhpFYI0VP3jJGxLdLDpTKjQ=="], @@ -679,14 +653,6 @@ "@tokenizer/token": ["@tokenizer/token@0.3.0", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="], - "@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="], - - "@types/babel__generator": ["@types/babel__generator@7.27.0", "", { "dependencies": { "@babel/types": "^7.0.0" } }, "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg=="], - - "@types/babel__template": ["@types/babel__template@7.4.4", "", { "dependencies": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" } }, "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A=="], - - "@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="], - "@types/bun": ["@types/bun@1.4.5", "", { "dependencies": { "bun-types": "1.4.5" } }, "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q=="], "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], @@ -757,10 +723,36 @@ "@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="], - "@vitejs/plugin-react": ["@vitejs/plugin-react@5.2.0", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw=="], + "@vitejs/plugin-react": ["@vitejs/plugin-react@6.3.0", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", "babel-plugin-react-compiler": "^1.0.0", "oxc-transform-react": ">=0.152.0 <0.157.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler", "oxc-transform-react"] }, "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw=="], "@vscode/diff": ["@vscode/diff@0.0.2-145", "", {}, "sha512-atPcmNrAU4B8OsbrmqYlHbZREt//m8z52o400YA8uuvq3Be5wnmIhLoLqhMum7Jv7kRC0FE+m3WAUbaZF681wg=="], + "@yuku-core/binding-android-arm64": ["@yuku-core/binding-android-arm64@0.19.0", "", { "os": "android", "cpu": "arm64" }, "sha512-wdL2XmTiZixAOaHk9Z0JJZ8u9Qm8d333Zjpc6gaxXFX+UR5BlsfxZ7a2+2Rm71pamppsPYGUGFq2oVLbh6DISw=="], + + "@yuku-core/binding-darwin-arm64": ["@yuku-core/binding-darwin-arm64@0.19.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-7sNJa6XJhyetnTy64jw3NEi4YgUcezHk1G5GH9FSvXAuC8wIlbaOwT9lgq5qo5sspjrZJQlBR1TWflP49uRpMw=="], + + "@yuku-core/binding-darwin-x64": ["@yuku-core/binding-darwin-x64@0.19.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-pTC7dYEc59isdyizc3nsuyFNBu2LU5wMYZ1be6UMr59PY/AJNtO1aBLWV0MgL/z7C1nv/2sX4TNjGgKLoeevJw=="], + + "@yuku-core/binding-freebsd-x64": ["@yuku-core/binding-freebsd-x64@0.19.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-xrZjF6XOEwyLOiDIfrwDdRCS6ghxcJeirNC1KivQhVcUwlRonaU79S3/Uiyx3lBylPnT8qKJ3/aMT+H52nGTJQ=="], + + "@yuku-core/binding-linux-arm-gnu": ["@yuku-core/binding-linux-arm-gnu@0.19.0", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-0OyIH53C0I1CbADHn9FSdCfX5qbpeLwJhmOVhonFJNYheybOnkSJ50qGMfTJIb8y5zrwqvLs7FVBvz6Fk8maZg=="], + + "@yuku-core/binding-linux-arm-musl": ["@yuku-core/binding-linux-arm-musl@0.19.0", "", { "os": "linux", "cpu": "arm", "libc": "musl" }, "sha512-z/iPfkCOCSXE34VXNt0uP1ORSW+4mEa9b5CiJcWZeqZH08g49bFU/jRM2T04f+Wpw5mJ6HIzNBiojxeAbrHjeg=="], + + "@yuku-core/binding-linux-arm64-gnu": ["@yuku-core/binding-linux-arm64-gnu@0.19.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-jLNTi+gzaRwBJ+gwhCJ+rDb5dmx/8hEBx93UWd7hjMSqPTL1D1wvVSvXVAldV5kALvju7b0/m51EHEhs4+I1fA=="], + + "@yuku-core/binding-linux-arm64-musl": ["@yuku-core/binding-linux-arm64-musl@0.19.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-YwyPIdW/rN2Fmv0MTFWi47FaB3F9g+2b+sJISyAw83Yd60RWH4T3Nx6XkAHHVN+uKJNBAd6So7/BVihSiFYvuQ=="], + + "@yuku-core/binding-linux-x64-gnu": ["@yuku-core/binding-linux-x64-gnu@0.19.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-/vskaAXVX3ESR43FiTdfiYS7z1b9uoQJwVQ/0RgUHgN2sWoAyCZs+aX4CgU7eKGIHTVfp9VFwv+c+2XchYiEtQ=="], + + "@yuku-core/binding-linux-x64-musl": ["@yuku-core/binding-linux-x64-musl@0.19.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-FuXL5igeSKib9Rye02TdH+D6SQezTyGxIATMu1Qsn/QywrzwpGl35OLpS2C1x5vpGLeVE2XgiLd5mVPFHmIglQ=="], + + "@yuku-core/binding-win32-arm64": ["@yuku-core/binding-win32-arm64@0.19.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-YuJAe7zEKT1Xa7LuHlhGJpPnYQeVtvo0rZvNjJRqkH0hQGOw4C8QeP30Tg5VKGzZfo2x8CjhjEhKt4TmLwfmdg=="], + + "@yuku-core/binding-win32-x64": ["@yuku-core/binding-win32-x64@0.19.0", "", { "os": "win32", "cpu": "x64" }, "sha512-o8iY/mXwlRkedp0LNTr4+TEfXTPQwoNZmv6k+1WIAd1ZXEn8xJJTBCtB0osaVvdZo/x/cNmV16UrWrrGpM5Mvw=="], + + "@yuku-toolchain/types": ["@yuku-toolchain/types@0.19.0", "", {}, "sha512-tFkNbsP4WXX9UMUC5syJGdK9dPMLK0PPaIuXCcCYH75sZ8MrebfBZ2XvCILRTw8AgLivSSCfDa4R67iYBDa4Kg=="], + "@zeit/schemas": ["@zeit/schemas@2.36.0", "", {}, "sha512-7kjMwcChYEzMKjeex9ZFXkt1AyNov9R5HZtjBKVsmVpw7pa7ZtlCGvCBC2vnnXctaYN+aRI61HjIqeetZW5ROg=="], "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], @@ -831,7 +823,7 @@ "character-reference-invalid": ["character-reference-invalid@2.0.1", "", {}, "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="], - "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + "chokidar": ["chokidar@6.0.0", "", { "dependencies": { "readdirp": "^5.1.1" } }, "sha512-Ec2Z7wpcKBiMpR7DxteoqS/sq5G5d2A4fpxzPv6+fD7xNNdrTghn7L11YwV5EN1B3i72Erc3XVT5FkWIDx90+A=="], "class-variance-authority": ["class-variance-authority@0.7.1", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="], @@ -841,6 +833,8 @@ "cmdk": ["cmdk@1.1.1", "", { "dependencies": { "@radix-ui/react-compose-refs": "^1.1.1", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-id": "^1.1.0", "@radix-ui/react-primitive": "^2.0.2" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg=="], + "cn": ["cn@0.5.2", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-wm10E6iuJ37rALOw3D+3cfaXXZSLNMh2uxpQn3dNICqfJM59yXqgbA9/9Iiz155j5kYNLdK6WreNdW3NQtx3OQ=="], + "collapse-white-space": ["collapse-white-space@2.1.0", "", {}, "sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw=="], "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], @@ -859,8 +853,6 @@ "content-disposition": ["content-disposition@0.5.2", "", {}, "sha512-kRGRZw3bLlFISDBgwTSA1TMBFN6J6GWDeubmDE3AF+3+yXL8hTWv8r5rkLbqYXY4RjPk/EzHnClI3zQf1cFmHA=="], - "content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], - "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], @@ -871,7 +863,7 @@ "date-fns": ["date-fns@4.4.0", "", {}, "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w=="], - "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + "debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], "decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="], @@ -887,7 +879,7 @@ "devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="], - "diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], + "diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], "docs": ["docs@workspace:packages/docs"], @@ -915,7 +907,7 @@ "esast-util-from-js": ["esast-util-from-js@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "acorn": "^8.0.0", "esast-util-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw=="], - "esbuild": ["esbuild@0.27.7", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.7", "@esbuild/android-arm": "0.27.7", "@esbuild/android-arm64": "0.27.7", "@esbuild/android-x64": "0.27.7", "@esbuild/darwin-arm64": "0.27.7", "@esbuild/darwin-x64": "0.27.7", "@esbuild/freebsd-arm64": "0.27.7", "@esbuild/freebsd-x64": "0.27.7", "@esbuild/linux-arm": "0.27.7", "@esbuild/linux-arm64": "0.27.7", "@esbuild/linux-ia32": "0.27.7", "@esbuild/linux-loong64": "0.27.7", "@esbuild/linux-mips64el": "0.27.7", "@esbuild/linux-ppc64": "0.27.7", "@esbuild/linux-riscv64": "0.27.7", "@esbuild/linux-s390x": "0.27.7", "@esbuild/linux-x64": "0.27.7", "@esbuild/netbsd-arm64": "0.27.7", "@esbuild/netbsd-x64": "0.27.7", "@esbuild/openbsd-arm64": "0.27.7", "@esbuild/openbsd-x64": "0.27.7", "@esbuild/openharmony-arm64": "0.27.7", "@esbuild/sunos-x64": "0.27.7", "@esbuild/win32-arm64": "0.27.7", "@esbuild/win32-ia32": "0.27.7", "@esbuild/win32-x64": "0.27.7" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w=="], + "esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], @@ -957,7 +949,7 @@ "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], - "fetchdts": ["fetchdts@0.1.7", "", {}, "sha512-YoZjBdafyLIop9lSxXVI33oLD5kN31q4Td+CasofLLYeLXRFeOsuOw0Uo+XNRi9PZlbfdlN2GmRtm4tCEQ9/KA=="], + "fetchdts": ["fetchdts@0.2.2", "", {}, "sha512-K1uYQ9JMv2/r7gCMC+J8uX1YfRqakhgq0/38nvlDNgJf0DUif/Qhu+Za8j+cH2JMauziN0YO2QfcoVvSdfzgzQ=="], "file-type": ["file-type@22.3.0", "", { "dependencies": { "@tokenizer/inflate": "^0.6.0", "strtok3": "^10.6.3", "token-types": "^6.1.2", "uint8array-extras": "^1.6.0" } }, "sha512-PrPedgnnWl5bWz3JHgar0QSzRvzeyFh7dZ9JpYOgcPZu4KALS9zw4MMa6qXRYyjeBsAlpaWB2boLuG991+0HIQ=="], @@ -965,11 +957,11 @@ "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - "fumadocs-core": ["fumadocs-core@16.2.0", "", { "dependencies": { "@formatjs/intl-localematcher": "^0.6.2", "@orama/orama": "^3.1.16", "@shikijs/rehype": "^3.15.0", "@shikijs/transformers": "^3.15.0", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "hast-util-to-estree": "^3.1.3", "hast-util-to-jsx-runtime": "^2.3.6", "image-size": "^2.0.2", "negotiator": "^1.0.0", "npm-to-yarn": "^3.0.1", "path-to-regexp": "^8.3.0", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-rehype": "^11.1.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^3.15.0", "unist-util-visit": "^5.0.0" }, "peerDependencies": { "@mixedbread/sdk": "^0.19.0", "@orama/core": "1.x.x", "@tanstack/react-router": "1.x.x", "@types/react": "*", "algoliasearch": "5.x.x", "lucide-react": "*", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "react-router": "7.x.x", "waku": "^0.26.0 || ^0.27.0" }, "optionalPeers": ["@mixedbread/sdk", "@orama/core", "@tanstack/react-router", "@types/react", "algoliasearch", "lucide-react", "next", "react", "react-dom", "react-router", "waku"] }, "sha512-ExfXGzeS2Xyny003HVNim91pF+gbo8HbB+33KgNAQXD55NOj/uXSLWlFHkvparmB0wvJoFUzDiOWhJvv3M9pKw=="], + "fumadocs-core": ["fumadocs-core@16.19.8", "", { "dependencies": { "@fumari/image-size": "^0.1.1", "acorn": "^8.19.0", "acorn-jsx": "^5.3.2", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "hast-util-from-dom": "^5.0.1", "hast-util-to-estree": "^3.1.3", "mdast-util-mdx": "^3.0.0", "micromark": "^4.0.3", "micromark-extension-gfm-table": "^2.1.2", "npm-to-yarn": "3.2.0", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-rehype": "^11.1.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^4.6.0", "tinyglobby": "^0.2.17", "unified": "^11.0.5", "vfile": "^6.0.3", "yaml": "^2.9.1", "zbsearch": "^4.0.2" }, "peerDependencies": { "@mdx-js/mdx": "*", "@mixedbread/sdk": "0.x.x", "@modelcontextprotocol/server": "2.x.x", "@orama/core": "1.x.x", "@oramacloud/client": "2.x.x", "@pierre/highlights": "0.x.x", "@tanstack/react-router": "1.x.x", "@types/estree-jsx": "*", "@types/hast": "*", "@types/mdast": "*", "@types/react": "*", "algoliasearch": "5.x.x", "flexsearch": "*", "lucide-react": "*", "meilisearch": ">=0.50.0 <1.0.0", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "react-router": "7.x.x || 8.x.x", "waku": "*", "zod": "4.x.x" }, "optionalPeers": ["@mdx-js/mdx", "@mixedbread/sdk", "@modelcontextprotocol/server", "@orama/core", "@oramacloud/client", "@pierre/highlights", "@tanstack/react-router", "@types/estree-jsx", "@types/hast", "@types/mdast", "@types/react", "algoliasearch", "flexsearch", "lucide-react", "meilisearch", "next", "react", "react-dom", "react-router", "waku", "zod"] }, "sha512-kKWLk5GWvxwvdjbnJnhhYapK701C/uzJOrhqXsp+i5tSuPxEo6NSf/aTfZ/YMjkuXbB5z3isH7bcKbEe3EoauA=="], - "fumadocs-mdx": ["fumadocs-mdx@14.0.3", "", { "dependencies": { "@mdx-js/mdx": "^3.1.1", "@standard-schema/spec": "^1.0.0", "chokidar": "^4.0.3", "esbuild": "^0.27.0", "estree-util-value-to-estree": "^3.5.0", "js-yaml": "^4.1.1", "lru-cache": "^11.2.2", "mdast-util-to-markdown": "^2.1.2", "picocolors": "^1.1.1", "picomatch": "^4.0.3", "remark-mdx": "^3.1.1", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.3", "zod": "^4.1.12" }, "peerDependencies": { "@fumadocs/mdx-remote": "^1.4.0", "fumadocs-core": "^15.0.0 || ^16.0.0", "next": "^15.3.0 || ^16.0.0", "react": "*", "vite": "6.x.x || 7.x.x" }, "optionalPeers": ["@fumadocs/mdx-remote", "next", "react", "vite"], "bin": { "fumadocs-mdx": "dist/bin.js" } }, "sha512-GnRnnkb9QUiur9fbHF5aPsD+IkxLwxJLNC/C1L9W+Ii/o8RseRVIWUJpEZNlG62KPtwsbwkr/0mQ4ToHUzCRng=="], + "fumadocs-mdx": ["fumadocs-mdx@15.6.4", "", { "dependencies": { "@mdx-js/mdx": "^3.1.1", "@standard-schema/spec": "^1.1.0", "acorn": "^8.19.0", "acorn-jsx": "^5.3.2", "chokidar": "^6.0.0", "esbuild": "^0.28.2", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "magic-string": "^1.4.5", "mdast-util-from-markdown": "^2.1.0", "mdast-util-mdx": "^3.0.0", "micromark-extension-mdxjs-esm": "^3.0.0", "picocolors": "^1.1.1", "picomatch": "^4.0.7", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "vfile": "^6.0.3", "yaml": "^2.9.1", "yuku-analyzer": "^0.19.0", "zod": "^4.6.7" }, "peerDependencies": { "@fumadocs/satteri": "0.x.x", "@types/mdast": "*", "@types/mdx": "*", "@types/react": "*", "@vitejs/plugin-rsc": "^0.5.34", "fumadocs-core": "^16.18.3", "mdast-util-directive": "*", "next": "^15.3.0 || ^16.0.0", "react": "^19.2.0", "rolldown": "*", "satteri": "^0.11.7", "vite": "7.x.x || 8.x.x" }, "optionalPeers": ["@fumadocs/satteri", "@types/mdast", "@types/mdx", "@types/react", "@vitejs/plugin-rsc", "mdast-util-directive", "next", "react", "rolldown", "satteri", "vite"], "bin": { "fumadocs-mdx": "./bin.js" } }, "sha512-b5z5GjDxDzdc9K1/HwAL6X77xj0ddinJ5FJFXeIxYCRRQq2rqSFNTNAd2fo2UmQnr87jkuE25+o5iAV0mg48lw=="], - "fumadocs-ui": ["fumadocs-ui@16.1.0", "", { "dependencies": { "@radix-ui/react-accordion": "^1.2.12", "@radix-ui/react-collapsible": "^1.1.12", "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-direction": "^1.1.1", "@radix-ui/react-navigation-menu": "^1.2.14", "@radix-ui/react-popover": "^1.1.15", "@radix-ui/react-presence": "^1.1.5", "@radix-ui/react-scroll-area": "^1.2.10", "@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-tabs": "^1.1.13", "class-variance-authority": "^0.7.1", "fumadocs-core": "16.1.0", "lodash.merge": "^4.6.2", "next-themes": "^0.4.6", "postcss-selector-parser": "^7.1.0", "react-medium-image-zoom": "^5.4.0", "scroll-into-view-if-needed": "^3.1.0", "tailwind-merge": "^3.4.0" }, "peerDependencies": { "@types/react": "*", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "tailwindcss": "^4.0.0" }, "optionalPeers": ["@types/react", "next", "tailwindcss"] }, "sha512-Yty9tINshfQQYHE/K+nH7+7VHTNtWL0hgNvwI7lLd6xcJrbFUgzJQUeS0oGxZx+7rgqGYvNqlByKLRQHqPR9dw=="], + "fumadocs-ui": ["fumadocs-ui@16.19.8", "", { "dependencies": { "@fuma-translate/react": "^1.0.2", "@fumadocs/tailwind": "0.1.5", "@radix-ui/react-accordion": "^1.3.1", "@radix-ui/react-collapsible": "^1.2.1", "@radix-ui/react-dialog": "^1.3.1", "@radix-ui/react-direction": "^1.2.0", "@radix-ui/react-navigation-menu": "^1.4.1", "@radix-ui/react-popover": "^1.3.1", "@radix-ui/react-presence": "^1.1.11", "@radix-ui/react-scroll-area": "^1.4.0", "@radix-ui/react-slot": "^1.5.0", "@radix-ui/react-tabs": "^1.2.1", "class-variance-authority": "^0.7.1", "cn": "^0.5.2", "lucide-react": "^1.71.0", "motion": "^14.12.0", "next-themes": "^0.4.6", "react-remove-scroll": "^2.7.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^4.6.0" }, "peerDependencies": { "@types/mdx": "*", "@types/react": "*", "fumadocs-core": "16.19.8", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "takumi-js": "*" }, "optionalPeers": ["@types/mdx", "@types/react", "next", "takumi-js"] }, "sha512-rVwME6IBCwwgDu3sADmnAYctvedWPZxDGylLIilMVSAPPIUsvnIFnP6KB3/iynRuIuqnIpdmdtscXhY6Gnzpvg=="], "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], @@ -977,33 +969,31 @@ "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], - "globrex": ["globrex@0.1.2", "", {}, "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg=="], - "graceful-fs": ["graceful-fs@4.2.12", "", {}, "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw=="], - "h3-v2": ["h3@2.0.1-rc.20", "", { "dependencies": { "rou3": "^0.8.1", "srvx": "^0.11.13" }, "peerDependencies": { "crossws": "^0.4.1" }, "optionalPeers": ["crossws"], "bin": { "h3": "bin/h3.mjs" } }, "sha512-28ljodXuUp0fZovdiSRq4G9OgrxCztrJe5VdYzXAB7ueRvI7pIUqLU14Xi3XqdYJ/khXjfpUOOD2EQa6CmBgsg=="], - "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], + "hast-util-from-dom": ["hast-util-from-dom@5.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "hastscript": "^9.0.0", "web-namespaces": "^2.0.0" } }, "sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q=="], + + "hast-util-parse-selector": ["hast-util-parse-selector@4.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A=="], + "hast-util-to-estree": ["hast-util-to-estree@3.1.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-attach-comments": "^3.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w=="], "hast-util-to-html": ["hast-util-to-html@9.0.7", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-HYNDA3qdnzUPitY/LcQm1nWs8z0cWFNH1Nz09jdI/tXifAqF7h3+jrLl4S/b9Mi4VSjn0Dsn54ctuTV6zhBthA=="], "hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.7", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-object": "^2.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-F7DNV2NMcTxA4GqPVHnXzX+mpoPHAIY9rJAVH3CZ1FdBZOcBUEjUuvMkMpHVs/sicEtznh9tMGj5WUR9S4E2rg=="], - "hast-util-to-string": ["hast-util-to-string@3.0.1", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A=="], - "hast-util-whitespace": ["hast-util-whitespace@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="], + "hastscript": ["hastscript@9.0.3", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-parse-selector": "^4.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0" } }, "sha512-1ALZXSmCGmW3h8AMz4R4+QKSKFi7sNgXLVwmwB8FYVtl1CwQ3WDkSAEY/d5tp1g/vbQgq2s1WlHgfO3jbw1TsA=="], + "html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="], "ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], - "image-size": ["image-size@2.2.0", "", { "bin": { "image-size": "bin/image-size.js" } }, "sha512-93QTtmEv0UD26RTJfmxQvWzhlauWO1TizNPjCumqzlACXYmI7TlwRWWT2+M4at7kZwnj+WkMOW9XKI76eX0dWw=="], - "ini": ["ini@1.3.8", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="], - "inline-style-parser": ["inline-style-parser@0.2.9", "", {}, "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg=="], + "inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="], "is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="], @@ -1065,15 +1055,13 @@ "lodash.debounce": ["lodash.debounce@4.0.8", "", {}, "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow=="], - "lodash.merge": ["lodash.merge@4.6.2", "", {}, "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="], - "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], - "lru-cache": ["lru-cache@11.5.4", "", {}, "sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw=="], + "lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], "lucide-react": ["lucide-react@1.84.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-kTIK/SVxMHW/d7hpjgleufRON3s6iWOvv7w9C8AeGQDYM4tDyWp58xltDHzlh7+x2uydNevrr7FgiAv0/dynLA=="], - "lucide-static": ["lucide-static@0.552.0", "", {}, "sha512-wL+9EAx8k/4i/w9qGuAwHrrV8SryVsJk+Ug9SErtg18Zq95FMwMXlu4Dhl4RS8C2b1oxFu66p7YK96yrNsm6cg=="], + "lucide-static": ["lucide-static@1.84.0", "", {}, "sha512-nr7xSL04HGusrhcIsFeUrPN0uGQ0ZJFx3oTBZStMBSjszS0xOtI/sl1YrRH3iQ1MDPo+yrJZlAmk2u+4P3WvIQ=="], "magic-string": ["magic-string@1.4.5", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w=="], @@ -1205,11 +1193,13 @@ "motion-utils": ["motion-utils@14.7.0", "", {}, "sha512-woO0/Nb7ys75f94fjvQi/6leiHGvZUYkeHUPEZ3vxsV+9OpEVhkxp01x8MlRwX0zt31EqgXsKDAoBoJLC148Tw=="], - "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + "ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], "nanoid": ["nanoid@6.0.2", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-hIvVOb9Qr1p/9CNNLOe0OlWvgx/ziTsVwKN/GDSsuArN2K0wDiafP3s0SWmsm7o2BdnyS8Z9Z64NFBUbn6ziBg=="], - "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], + "napi-windows-process-start-time": ["napi-windows-process-start-time@0.1.0", "", { "os": "win32", "cpu": [ "x64", "arm64", ] }, "sha512-zHxhzKsIFu3elch3eFw69WEUGc79DFhbc3nD/WEOzWL/pFFLZRW13EHnuO0c+0YjncE5uCaS9ICHxOBXkb6vPw=="], + + "negotiator": ["negotiator@0.6.4", "", {}, "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w=="], "next-themes": ["next-themes@0.4.6", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="], @@ -1239,7 +1229,7 @@ "path-is-inside": ["path-is-inside@1.0.2", "", {}, "sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w=="], - "path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], + "path-to-regexp": ["path-to-regexp@3.3.0", "", {}, "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw=="], "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], @@ -1255,8 +1245,6 @@ "postcss": ["postcss@8.5.34", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.4" } }, "sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw=="], - "postcss-selector-parser": ["postcss-selector-parser@7.2.1", "", { "dependencies": { "util-deprecate": "^1.0.2" } }, "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ=="], - "postgres": ["postgres@4.2.0", "", {}, "sha512-9/HKJPaDuY7bhg97y8aYcTaF9hNAXGu85Fo/TNGnPkVoTGZWLsJNcLmhjv291K4mxC4glRdsfsbV42986JbntQ=="], "prettier": ["prettier@3.10.1", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg=="], @@ -1277,10 +1265,6 @@ "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], - "react-medium-image-zoom": ["react-medium-image-zoom@5.4.9", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-czBdTbJI6JEbqeRIT5M8D3j7TrffBfo00U0P0lzzd19usj8PiR1yPH7PK/vQlwBE/Sv9YFdJGN6XauJPi4jRyg=="], - - "react-refresh": ["react-refresh@0.18.0", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="], - "react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="], "react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="], @@ -1289,7 +1273,7 @@ "react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="], - "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + "readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], "real-require": ["real-require@1.0.0", "", {}, "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g=="], @@ -1329,9 +1313,7 @@ "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], - "rollup": ["rollup@4.69.1", "", { "dependencies": { "@types/estree": "^1.0.10" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.69.1", "@rollup/rollup-android-arm64": "4.69.1", "@rollup/rollup-android-x64": "4.69.1", "@rollup/rollup-darwin-arm64": "4.69.1", "@rollup/rollup-darwin-x64": "4.69.1", "@rollup/rollup-freebsd-arm64": "4.69.1", "@rollup/rollup-freebsd-x64": "4.69.1", "@rollup/rollup-linux-arm-gnueabihf": "4.69.1", "@rollup/rollup-linux-arm-musleabihf": "4.69.1", "@rollup/rollup-linux-arm64-gnu": "4.69.1", "@rollup/rollup-linux-arm64-musl": "4.69.1", "@rollup/rollup-linux-loong64-gnu": "4.69.1", "@rollup/rollup-linux-loong64-musl": "4.69.1", "@rollup/rollup-linux-ppc64-gnu": "4.69.1", "@rollup/rollup-linux-ppc64-musl": "4.69.1", "@rollup/rollup-linux-riscv64-gnu": "4.69.1", "@rollup/rollup-linux-riscv64-musl": "4.69.1", "@rollup/rollup-linux-s390x-gnu": "4.69.1", "@rollup/rollup-linux-x64-gnu": "4.69.1", "@rollup/rollup-linux-x64-musl": "4.69.1", "@rollup/rollup-openbsd-x64": "4.69.1", "@rollup/rollup-openharmony-arm64": "4.69.1", "@rollup/rollup-win32-arm64-msvc": "4.69.1", "@rollup/rollup-win32-ia32-msvc": "4.69.1", "@rollup/rollup-win32-x64-gnu": "4.69.1", "@rollup/rollup-win32-x64-msvc": "4.69.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-vWe2JWir6FmmYA78Af6xZABpkYGvuKcgy6gZuOxa7PXNayPQ/lJqkqUgeiZelX8q2Djgu5XKP0qk77y0WXn2JQ=="], - - "rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="], + "rolldown": ["rolldown@1.3.4", "", { "dependencies": { "@oxc-project/types": "=0.160.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.3.4", "@rolldown/binding-android-arm64": "1.3.4", "@rolldown/binding-darwin-arm64": "1.3.4", "@rolldown/binding-darwin-x64": "1.3.4", "@rolldown/binding-freebsd-x64": "1.3.4", "@rolldown/binding-linux-arm-gnueabihf": "1.3.4", "@rolldown/binding-linux-arm64-gnu": "1.3.4", "@rolldown/binding-linux-arm64-musl": "1.3.4", "@rolldown/binding-linux-ppc64-gnu": "1.3.4", "@rolldown/binding-linux-s390x-gnu": "1.3.4", "@rolldown/binding-linux-x64-gnu": "1.3.4", "@rolldown/binding-linux-x64-musl": "1.3.4", "@rolldown/binding-openharmony-arm64": "1.3.4", "@rolldown/binding-wasm32-wasi": "1.3.4", "@rolldown/binding-win32-arm64-msvc": "1.3.4", "@rolldown/binding-win32-x64-msvc": "1.3.4" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q=="], "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], @@ -1353,7 +1335,7 @@ "shared-actions": ["shared-actions@workspace:packages/shared-actions"], - "shiki": ["shiki@3.23.0", "", { "dependencies": { "@shikijs/core": "3.23.0", "@shikijs/engine-javascript": "3.23.0", "@shikijs/engine-oniguruma": "3.23.0", "@shikijs/langs": "3.23.0", "@shikijs/themes": "3.23.0", "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-55Dj73uq9ZXL5zyeRPzHQsK7Nbyt6Y10k5s7OjuFZGMhpp4r/rsLBH0o/0fstIzX1Lep9VxefWljK/SKCzygIA=="], + "shiki": ["shiki@4.6.0", "", { "dependencies": { "@shikijs/core": "4.6.0", "@shikijs/engine-javascript": "4.6.0", "@shikijs/engine-oniguruma": "4.6.0", "@shikijs/langs": "4.6.0", "@shikijs/themes": "4.6.0", "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA=="], "sonic-boom": ["sonic-boom@4.2.1", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q=="], @@ -1365,7 +1347,7 @@ "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], - "srvx": ["srvx@0.11.22", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-LqZxxBDMKuMAZzFzJnDCkFOrs9MZQZr0LvHiO/SuSZVdQaXD7xQ5UWTUxheJrQPve1qk9MG2B/yttUvJxw8egQ=="], + "srvx": ["srvx@1.0.8", "", { "bin": { "srvx": "./bin/srvx.mjs" } }, "sha512-ngFS/J6St4PJfHRHGjr78xkPPtbyXtdMOLNE4x/XZunEK3OhV7aGUWMHf9WTUEy6wm1U0W4okkd82ZFFWRVQTw=="], "state-local": ["state-local@1.0.7", "", {}, "sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w=="], @@ -1381,7 +1363,7 @@ "style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="], - "style-to-object": ["style-to-object@2.0.2", "", { "dependencies": { "inline-style-parser": "0.2.9" } }, "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA=="], + "style-to-object": ["style-to-object@1.0.14", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="], "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], @@ -1407,8 +1389,6 @@ "trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="], - "tsconfck": ["tsconfck@3.1.6", "", { "peerDependencies": { "typescript": "^5.0.0" }, "optionalPeers": ["typescript"], "bin": { "tsconfck": "bin/tsconfck.js" } }, "sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w=="], - "tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], "tw-animate-css": ["tw-animate-css@1.4.0", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="], @@ -1455,20 +1435,18 @@ "usehooks-ts": ["usehooks-ts@3.1.1", "", { "dependencies": { "lodash.debounce": "^4.0.8" }, "peerDependencies": { "react": "^16.8.0 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-I4diPp9Cq6ieSUH2wu+fDAVQO43xwtulo+fKEidHUwZPnYImbtkTjzIJYcDcJqxgmX31GVqNFURodvcgHcW0pA=="], - "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], - "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], "vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="], "vfile-message": ["vfile-message@4.0.4", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg=="], - "vite": ["vite@7.3.8", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw=="], - - "vite-tsconfig-paths": ["vite-tsconfig-paths@5.1.4", "", { "dependencies": { "debug": "^4.1.1", "globrex": "^0.1.2", "tsconfck": "^3.0.3" }, "peerDependencies": { "vite": "*" }, "optionalPeers": ["vite"] }, "sha512-cYj0LRuLV2c2sMqhqhGpaO3LretdtMn/BVX4cPLanIZuwwrkVl+lK84E/miEXkCHWXuq65rhNN4rXsBcOB3S4w=="], + "vite": ["vite@8.4.0", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.33", "rolldown": "~1.3.2", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3", "napi-windows-process-start-time": "^0.1.0" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-X2nUJg+9cutlz3hzqyO6p+WTwk9H257DjwAEf9EQYUFrQbDItmetadi9gYmb+l7VDy4r3VXLUnmLTwuPmzejDw=="], "vitefu": ["vitefu@1.1.4", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-qbEIDswfXH3x3IYRMScl/bf1AVW0dn7Z8qkr7g7nohkusfuC7tcFa7t5EoTOz60AunosLM9sDrDjHxsX+Up+CQ=="], + "web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="], + "webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], "widest-line": ["widest-line@4.0.1", "", { "dependencies": { "string-width": "^5.0.1" } }, "sha512-o0cyEG0e8GPzT4iGHphIOh0cJOV8fivsXxddQasHPHfoZf1ZexrfeA21w2NaEN1RHE+fXlfISmOE8R9N3u3Qig=="], @@ -1479,11 +1457,23 @@ "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], + + "yuku-analyzer": ["yuku-analyzer@0.19.0", "", { "dependencies": { "@yuku-toolchain/types": "^0.19.0", "yuku-ast": "^0.19.0", "yuku-core": "0.19.0" } }, "sha512-Iu7DV5cWOQ3ERSA7oBquz/RT5IEGsUyUeCivYs9lQaZ4nSjM31yD17mH616JKcTyVoVWYivsFZ+twT3UyBosTA=="], + + "yuku-ast": ["yuku-ast@0.19.0", "", { "dependencies": { "@yuku-toolchain/types": "^0.19.0" } }, "sha512-PyCsiScaelhxBGzL8dyeJkLqvRZycoh78R31Vrt/WqYrm0hMFoKwIw/X7Dx5mBKLWAMlV9I9HEyBOHnj2gZVyw=="], + + "yuku-core": ["yuku-core@0.19.0", "", { "dependencies": { "@yuku-toolchain/types": "^0.19.0" }, "optionalDependencies": { "@yuku-core/binding-android-arm64": "0.19.0", "@yuku-core/binding-darwin-arm64": "0.19.0", "@yuku-core/binding-darwin-x64": "0.19.0", "@yuku-core/binding-freebsd-x64": "0.19.0", "@yuku-core/binding-linux-arm-gnu": "0.19.0", "@yuku-core/binding-linux-arm-musl": "0.19.0", "@yuku-core/binding-linux-arm64-gnu": "0.19.0", "@yuku-core/binding-linux-arm64-musl": "0.19.0", "@yuku-core/binding-linux-x64-gnu": "0.19.0", "@yuku-core/binding-linux-x64-musl": "0.19.0", "@yuku-core/binding-win32-arm64": "0.19.0", "@yuku-core/binding-win32-x64": "0.19.0" } }, "sha512-kYK9e1XdfirNhkipzW0wmMcSWcVF/CWnuugodfVYRCUwvoBefweL9HzB96OiKEhsx78V5WbUxbJqlizMX869Qg=="], + + "zbsearch": ["zbsearch@4.0.4", "", {}, "sha512-uajYItKQcOP6f1z+XqzJSIx1jQPe7PbXajElh7r60KGc1MoSIn/hH9d++SvtkT78GXrZB4fah/e8Ts8jFh2CGw=="], + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], - "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], + "@babel/core/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "@babel/traverse/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], @@ -1497,15 +1487,11 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.9.1", "", { "bundled": true }, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], - "@tanstack/react-table/@tanstack/react-store": ["@tanstack/react-store@0.11.4", "", { "dependencies": { "@tanstack/store": "0.11.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-JAQz7LcABVRbxZ6qCd4u/KqDaqBc1qmcOWz7XBTdav1Ib363HQdihCQF1A755nDhoi9VEd6UqZ5thWVKTwIIXw=="], - "@tanstack/router-generator/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], "@tanstack/router-plugin/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], - "@tanstack/start-plugin-core/@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], - - "@tanstack/table-core/@tanstack/store": ["@tanstack/store@0.11.3", "", {}, "sha512-/Mt3h2Qe67HmRMc5SJ+8jM2Fp7O4fBbwOlS0ujUvx34KgAvkvdLSHrJatv0PJG5fbvlDsACTawMMY4ptCpVI8w=="], + "@tokenizer/inflate/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "ansi-align/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], @@ -1513,11 +1499,9 @@ "chalk-template/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], - "compression/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], - - "compression/negotiator": ["negotiator@0.6.4", "", {}, "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w=="], + "hast-util-to-jsx-runtime/style-to-object": ["style-to-object@2.0.2", "", { "dependencies": { "inline-style-parser": "0.2.9" } }, "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA=="], - "fumadocs-ui/fumadocs-core": ["fumadocs-core@16.1.0", "", { "dependencies": { "@formatjs/intl-localematcher": "^0.6.2", "@orama/orama": "^3.1.16", "@shikijs/rehype": "^3.15.0", "@shikijs/transformers": "^3.15.0", "estree-util-value-to-estree": "^3.5.0", "github-slugger": "^2.0.0", "hast-util-to-estree": "^3.1.3", "hast-util-to-jsx-runtime": "^2.3.6", "image-size": "^2.0.2", "negotiator": "^1.0.0", "npm-to-yarn": "^3.0.1", "path-to-regexp": "^8.3.0", "remark": "^15.0.1", "remark-gfm": "^4.0.1", "remark-rehype": "^11.1.2", "scroll-into-view-if-needed": "^3.1.0", "shiki": "^3.15.0", "unist-util-visit": "^5.0.0" }, "peerDependencies": { "@mixedbread/sdk": "^0.19.0", "@orama/core": "1.x.x", "@tanstack/react-router": "1.x.x", "@types/react": "*", "algoliasearch": "5.x.x", "lucide-react": "*", "next": "16.x.x", "react": "^19.2.0", "react-dom": "^19.2.0", "react-router": "7.x.x", "waku": "^0.26.0 || ^0.27.0" }, "optionalPeers": ["@mixedbread/sdk", "@orama/core", "@tanstack/react-router", "@types/react", "algoliasearch", "lucide-react", "next", "react", "react-dom", "react-router", "waku"] }, "sha512-5pbO2bOGc/xlb2yLQSy6Oag8mvD5CNf5HzQIG80HjZzLXYWEOHW8yovRKnWKRF9gAibn6WHnbssj3YPAlitV/A=="], + "micromark/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "mime-types/mime-db": ["mime-db@1.33.0", "", {}, "sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ=="], @@ -1527,15 +1511,11 @@ "serve-handler/bytes": ["bytes@3.0.0", "", {}, "sha512-pMhOfFDPiv9t5jjIXkHosWmkSyQbvsgEVNkz0ERHbuLh2T/7j4Mqqpz523Fe8MVY89KC6Sh/QfS2sM+SjgFDcw=="], - "serve-handler/path-to-regexp": ["path-to-regexp@3.3.0", "", {}, "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw=="], - - "style-to-js/style-to-object": ["style-to-object@1.0.14", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="], - - "unplugin/@rolldown/pluginutils": ["@rolldown/pluginutils@1.1.1", "", {}, "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA=="], + "@babel/core/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "@tanstack/react-table/@tanstack/react-store/@tanstack/store": ["@tanstack/store@0.11.3", "", {}, "sha512-/Mt3h2Qe67HmRMc5SJ+8jM2Fp7O4fBbwOlS0ujUvx34KgAvkvdLSHrJatv0PJG5fbvlDsACTawMMY4ptCpVI8w=="], + "@babel/traverse/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], - "@tanstack/router-plugin/chokidar/readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], + "@tokenizer/inflate/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "ansi-align/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], @@ -1543,9 +1523,9 @@ "chalk-template/chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], - "compression/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], + "hast-util-to-jsx-runtime/style-to-object/inline-style-parser": ["inline-style-parser@0.2.9", "", {}, "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg=="], - "style-to-js/style-to-object/inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="], + "micromark/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "ansi-align/string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], } diff --git a/packages/docs/package.json b/packages/docs/package.json index c63c0a6..5dc71db 100644 --- a/packages/docs/package.json +++ b/packages/docs/package.json @@ -11,17 +11,16 @@ "postinstall": "fumadocs-mdx" }, "dependencies": { - "@orama/orama": "^3.1.18", - "@tanstack/react-router": "^1.134.12", - "@tanstack/react-start": "^1.134.12", - "@tanstack/start-static-server-functions": "^1.134.12", - "fumadocs-core": "16.2.0", - "fumadocs-mdx": "14.0.3", - "fumadocs-ui": "16.1.0", - "lucide-static": "^0.552.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-start": "^1.170.0", + "@tanstack/start-static-server-functions": "^1.167.44", + "fumadocs-core": "16.19.8", + "fumadocs-mdx": "15.6.4", + "fumadocs-ui": "16.19.8", + "lucide-static": "^1.84.0", "react": "^19.3.1", "react-dom": "^19.3.1", - "vite": "^7.3.8" + "vite": "^8.4.0" }, "devDependencies": { "@tailwindcss/vite": "^4.3.5", @@ -29,10 +28,9 @@ "@types/node": "^26.6.11", "@types/react": "^19.3.3", "@types/react-dom": "^19.3.0", - "@vitejs/plugin-react": "^5.2.0", + "@vitejs/plugin-react": "^6.3.0", "serve": "^14.2.8", "tailwindcss": "^4.3.5", - "typescript": "^7.0.2", - "vite-tsconfig-paths": "^5.1.4" + "typescript": "^7.0.2" } } diff --git a/packages/docs/src/components/search.tsx b/packages/docs/src/components/search.tsx index 9253dce..2fdd7b0 100644 --- a/packages/docs/src/components/search.tsx +++ b/packages/docs/src/components/search.tsx @@ -1,7 +1,6 @@ 'use client' -import { create } from '@orama/orama' -import { useDocsSearch } from 'fumadocs-core/search/client' +import { useStaticSearch } from 'fumadocs-core/search/client/orama-static' import { SearchDialog, SearchDialogClose, @@ -15,25 +14,15 @@ import { } from 'fumadocs-ui/components/dialog/search' import { useI18n } from 'fumadocs-ui/contexts/i18n' -function initOrama() { - return create({ - schema: { _: 'string' }, - // https://docs.orama.com/docs/orama-js/supported-languages - language: 'english', - }) -} - export default function DefaultSearchDialog(props: SharedProps) { const { locale } = useI18n() // (optional) for i18n - const { search, setSearch, query } = useDocsSearch({ - type: 'static', - initOrama, - locale, - }) + // Static search reads the index exported by /api/search; the exported data restores the + // tokenizer configured on the server (see routes/api/search.ts), so no client init is needed. + const search = useStaticSearch({ locale }) return ( - + @@ -41,7 +30,7 @@ export default function DefaultSearchDialog(props: SharedProps) { - + ) diff --git a/packages/docs/src/routes/docs/$.tsx b/packages/docs/src/routes/docs/$.tsx index df26bef..88edaec 100644 --- a/packages/docs/src/routes/docs/$.tsx +++ b/packages/docs/src/routes/docs/$.tsx @@ -24,7 +24,7 @@ export const Route = createFileRoute('/docs/$')({ const loader = createServerFn({ method: 'GET', }) - .inputValidator((slugs: string[]) => slugs) + .validator((slugs: string[]) => slugs) .middleware([staticFunctionMiddleware]) .handler(async ({ data: slugs }) => { const page = source.getPage(slugs) @@ -36,7 +36,8 @@ const loader = createServerFn({ } }) -const clientLoader = browserCollections.docs.createClientLoader({ +// Props is `object`: the page component is rendered without props (``). +const clientLoader = browserCollections.docs.createClientLoader({ component({ toc, frontmatter, default: MDX }) { return ( @@ -57,7 +58,7 @@ const clientLoader = browserCollections.docs.createClientLoader({ function Page() { const data = Route.useLoaderData() const Content = clientLoader.getComponent(data.path) - const tree = useMemo(() => transformPageTree(data.tree as PageTree.Folder), [data.tree]) + const tree = useMemo(() => transformPageTree(data.tree as PageTree.Root), [data.tree]) return ( diff --git a/packages/docs/src/routes/index.tsx b/packages/docs/src/routes/index.tsx index 7175c4b..06007e6 100644 --- a/packages/docs/src/routes/index.tsx +++ b/packages/docs/src/routes/index.tsx @@ -10,20 +10,24 @@ export const Route = createFileRoute('/')({ function Home() { return ( - -
- -

Documentation

+ + {/* fumadocs-ui 16.x: HomeLayout's root contains the navbar, so center the content in a + flex-1 wrapper (as the upstream template does) instead of styling the layout itself. */} +
+
+ +

Documentation

+
+ + Open Docs +
- - Open Docs -
) } diff --git a/packages/docs/tsconfig.json b/packages/docs/tsconfig.json index 54eb777..b0f834d 100644 --- a/packages/docs/tsconfig.json +++ b/packages/docs/tsconfig.json @@ -13,6 +13,7 @@ "skipLibCheck": true, "target": "ES2022", "allowJs": true, + "allowImportingTsExtensions": true, "forceConsistentCasingInFileNames": true, "paths": { "@/*": ["./src/*"], diff --git a/packages/docs/vite.config.ts b/packages/docs/vite.config.ts index 5e11b40..28a2f34 100644 --- a/packages/docs/vite.config.ts +++ b/packages/docs/vite.config.ts @@ -5,23 +5,21 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' import mdx from 'fumadocs-mdx/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' export default defineConfig({ server: { port: 3001, }, resolve: { + // Vite 8 resolves tsconfig `paths` natively (replaces the vite-tsconfig-paths plugin). + tsconfigPaths: true, alias: { - '@assets': resolve(__dirname, '../assets'), + '@assets': resolve(import.meta.dirname, '../assets'), }, }, plugins: [ - mdx(await import('./source.config')), + mdx(await import('./source.config.ts')), tailwindcss(), - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), tanstackStart({ spa: { enabled: true, From d04b10daefa5fd28b70d1cccf41e09b3d4ee2c60 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 11:47:22 -0300 Subject: [PATCH 045/100] fix(examples): pass variables in server example; typecheck examples and shared-actions - examples/server/start.ts registered sendEmail without the variables it was defined with. Its handler calls ctx.var.sendEmail, so the example failed at runtime. tsc caught it as TS2322 (server/start.ts:13), but nothing type-checked the examples. Pass `variables` like the other examples. - examples and shared-actions get "typecheck": "bun check --no-script", so root `bun run typecheck` (and CI) now cover them. --- packages/examples/package.json | 3 ++- packages/examples/server/start.ts | 4 +++- packages/shared-actions/package.json | 3 +++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/examples/package.json b/packages/examples/package.json index f2b8260..ec4251e 100644 --- a/packages/examples/package.json +++ b/packages/examples/package.json @@ -3,7 +3,8 @@ "private": true, "scripts": { "basic": "bun --hot basic/start.ts", - "multi-worker": "bun multi-worker/parent.ts" + "multi-worker": "bun multi-worker/parent.ts", + "typecheck": "bun check --no-script" }, "devDependencies": { "@types/bun": "latest", diff --git a/packages/examples/server/start.ts b/packages/examples/server/start.ts index 21d0bb5..53de354 100644 --- a/packages/examples/server/start.ts +++ b/packages/examples/server/start.ts @@ -1,4 +1,4 @@ -import { sendEmail } from '@shared-actions/index' +import { sendEmail, variables } from '@shared-actions/index' import { serve } from 'bun' import { duron } from 'duron' import { getHTML } from 'duron-dashboard/get-html' @@ -12,6 +12,8 @@ const client = duron({ actions: { sendEmail, }, + // sendEmail's handler calls ctx.var.sendEmail, so the variables it was defined with are required. + variables, logger: 'info', }) diff --git a/packages/shared-actions/package.json b/packages/shared-actions/package.json index 65eafd2..049f3cd 100644 --- a/packages/shared-actions/package.json +++ b/packages/shared-actions/package.json @@ -1,6 +1,9 @@ { "name": "shared-actions", "private": true, + "scripts": { + "typecheck": "bun check --no-script" + }, "dependencies": { "@ai-sdk/openai": "^3.0.147", "@opentelemetry/api": ">=1.9.0 <1.10.0", From 715108f277e59420a97c066c131796084f5e530f Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 11:49:33 -0300 Subject: [PATCH 046/100] chore(shared-actions): AI SDK 7 (ai 7, @ai-sdk/openai 4, @ai-sdk/otel) - ai 6 -> 7 and @ai-sdk/openai 3 -> 4. AI SDK 7 moved OpenTelemetry into @ai-sdk/otel and removed experimental_telemetry.tracer. The weather action now passes a per-call integration with the Duron step tracer (telemetry.integrations: [new OpenTelemetry({ tracer })]), so its AI spans stay under the step span. Checked with a mock model: invoke_agent, chat and step spans are children of step:, in the job's single trace. - @ai-sdk/otel depends on @opentelemetry/api 1.9.1, which is the locked version; there is still a single api copy. - docs/telemetry.mdx: same pattern in the external library example. --- bun.lock | 21 ++++++++++++--------- packages/docs/content/docs/telemetry.mdx | 10 +++++----- packages/shared-actions/index.ts | 8 +++++--- packages/shared-actions/package.json | 5 +++-- 4 files changed, 25 insertions(+), 19 deletions(-) diff --git a/bun.lock b/bun.lock index c4dc4b7..b8e5754 100644 --- a/bun.lock +++ b/bun.lock @@ -143,9 +143,10 @@ "packages/shared-actions": { "name": "shared-actions", "dependencies": { - "@ai-sdk/openai": "^3.0.147", + "@ai-sdk/openai": "^4.0.126", + "@ai-sdk/otel": "^1.0.185", "@opentelemetry/api": ">=1.9.0 <1.10.0", - "ai": "^6.0.339", + "ai": "^7.0.185", "zod": "^4.6.7", }, "devDependencies": { @@ -157,13 +158,15 @@ }, }, "packages": { - "@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.244", "", { "dependencies": { "@ai-sdk/provider": "3.0.19", "@ai-sdk/provider-utils": "4.0.69", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-U3k15BP8I3WIeKMi/p0G4JvVs/INNSqa16qK2Qj20yNsKBGT63dFDEGdpysxY+EG32SjKLcb7X0DJ0ondY99+g=="], + "@ai-sdk/gateway": ["@ai-sdk/gateway@4.0.158", "", { "dependencies": { "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.86", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-kYAY2Ogh6T5+f0Zj87nfo37F3sV4k3fimsQVShM0no2h5FMLb/7Uflvz9I9gvcYBDEHVhHB8Yr7oOyUNRVWc3g=="], - "@ai-sdk/openai": ["@ai-sdk/openai@3.0.147", "", { "dependencies": { "@ai-sdk/provider": "3.0.19", "@ai-sdk/provider-utils": "4.0.69" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-OBogVZLOdS6TXjSi6l4hEVgWkC2ijCkSvffGLW2FT9oSYBu9frvsvkh+U3sWFM5OpxqScNpehQAahOp/Qs1kRA=="], + "@ai-sdk/openai": ["@ai-sdk/openai@4.0.126", "", { "dependencies": { "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.86" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-meqsWzIAUJopCIqJUVU6RuSUnXya8TLT6xrpAaFt0NjltLSWL9CEWsyooxcFxw/eJ7Maxnc56e6miz6Q4/+QXg=="], - "@ai-sdk/provider": ["@ai-sdk/provider@3.0.19", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-5lWq7zSfRaU5ylDESn3sDQjgGl2AI1vjZKO/6JY3aFW70ct4zcP1kN+ZUYOuTXr28fVsYbyu2YFhddLdIgQFZQ=="], + "@ai-sdk/otel": ["@ai-sdk/otel@1.0.185", "", { "dependencies": { "@ai-sdk/provider": "4.0.39", "@opentelemetry/api": "1.9.1", "ai": "7.0.185" } }, "sha512-4kMwqVQF5PWimDYcZV9uuswnNZPh032TF6KKY64WjIfYIS/2wYRQ6iO/Mg8RDA75+q0MfUVq/sM0YhnuaucCWg=="], - "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.69", "", { "dependencies": { "@ai-sdk/provider": "3.0.19", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.1.1", "undici": "^6.28.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-j4coUNodGSDug1pGqmBOdRJKSoJ+QwbVs+gsfufLUx6YPuO87b3Q5ryUfsk1G5xL7IvGLFH+SNih26Oh8Ucv2Q=="], + "@ai-sdk/provider": ["@ai-sdk/provider@4.0.39", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-jRvAhvW23+TeMGVCME2WGejP/TjzyDg7TplUep3t8HcEYnC2/8zqhCy9RRrjjVs1ljcygABZ8pQ21MbCRdF01w=="], + + "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@5.0.86", "", { "dependencies": { "@ai-sdk/provider": "4.0.39", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-mni1RnIiyLdXGdsZJz5Zq3XyOx4MjeO7oaWfjrNIA2984zdDv44HBNBXjh294dLZ4BV3p9yKqJrC7vBDP5elBQ=="], "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], @@ -727,6 +730,8 @@ "@vscode/diff": ["@vscode/diff@0.0.2-145", "", {}, "sha512-atPcmNrAU4B8OsbrmqYlHbZREt//m8z52o400YA8uuvq3Be5wnmIhLoLqhMum7Jv7kRC0FE+m3WAUbaZF681wg=="], + "@workflow/serde": ["@workflow/serde@4.1.0", "", {}, "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ=="], + "@yuku-core/binding-android-arm64": ["@yuku-core/binding-android-arm64@0.19.0", "", { "os": "android", "cpu": "arm64" }, "sha512-wdL2XmTiZixAOaHk9Z0JJZ8u9Qm8d333Zjpc6gaxXFX+UR5BlsfxZ7a2+2Rm71pamppsPYGUGFq2oVLbh6DISw=="], "@yuku-core/binding-darwin-arm64": ["@yuku-core/binding-darwin-arm64@0.19.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-7sNJa6XJhyetnTy64jw3NEi4YgUcezHk1G5GH9FSvXAuC8wIlbaOwT9lgq5qo5sspjrZJQlBR1TWflP49uRpMw=="], @@ -759,7 +764,7 @@ "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], - "ai": ["ai@6.0.339", "", { "dependencies": { "@ai-sdk/gateway": "3.0.244", "@ai-sdk/provider": "3.0.19", "@ai-sdk/provider-utils": "4.0.69", "@opentelemetry/api": "^1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-uJUaEICQoFDJ8tQQgv2VUwDwjw4obkcVuBNRsEaXiQ91qbHTFlPHAK8J0qQJAL/2+RQla8dSW7Q4jP2cbgJg5w=="], + "ai": ["ai@7.0.185", "", { "dependencies": { "@ai-sdk/gateway": "4.0.158", "@ai-sdk/provider": "4.0.39", "@ai-sdk/provider-utils": "5.0.86" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-+35KFsrSboiWoPrq5q9hhiLiI/E11H0u2eLzI+R7SoNiI/Q93VDQMedNmFzvasmtN5ash7zHRU5d30qp1R9hxQ=="], "ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="], @@ -1401,8 +1406,6 @@ "uint8array-extras": ["uint8array-extras@1.6.0", "", {}, "sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q=="], - "undici": ["undici@6.29.1", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="], - "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], "unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="], diff --git a/packages/docs/content/docs/telemetry.mdx b/packages/docs/content/docs/telemetry.mdx index 5cfda77..3c4ad6e 100644 --- a/packages/docs/content/docs/telemetry.mdx +++ b/packages/docs/content/docs/telemetry.mdx @@ -155,21 +155,21 @@ const result = await ctx.step('annotated', async ({ telemetry }) => { Use `getTracer()` to get an OpenTelemetry tracer for external library integration. The tracer automatically links spans to the current job/step trace: ```ts -import { generateText } from 'ai' import { openai } from '@ai-sdk/openai' +import { OpenTelemetry } from '@ai-sdk/otel' +import { generateText } from 'ai' const aiAction = defineAction()({ name: 'ai-generation', input: z.object({ prompt: z.string() }), handler: async (ctx) => { const response = await ctx.step('generate', async ({ telemetry }) => { - // Pass the tracer to AI SDK - spans are automatically linked + // Pass the tracer to the AI SDK's OpenTelemetry integration - spans are automatically linked const result = await generateText({ prompt: ctx.input.prompt, model: openai('gpt-4o-mini'), - experimental_telemetry: { - isEnabled: true, - tracer: telemetry.getTracer('ai'), + telemetry: { + integrations: [new OpenTelemetry({ tracer: telemetry.getTracer('ai') })], }, }) diff --git a/packages/shared-actions/index.ts b/packages/shared-actions/index.ts index f350d57..e3a26bc 100644 --- a/packages/shared-actions/index.ts +++ b/packages/shared-actions/index.ts @@ -1,4 +1,5 @@ import { openai } from '@ai-sdk/openai' +import { OpenTelemetry } from '@ai-sdk/otel' import { context, trace } from '@opentelemetry/api' import { generateText } from 'ai' import { defineAction, NonRetriableError } from 'duron/index' @@ -199,9 +200,10 @@ export const getWeather = defineAction()({ model: openai('gpt-4o-mini'), temperature: 1, abortSignal: stepCtx.signal, - experimental_telemetry: { - isEnabled: true, - tracer: stepCtx.telemetry.getTracer('ai'), + // AI SDK 7: OpenTelemetry spans come from @ai-sdk/otel. A per-call integration with the + // step's tracer keeps the AI spans under this Duron step. + telemetry: { + integrations: [new OpenTelemetry({ tracer: stepCtx.telemetry.getTracer('ai') })], }, }) }, diff --git a/packages/shared-actions/package.json b/packages/shared-actions/package.json index 049f3cd..fb5e5d8 100644 --- a/packages/shared-actions/package.json +++ b/packages/shared-actions/package.json @@ -5,9 +5,10 @@ "typecheck": "bun check --no-script" }, "dependencies": { - "@ai-sdk/openai": "^3.0.147", + "@ai-sdk/openai": "^4.0.126", + "@ai-sdk/otel": "^1.0.185", "@opentelemetry/api": ">=1.9.0 <1.10.0", - "ai": "^6.0.339", + "ai": "^7.0.185", "zod": "^4.6.7" }, "devDependencies": { From 84befb0a9605fd671a56e58dec4398b82db484d0 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 12:37:37 -0300 Subject: [PATCH 047/100] perf(listing): index-friendly getJobs sort keys and per-table sort indexes Sorting the job list by status/actionName (~2.8 s) or description (~5.2 s) at 200k jobs was slow. Text keys were decoded row by row into UTF-16 code units, and timestamps were wrapped in date_trunc('milliseconds'). Both prevented index use. - Sort keys are now the stored columns: - timestamps (createdAt/startedAt/finishedAt/expiresAt) sort by stored precision; - status/actionName/description sort by `column COLLATE "C"`, which is byte order (Unicode code point order), independent of the database locale; - duration keeps its Number-precision key. NULLs stay last for asc and first for desc. - The id tie-break follows the direction of the last sort key (ascending with no sort key). The order stays total and deterministic, and one (column, id) index serves both directions. - Migration: (created_at, id), (started_at, id) and (status COLLATE "C", id) on jobs_active and jobs_archive. Verified with EXPLAIN on the SQL the adapter sends: Merge Append over Index Scan / Index Scan Backward for asc and desc, page 1 and page 200. idx_jobs_active_status stays: it is the default-collation index for status equality in claims, and the "C" index cannot serve it. - Tests: the listing tests now assert the new contract (code point text order, stored timestamp precision, direction-following id ties). A new test checks page stability when equal sort values span pages. Native and PGLite. - Docs: client-api and server-api describe the new order. --- packages/docs/content/docs/client-api.mdx | 16 +- packages/docs/content/docs/server-api.mdx | 10 +- .../migration.sql | 6 + .../snapshot.json | 277 ++++++++++++++++++ packages/duron/src/adapters/postgres/base.ts | 44 +-- .../duron/src/adapters/postgres/schema.ts | 9 + packages/duron/test/adapter.test.ts | 104 ++++++- 7 files changed, 409 insertions(+), 57 deletions(-) create mode 100644 packages/duron/migrations/postgres/20261130153037_silly_layla_miller/migration.sql create mode 100644 packages/duron/migrations/postgres/20261130153037_silly_layla_miller/snapshot.json diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index df1bdbc..c56ff96 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -466,11 +466,17 @@ Get matching jobs from active and archive storage with global sorting and pagina Job records include input, output, and error, but not steps. A terminal job restored to active storage remains visible under its status filter. -SQL adapters apply every requested sort key in order, then use job ID ascending to -break ties. An empty sort array uses only ID ascending. The default is `startedAt` -descending. Nulls sort last ascending and first descending; text uses JavaScript -UTF-16 lexical order, dates use public millisecond precision, and `duration` sorts -numeric `durationMs` (including fractional or negative values). +SQL adapters apply every requested sort key in order, then break ties by job ID in the +direction of the last sort key (ID descending when that key is descending). An empty +sort array uses only ID ascending. The order is total, so while the jobs do not change, +every job appears on exactly one page. The default is `startedAt` descending. Nulls +sort last ascending and first descending. Text (`status`, `actionName`, `description`) +uses byte order, which is Unicode code point order: it does not depend on the database +locale and, unlike JavaScript UTF-16 order, sorts characters above U+FFFF after +U+E000–U+FFFF. Dates sort by their stored microsecond precision, finer than the +millisecond `Date` values returned. `duration` sorts numeric `durationMs` (including +fractional or negative values). Sorts by `createdAt`, `startedAt` and `status` are +indexed in both storages. `total` counts all matching jobs even for an empty or out-of-range page. Count and page queries do not share a method-wide snapshot, and separate page requests do diff --git a/packages/docs/content/docs/server-api.mdx b/packages/docs/content/docs/server-api.mdx index b7876c2..4b2e375 100644 --- a/packages/docs/content/docs/server-api.mdx +++ b/packages/docs/content/docs/server-api.mdx @@ -180,10 +180,12 @@ Get matching jobs from active and archive storage with global sorting and pagina Job records include input, output, and error, but not steps. Restored terminal jobs remain visible under their status filters. -SQL adapters apply sort keys in the supplied order, followed by job ID ascending for -ties. The default sort is `startedAt:desc`. Nulls sort last ascending and first -descending; text follows JavaScript UTF-16 lexical order, dates use public millisecond -precision, and `duration` sorts numeric `durationMs`. +SQL adapters apply sort keys in the supplied order, followed by job ID for ties in the +direction of the last sort key, so pages are stable while the jobs do not change. The +default sort is `startedAt:desc`. Nulls sort last ascending and first descending; text +uses byte (Unicode code point) order, independent of the database locale; dates sort by +their stored microsecond precision; and `duration` sorts numeric `durationMs`. Sorts by +`createdAt`, `startedAt` and `status` are indexed. `total` includes all matching jobs even when the page is empty. Count and page are separate queries, not a method-wide or cross-request snapshot. At most `pageSize` diff --git a/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/migration.sql b/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/migration.sql new file mode 100644 index 0000000..b5432fc --- /dev/null +++ b/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/migration.sql @@ -0,0 +1,6 @@ +CREATE INDEX "idx_jobs_active_created_at_id" ON "duron"."jobs_active" ("created_at","id");--> statement-breakpoint +CREATE INDEX "idx_jobs_active_started_at_id" ON "duron"."jobs_active" ("started_at","id");--> statement-breakpoint +CREATE INDEX "idx_jobs_active_status_c_id" ON "duron"."jobs_active" ("status" COLLATE "C","id");--> statement-breakpoint +CREATE INDEX "idx_jobs_archive_created_at_id" ON "duron"."jobs_archive" ("created_at","id");--> statement-breakpoint +CREATE INDEX "idx_jobs_archive_started_at_id" ON "duron"."jobs_archive" ("started_at","id");--> statement-breakpoint +CREATE INDEX "idx_jobs_archive_status_c_id" ON "duron"."jobs_archive" ("status" COLLATE "C","id"); \ No newline at end of file diff --git a/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/snapshot.json b/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/snapshot.json new file mode 100644 index 0000000..f134d40 --- /dev/null +++ b/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/snapshot.json @@ -0,0 +1,277 @@ +{ + "type": "diff", + "version": "10", + "dialect": "postgres", + "id": "c4593ee7-008a-498f-9118-be27682c978e", + "prevIds": ["2669b14e-39af-408d-bed1-71acb119e105"], + "footprints": [ + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_created_at_id"], + "writes": [ + "s|idx|duron.idx_jobs_active_created_at_id", + "n|idx|duron.idx_jobs_active_created_at_id", + "e|idx|duron.idx_jobs_active_created_at_id", + "n|rel|duron.idx_jobs_active_created_at_id" + ], + "reads": [ + "n|tbl|duron.jobs_active", + "n|sch|duron", + "n|col|duron.jobs_active.created_at", + "n|col|duron.jobs_active.id" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_started_at_id"], + "writes": [ + "s|idx|duron.idx_jobs_active_started_at_id", + "n|idx|duron.idx_jobs_active_started_at_id", + "e|idx|duron.idx_jobs_active_started_at_id", + "n|rel|duron.idx_jobs_active_started_at_id" + ], + "reads": [ + "n|tbl|duron.jobs_active", + "n|sch|duron", + "n|col|duron.jobs_active.started_at", + "n|col|duron.jobs_active.id" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_active", "idx_jobs_active_status_c_id"], + "writes": [ + "s|idx|duron.idx_jobs_active_status_c_id", + "n|idx|duron.idx_jobs_active_status_c_id", + "e|idx|duron.idx_jobs_active_status_c_id", + "n|rel|duron.idx_jobs_active_status_c_id" + ], + "reads": ["n|tbl|duron.jobs_active", "n|sch|duron", "n|col|duron.jobs_active.id"] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_created_at_id"], + "writes": [ + "s|idx|duron.idx_jobs_archive_created_at_id", + "n|idx|duron.idx_jobs_archive_created_at_id", + "e|idx|duron.idx_jobs_archive_created_at_id", + "n|rel|duron.idx_jobs_archive_created_at_id" + ], + "reads": [ + "n|tbl|duron.jobs_archive", + "n|sch|duron", + "n|col|duron.jobs_archive.created_at", + "n|col|duron.jobs_archive.id" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_started_at_id"], + "writes": [ + "s|idx|duron.idx_jobs_archive_started_at_id", + "n|idx|duron.idx_jobs_archive_started_at_id", + "e|idx|duron.idx_jobs_archive_started_at_id", + "n|rel|duron.idx_jobs_archive_started_at_id" + ], + "reads": [ + "n|tbl|duron.jobs_archive", + "n|sch|duron", + "n|col|duron.jobs_archive.started_at", + "n|col|duron.jobs_archive.id" + ] + }, + { + "statementType": "create_index", + "statementTarget": ["index", "duron", "jobs_archive", "idx_jobs_archive_status_c_id"], + "writes": [ + "s|idx|duron.idx_jobs_archive_status_c_id", + "n|idx|duron.idx_jobs_archive_status_c_id", + "e|idx|duron.idx_jobs_archive_status_c_id", + "n|rel|duron.idx_jobs_archive_status_c_id" + ], + "reads": ["n|tbl|duron.jobs_archive", "n|sch|duron", "n|col|duron.jobs_archive.id"] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_created_at_id", + "nameExplicit": true, + "columns": [ + { + "value": "created_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_started_at_id", + "nameExplicit": true, + "columns": [ + { + "value": "started_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "duron", + "table": "jobs_active", + "name": "idx_jobs_active_status_c_id", + "nameExplicit": true, + "columns": [ + { + "value": "\"status\" COLLATE \"C\"", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_created_at_id", + "nameExplicit": true, + "columns": [ + { + "value": "created_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_started_at_id", + "nameExplicit": true, + "columns": [ + { + "value": "started_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "duron", + "table": "jobs_archive", + "name": "idx_jobs_archive_status_c_id", + "nameExplicit": true, + "columns": [ + { + "value": "\"status\" COLLATE \"C\"", + "isExpression": true, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "entityType": "indexes" + } + } + ] +} diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 763039f..eaeaaf1 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -2107,50 +2107,30 @@ export abstract class PostgresBaseAdapter< .from(matchingIds) const sortInput = options?.sort ?? { field: 'startedAt', order: 'desc' } const sorts = Array.isArray(sortInput) ? sortInput : [sortInput] + // Sort keys are the stored columns so the per-table (column, id) indexes can serve them + // (Merge Append over index scans of jobs_active and jobs_archive): + // - timestamps sort by their stored (microsecond) precision; + // - text sorts by byte order (`COLLATE "C"`, Unicode code point order for UTF-8), + // independent of the database locale; + // - duration is computed, so it has no index; its key is the public Number precision. + // asc places NULLs last and desc first; a btree index scans forward or backward for these. const order = sorts.map((sort) => { const column = matching[sort.field === 'duration' ? 'durationMs' : sort.field] let key = sql`${column}` if (sort.field === 'description' || sort.field === 'actionName' || sort.field === 'status') { - // SQL locale/code-point order differs from JS UTF-16 lexical order. Decode explicitly - // converted UTF8 bytes, then emit BMP units or surrogate pairs without installing a function. - key = sql`CASE WHEN ${column} IS NULL THEN NULL ELSE ARRAY( - SELECT unit FROM generate_series(1, char_length(${column})) AS positions(pos) - CROSS JOIN LATERAL ( - SELECT convert_to(substr(${column}, positions.pos, 1), 'UTF8') AS bytes - ) AS encoded - CROSS JOIN LATERAL (SELECT CASE octet_length(bytes) - WHEN 1 THEN get_byte(bytes, 0) - WHEN 2 THEN (get_byte(bytes, 0) - 192) * 64 + get_byte(bytes, 1) - 128 - WHEN 3 THEN (get_byte(bytes, 0) - 224) * 4096 - + (get_byte(bytes, 1) - 128) * 64 + get_byte(bytes, 2) - 128 - WHEN 4 THEN (get_byte(bytes, 0) - 240) * 262144 - + (get_byte(bytes, 1) - 128) * 4096 - + (get_byte(bytes, 2) - 128) * 64 + get_byte(bytes, 3) - 128 - END AS codepoint) AS decoded - CROSS JOIN LATERAL unnest(CASE WHEN codepoint < 65536 THEN ARRAY[codepoint] - ELSE ARRAY[55296 + ((codepoint - 65536) / 1024), - 56320 + ((codepoint - 65536) % 1024)] END) - WITH ORDINALITY AS units(unit, ordinal) - ORDER BY positions.pos, units.ordinal - ) END` - } else if ( - sort.field === 'createdAt' || - sort.field === 'startedAt' || - sort.field === 'finishedAt' || - sort.field === 'expiresAt' - ) { - // Match the selected timestamp's ORM Date precision, including before the epoch. - key = sql`date_trunc('milliseconds', ${column})` + key = sql`${column} COLLATE "C"` } else if (sort.field === 'duration') { - // The public duration is a Number, so SQL-only extra precision must not break its ties. key = sql`${column}::double precision` } return sql`${key} ${sql.raw(sort.order === 'asc' ? 'ASC NULLS LAST' : 'DESC NULLS FIRST')}` }) + // The id tie-break follows the direction of the last sort key, so one (column, id) index + // serves both directions. The order stays total and deterministic, so pages are stable. + const tieBreak = (sorts.at(-1)?.order ?? 'asc') === 'asc' ? 'ASC' : 'DESC' const jobs = await this.db .select() .from(matching) - .orderBy(...order, sql`${matching.id} ASC`) + .orderBy(...order, sql`${matching.id} ${sql.raw(tieBreak)}`) .offset((page - 1) * pageSize) .limit(pageSize) diff --git a/packages/duron/src/adapters/postgres/schema.ts b/packages/duron/src/adapters/postgres/schema.ts index 1f1f76f..092f4a2 100644 --- a/packages/duron/src/adapters/postgres/schema.ts +++ b/packages/duron/src/adapters/postgres/schema.ts @@ -68,6 +68,11 @@ export default function createSchema(schemaName: string) { index('idx_jobs_active_checksum').on(table.checksum), // Composite indexes index('idx_jobs_active_action_group').on(table.action_name, table.group_key), + // Job listing sorts (getJobs): key + id tie-break, scanned forward for asc and backward + // for desc. Status sorts by byte order, so its index uses the "C" collation. + index('idx_jobs_active_created_at_id').on(table.created_at, table.id), + index('idx_jobs_active_started_at_id').on(table.started_at, table.id), + index('idx_jobs_active_status_c_id').on(sql`${table.status} COLLATE "C"`, table.id), check( 'jobs_active_status_check', sql`${table.status} IN ${sql.raw(`(${JOB_STATUSES.map((s) => `'${s}'`).join(',')})`)}`, @@ -161,6 +166,10 @@ export default function createSchema(schemaName: string) { index('idx_jobs_archive_finished_at').on(table.finished_at), // Composite indexes index('idx_jobs_archive_action_group').on(table.action_name, table.group_key), + // Job listing sorts (getJobs), as on jobs_active. + index('idx_jobs_archive_created_at_id').on(table.created_at, table.id), + index('idx_jobs_archive_started_at_id').on(table.started_at, table.id), + index('idx_jobs_archive_status_c_id').on(sql`${table.status} COLLATE "C"`, table.id), // GIN indexes for full-text search (dashboard search) index('idx_jobs_archive_input_fts').using( 'gin', diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index bf7dccc..8eb5798 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -683,7 +683,9 @@ function runAdapterTests(adapterFactory: AdapterFactory) { } }) - it('should preserve secondary keys and final ID ties, including empty sorts (seeded keys)', async () => { + // Listing order contract: the sort keys, then `id` in the direction of the last sort key + // (ascending when there are no sort keys). The order is total, so pages are stable. + it('should preserve secondary keys and direction-following ID ties, including empty sorts (seeded keys)', async () => { const ids = await createListingJobs(4) for (const [rank, id] of ids.entries()) { const storage = rank % 2 === 0 ? 'active' : 'archive' @@ -702,26 +704,87 @@ function runAdapterTests(adapterFactory: AdapterFactory) { { field: 'createdAt', order: 'desc' }, ], }) - expect(secondary.jobs.map((job) => job.id)).toEqual([ids[1]!, ids[2]!, ids[3]!, ids[0]!]) + // ranks 2 and 3 tie on both keys; the last key is desc, so the id tie-break is desc too + expect(secondary.jobs.map((job) => job.id)).toEqual([ids[1]!, ids[3]!, ids[2]!, ids[0]!]) expect(secondary.total).toBe(4) - for (const sort of [ - [], - [{ field: 'description', order: 'desc' }], + for (const [sort, expected] of [ + [[], ids], + [[{ field: 'description', order: 'asc' }], ids], + [[{ field: 'description', order: 'desc' }], ids.toReversed()], [ - { field: 'description', order: 'asc' }, - { field: 'description', order: 'desc' }, + [ + { field: 'description', order: 'asc' }, + { field: 'description', order: 'desc' }, + ], + ids.toReversed(), + ], + [ + [ + { field: 'description', order: 'desc' }, + { field: 'description', order: 'asc' }, + ], + ids, ], ] as const) { for (const page of [1, 2, 2, 3]) { const result = await adapter.getJobs({ page, pageSize: 2, sort: [...sort] }) - expect(result.jobs.map((job) => job.id)).toEqual(ids.slice((page - 1) * 2, page * 2)) + expect(result.jobs.map((job) => job.id)).toEqual( + expected.slice((page - 1) * 2, page * 2), + ) expect(result.total).toBe(4) } } }) + it('should keep pages stable when equal sort values span page boundaries (seeded keys)', async () => { + // Two createdAt groups (3 + 4 jobs) over both storages; page size 2 splits every group. + const ids = await createListingJobs(7) + const groups = [1, 0, 1, 0, 1, 0, 0] + for (const [rank, id] of ids.entries()) { + const storage = rank % 2 === 0 ? 'active' : 'archive' + if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) + await seedListingJob( + id, + storage, + sql`created_at = ${`2026-01-0${groups[rank]! + 1}T00:00:00Z`}::timestamptz`, + ) + } + // Ranks follow id order, so key-then-id ascending is a sort by (key, rank). + const byKey = (key: (rank: number) => string | number) => + ids + .map((_, rank) => rank) + .toSorted((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : a - b)) + for (const [field, ascending] of [ + ['createdAt', byKey((rank) => groups[rank]!)], + ['status', byKey((rank) => (rank % 2 === 0 ? JOB_STATUS_CREATED : JOB_STATUS_CANCELLED))], + ['startedAt', byKey(() => 0)], // all NULL: one tie group + ] as const) { + for (const order of ['asc', 'desc'] as const) { + // desc is the exact reverse of asc: NULLS FIRST and the id tie-break flip with it + const expected = (order === 'asc' ? ascending : ascending.toReversed()).map( + (rank) => ids[rank]!, + ) + const whole = await adapter.getJobs({ pageSize: 100, sort: { field, order } }) + expect(whole.jobs.map((job) => job.id)).toEqual(expected) + const paged: string[] = [] + for (let page = 1; page <= 4; page++) { + const first = await adapter.getJobs({ page, pageSize: 2, sort: { field, order } }) + const again = await adapter.getJobs({ page, pageSize: 2, sort: { field, order } }) + expect(again.jobs.map((job) => job.id)).toEqual(first.jobs.map((job) => job.id)) + expect(first.total).toBe(7) + paged.push(...first.jobs.map((job) => job.id)) + } + expect(paged).toEqual(expected) + expect(new Set(paged).size).toBe(7) + } + } + }) + for (const field of ['description', 'actionName'] as const) { - it(`should order ${field} by UTF-16 units with prefixes and nulls (seeded text)`, async () => { + // Text sorts by byte order (COLLATE "C"), i.e. Unicode code point order for UTF-8. This is + // not JS UTF-16 order: U+E000..U+FFFF sort before supplementary characters (U+10000+), + // whose UTF-16 surrogates would sort first. It does not depend on the database locale. + it(`should order ${field} by code point (byte) order with prefixes and nulls (seeded text)`, async () => { const values = [ '\uE000', '\u{10000}', @@ -748,10 +811,12 @@ function runAdapterTests(adapterFactory: AdapterFactory) { sql`${sql.identifier(field === 'actionName' ? 'action_name' : field)} = ${value}`, ) } + // '' < 'A' < 'a' < 'a\uE000' < 'a\u{10000}' < 'e\u0301' < ('z') < 'é' < '\uD7FF' + // < '\uE000' < '\uFFFF' < '\u{10000}' < '\u{10FFFF}' < null (asc, NULLS LAST) const ascending = field === 'description' - ? [4, 12, 5, 3, 2, 11, 10, 8, 1, 9, 0, 7, 6] - : [4, 12, 5, 3, 2, 11, 6, 10, 8, 1, 9, 0, 7] + ? [4, 12, 5, 2, 3, 11, 10, 8, 0, 7, 1, 9, 6] + : [4, 12, 5, 2, 3, 11, 6, 10, 8, 0, 7, 1, 9] for (const order of ['asc', 'desc'] as const) { const expected = order === 'asc' ? ascending : ascending.toReversed() for (let page = 1; page <= 6; page++) { @@ -775,7 +840,9 @@ function runAdapterTests(adapterFactory: AdapterFactory) { ['finishedAt', 'finished_at'], ['expiresAt', 'expires_at'], ] as const) { - it(`should order ${field} by public Date milliseconds (seeded native precision)`, async () => { + // Timestamps sort by their stored (microsecond) precision, so jobs whose public Dates show + // the same millisecond still have a definite order; NULLs last for asc, first for desc. + it(`should order ${field} by stored timestamp precision (seeded native precision)`, async () => { const timestamps = [ '1970-01-01T00:00:00.000900Z', '1970-01-01T00:00:00.000100Z', @@ -798,9 +865,11 @@ function runAdapterTests(adapterFactory: AdapterFactory) { ) } for (const order of ['asc', 'desc'] as const) { - const nulls = field === 'createdAt' ? [] : [7, 8] + // the two NULLs tie: id tie-break follows the direction (asc 7, 8; desc 8, 7) + const nulls = field === 'createdAt' ? [] : order === 'asc' ? [7, 8] : [8, 7] + const ascending = [6, 4, 3, 5, 1, 0, 2] const expected = - order === 'asc' ? [6, 3, 4, 0, 1, 5, 2, ...nulls] : [...nulls, 2, 0, 1, 5, 3, 4, 6] + order === 'asc' ? [...ascending, ...nulls] : [...nulls, ...ascending.toReversed()] for (let page = 1; page <= 4; page++) { const result = await adapter.getJobs({ page, pageSize: 3, sort: { field, order } }) expect(result.jobs.map((job) => job.id)).toEqual( @@ -835,7 +904,9 @@ function runAdapterTests(adapterFactory: AdapterFactory) { ) } for (const order of ['asc', 'desc'] as const) { - const expected = order === 'asc' ? [5, 2, 3, 1, 0, 6, 7, 4] : [4, 6, 7, 0, 1, 3, 2, 5] + // ranks 6 and 7 tie as Numbers (sub-millisecond SQL difference); the id tie-break follows + // the direction of the last sort key + const expected = order === 'asc' ? [5, 2, 3, 1, 0, 6, 7, 4] : [4, 7, 6, 0, 1, 3, 2, 5] for (const sort of [ [{ field: 'duration', order }], [ @@ -887,8 +958,9 @@ function runAdapterTests(adapterFactory: AdapterFactory) { expect(result.total).toBe(expected.length) } } + // Default sort is startedAt desc; all are unstarted (NULL) ties, so id desc const defaults = await adapter.getJobs() - expect(defaults.jobs.map((job) => job.id)).toEqual(ids) + expect(defaults.jobs.map((job) => job.id)).toEqual(ids.toReversed()) expect(defaults).toMatchObject({ total: 6, page: 1, pageSize: 10 }) const statuses = await adapter.getJobs({ sort: { field: 'status', order: 'asc' } }) expect(statuses.jobs.map((job) => job.id)).toEqual([ From 3130cda2170008bbcad2c652e2c4c83aa2e04114 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 13:19:06 -0300 Subject: [PATCH 048/100] docs(listing): migration locking and pre-build path; IF NOT EXISTS indexes Review fixes for the job listing indexes (84befb0): - migration.sql: CREATE INDEX IF NOT EXISTS for the six listing indexes (the drizzle snapshot is unchanged; drizzle-kit generate reports no changes). Operators can pre-build them with CREATE INDEX CONCURRENTLY and the migration builds nothing. Checked on an existing 205k-job install: the pre-built indexes keep their OID and relfilenode through the upgrade. On a fresh database the migration creates them with identical definitions. - adapters.mdx (Migrations): Duron applies pending migrations in one transaction, so writes to jobs_active and jobs_archive are blocked until it commits, for a time that grows with table size. Documents the options (maintenance window or a single migrating instance) and the exact CONCURRENTLY statements, plus a validity check for failed concurrent builds. - client-api/server-api: byte order is code point order in a UTF-8 database; only unfiltered createdAt/startedAt/status sorts are index-served. - Page-stability test: seed in a non-monotonic order, so ascending also fails without the id tie-break (mutation-checked). --- packages/docs/content/docs/adapters.mdx | 58 +++++++++++++++++++ packages/docs/content/docs/client-api.mdx | 11 ++-- packages/docs/content/docs/server-api.mdx | 7 ++- .../migration.sql | 12 ++-- packages/duron/test/adapter.test.ts | 5 +- 5 files changed, 78 insertions(+), 15 deletions(-) diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 9f82137..eb6cf01 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -159,6 +159,64 @@ To generate new migrations: bun run generate:postgres ``` +#### Upgrading to the job listing indexes + +The migration `20261130153037_silly_layla_miller` adds six btree indexes that serve the job +listing sorts by `createdAt`, `startedAt` and `status`, on both `jobs_active` and `jobs_archive`. +It is the first migration that existing installations apply to populated tables. + +Duron applies all pending migrations in one transaction. Each `CREATE INDEX` holds a lock on its +table until that transaction commits, so **writes to both `jobs_active` and `jobs_archive` are +blocked until the whole migration finishes**: creating jobs, claiming, completing, moving jobs to +the archive and pruning wait; reads continue. In a rolling deploy, instances still running the +previous version stall on every write for that time. The time grows with the size of the tables: +about 0.3 seconds for 200,000 archived jobs in our tests, growing roughly linearly, so expect a +minute or more for tens of millions. + +For small tables nothing needs to be done. For large tables, either: + +- run the upgrade in a maintenance window, or start a single instance with `migrateOnStart` while + the other instances are stopped; or +- build the indexes beforehand without blocking writes. The migration creates them with + `CREATE INDEX IF NOT EXISTS` under the same names, so with the indexes already in place it + builds nothing and only takes the table locks briefly. + +To build them beforehand, run these statements against the database while the current version +keeps running. `CREATE INDEX CONCURRENTLY` cannot run inside a transaction block, so run each +statement on its own (for example with `psql`, which runs each `-c` statement in autocommit +mode). The names, columns and collation must be exactly these: + +```sql +CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_active_created_at_id" ON "duron"."jobs_active" ("created_at", "id"); +CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_active_started_at_id" ON "duron"."jobs_active" ("started_at", "id"); +CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_active_status_c_id" ON "duron"."jobs_active" ("status" COLLATE "C", "id"); +CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_archive_created_at_id" ON "duron"."jobs_archive" ("created_at", "id"); +CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_archive_started_at_id" ON "duron"."jobs_archive" ("started_at", "id"); +CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_jobs_archive_status_c_id" ON "duron"."jobs_archive" ("status" COLLATE "C", "id"); +``` + +A concurrent build that fails or is cancelled leaves an invalid index with that name, and +`IF NOT EXISTS` would then skip it. Before upgrading, check that all six indexes are valid: + +```sql +SELECT c.relname, i.indisvalid +FROM pg_index i +JOIN pg_class c ON c.oid = i.indexrelid +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE n.nspname = 'duron' AND c.relname IN ( + 'idx_jobs_active_created_at_id', 'idx_jobs_active_started_at_id', 'idx_jobs_active_status_c_id', + 'idx_jobs_archive_created_at_id', 'idx_jobs_archive_started_at_id', 'idx_jobs_archive_status_c_id' +); +``` + +For any row with `indisvalid = false`, run `DROP INDEX CONCURRENTLY "duron"."";` and run its +`CREATE INDEX CONCURRENTLY` statement again. + +If you manage Duron's tables with your own Drizzle migrations (see below), the generated +migration contains plain `CREATE INDEX` statements in your schema: the same locking applies, and +you can pre-build the indexes the same way in your schema and add `IF NOT EXISTS` to your +migration. + ## Integrating Duron Schema into Your Own Drizzle Schema If you're already using Drizzle ORM in your project and want to manage all migrations together, you can include Duron's schema in your own Drizzle schema instead of using Duron's automatic migrations. diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index c56ff96..0eebfc2 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -471,12 +471,13 @@ direction of the last sort key (ID descending when that key is descending). An e sort array uses only ID ascending. The order is total, so while the jobs do not change, every job appears on exactly one page. The default is `startedAt` descending. Nulls sort last ascending and first descending. Text (`status`, `actionName`, `description`) -uses byte order, which is Unicode code point order: it does not depend on the database -locale and, unlike JavaScript UTF-16 order, sorts characters above U+FFFF after -U+E000–U+FFFF. Dates sort by their stored microsecond precision, finer than the +uses byte order (Unicode code point order in a UTF-8 database): it does not depend on +the database locale and, unlike JavaScript UTF-16 order, sorts characters above U+FFFF +after U+E000–U+FFFF. Dates sort by their stored microsecond precision, finer than the millisecond `Date` values returned. `duration` sorts numeric `durationMs` (including -fractional or negative values). Sorts by `createdAt`, `startedAt` and `status` are -indexed in both storages. +fractional or negative values). Unfiltered sorts by `createdAt`, `startedAt` and +`status` use indexes in both storages; with filters (for example a status filter), the +database may scan and sort the matching jobs instead. `total` counts all matching jobs even for an empty or out-of-range page. Count and page queries do not share a method-wide snapshot, and separate page requests do diff --git a/packages/docs/content/docs/server-api.mdx b/packages/docs/content/docs/server-api.mdx index 4b2e375..f3aa1f2 100644 --- a/packages/docs/content/docs/server-api.mdx +++ b/packages/docs/content/docs/server-api.mdx @@ -183,9 +183,10 @@ remain visible under their status filters. SQL adapters apply sort keys in the supplied order, followed by job ID for ties in the direction of the last sort key, so pages are stable while the jobs do not change. The default sort is `startedAt:desc`. Nulls sort last ascending and first descending; text -uses byte (Unicode code point) order, independent of the database locale; dates sort by -their stored microsecond precision; and `duration` sorts numeric `durationMs`. Sorts by -`createdAt`, `startedAt` and `status` are indexed. +uses byte order (Unicode code point order in a UTF-8 database), independent of the +database locale; dates sort by their stored microsecond precision; and `duration` sorts +numeric `durationMs`. Unfiltered sorts by `createdAt`, `startedAt` and `status` use +indexes; filtered listings may scan and sort the matching jobs instead. `total` includes all matching jobs even when the page is empty. Count and page are separate queries, not a method-wide or cross-request snapshot. At most `pageSize` diff --git a/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/migration.sql b/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/migration.sql index b5432fc..84dfd8b 100644 --- a/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/migration.sql +++ b/packages/duron/migrations/postgres/20261130153037_silly_layla_miller/migration.sql @@ -1,6 +1,6 @@ -CREATE INDEX "idx_jobs_active_created_at_id" ON "duron"."jobs_active" ("created_at","id");--> statement-breakpoint -CREATE INDEX "idx_jobs_active_started_at_id" ON "duron"."jobs_active" ("started_at","id");--> statement-breakpoint -CREATE INDEX "idx_jobs_active_status_c_id" ON "duron"."jobs_active" ("status" COLLATE "C","id");--> statement-breakpoint -CREATE INDEX "idx_jobs_archive_created_at_id" ON "duron"."jobs_archive" ("created_at","id");--> statement-breakpoint -CREATE INDEX "idx_jobs_archive_started_at_id" ON "duron"."jobs_archive" ("started_at","id");--> statement-breakpoint -CREATE INDEX "idx_jobs_archive_status_c_id" ON "duron"."jobs_archive" ("status" COLLATE "C","id"); \ No newline at end of file +CREATE INDEX IF NOT EXISTS "idx_jobs_active_created_at_id" ON "duron"."jobs_active" ("created_at","id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "idx_jobs_active_started_at_id" ON "duron"."jobs_active" ("started_at","id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "idx_jobs_active_status_c_id" ON "duron"."jobs_active" ("status" COLLATE "C","id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "idx_jobs_archive_created_at_id" ON "duron"."jobs_archive" ("created_at","id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "idx_jobs_archive_started_at_id" ON "duron"."jobs_archive" ("started_at","id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "idx_jobs_archive_status_c_id" ON "duron"."jobs_archive" ("status" COLLATE "C","id"); \ No newline at end of file diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index 8eb5798..8987d43 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -740,7 +740,10 @@ function runAdapterTests(adapterFactory: AdapterFactory) { // Two createdAt groups (3 + 4 jobs) over both storages; page size 2 splits every group. const ids = await createListingJobs(7) const groups = [1, 0, 1, 0, 1, 0, 0] - for (const [rank, id] of ids.entries()) { + // Archive and seed in a non-monotonic rank (= id) order, so the physical row order is + // neither id ascending nor descending: both directions fail without the id tie-break. + for (const rank of [3, 0, 6, 2, 5, 1, 4]) { + const id = ids[rank]! const storage = rank % 2 === 0 ? 'active' : 'archive' if (storage === 'archive') expect(await adapter.cancelJob({ jobId: id })).toBe(true) await seedListingJob( From e0bff4f1b82501a4698027c597eb35c699105108 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 13:51:22 -0300 Subject: [PATCH 049/100] chore(dashboard): remove unreachable code and its dependencies An import graph from every dashboard entry point found 16 files that nothing reaches. The entry points: the package exports' dev-source/types (index.tsx, init.tsx, get-html.ts, types/*.d.ts), build.ts (index.tsx, init.tsx, index.html), dev.tsx and css.d.ts. Removed files: - data-table: action-bar, advanced-toolbar, filter-list, filter-menu, range-filter, skeleton, view-options - ui (shadcn, unreachable): calendar, checkbox, faceted, skeleton, tabs - hooks/use-copy-to-clipboard, lib/data-table, lib/id, views/job-io Removed the dependencies only those files used: motion, nanoid, react-day-picker, @radix-ui/react-checkbox. The date filter imported react-day-picker only for the DateRange type; it now declares the same shape locally. The published dist JS is unchanged (the removed code was already tree-shaken). The dist CSS shrinks (index.css 77.6 -> 66.7 KB, init.css 96.6 -> 86.4 KB), and the package drops from 107 to 91 files. --- bun.lock | 14 +- packages/duron-dashboard/package.json | 4 - .../data-table/data-table-action-bar.tsx | 162 ---- .../data-table-advanced-toolbar.tsx | 33 - .../data-table/data-table-date-filter.tsx | 4 +- .../data-table/data-table-filter-list.tsx | 726 ---------------- .../data-table/data-table-filter-menu.tsx | 797 ------------------ .../data-table/data-table-range-filter.tsx | 112 --- .../data-table/data-table-skeleton.tsx | 110 --- .../data-table/data-table-view-options.tsx | 78 -- .../src/components/ui/calendar.tsx | 180 ---- .../src/components/ui/checkbox.tsx | 27 - .../src/components/ui/faceted.tsx | 257 ------ .../src/components/ui/skeleton.tsx | 13 - .../src/components/ui/tabs.tsx | 82 -- .../src/hooks/use-copy-to-clipboard.ts | 32 - .../duron-dashboard/src/lib/data-table.ts | 67 -- packages/duron-dashboard/src/lib/id.ts | 25 - packages/duron-dashboard/src/views/job-io.tsx | 61 -- 19 files changed, 4 insertions(+), 2780 deletions(-) delete mode 100644 packages/duron-dashboard/src/components/data-table/data-table-action-bar.tsx delete mode 100644 packages/duron-dashboard/src/components/data-table/data-table-advanced-toolbar.tsx delete mode 100644 packages/duron-dashboard/src/components/data-table/data-table-filter-list.tsx delete mode 100644 packages/duron-dashboard/src/components/data-table/data-table-filter-menu.tsx delete mode 100644 packages/duron-dashboard/src/components/data-table/data-table-range-filter.tsx delete mode 100644 packages/duron-dashboard/src/components/data-table/data-table-skeleton.tsx delete mode 100644 packages/duron-dashboard/src/components/data-table/data-table-view-options.tsx delete mode 100644 packages/duron-dashboard/src/components/ui/calendar.tsx delete mode 100644 packages/duron-dashboard/src/components/ui/checkbox.tsx delete mode 100644 packages/duron-dashboard/src/components/ui/faceted.tsx delete mode 100644 packages/duron-dashboard/src/components/ui/skeleton.tsx delete mode 100644 packages/duron-dashboard/src/components/ui/tabs.tsx delete mode 100644 packages/duron-dashboard/src/hooks/use-copy-to-clipboard.ts delete mode 100644 packages/duron-dashboard/src/lib/data-table.ts delete mode 100644 packages/duron-dashboard/src/lib/id.ts delete mode 100644 packages/duron-dashboard/src/views/job-io.tsx diff --git a/bun.lock b/bun.lock index b8e5754..588c8b6 100644 --- a/bun.lock +++ b/bun.lock @@ -89,7 +89,6 @@ "@maskito/react": "^5.6.1", "@monaco-editor/react": "^4.7.0", "@radix-ui/react-accordion": "^1.3.1", - "@radix-ui/react-checkbox": "^1.4.1", "@radix-ui/react-dialog": "^1.3.1", "@radix-ui/react-dropdown-menu": "^2.2.1", "@radix-ui/react-label": "^2.1.17", @@ -109,11 +108,8 @@ "cmdk": "^1.1.1", "date-fns": "^4.4.0", "lucide-react": "^1.84.0", - "motion": "^14.14.0", - "nanoid": "^6.0.2", "nuqs": "^2.10.3", "react": "^19.3.1", - "react-day-picker": "^10.0.2", "react-dom": "^19.3.1", "react-resizable-panels": "^4.27.0", "tailwind-merge": "^3.7.1", @@ -202,8 +198,6 @@ "@borewit/text-codec": ["@borewit/text-codec@0.2.3", "", {}, "sha512-49CycTz1aAZmvFcwkeFyhud1HUmRIB5Tabf7ALV+VA4Iu85MTfz2cUwzPagMFAdVBvrWdkCxG67I30tUwwpKsw=="], - "@date-fns/tz": ["@date-fns/tz@1.5.0", "", {}, "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg=="], - "@dnd-kit/accessibility": ["@dnd-kit/accessibility@3.1.1", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw=="], "@dnd-kit/core": ["@dnd-kit/core@6.3.1", "", { "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ=="], @@ -440,8 +434,6 @@ "@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.17", "", { "dependencies": { "@radix-ui/react-primitive": "2.2.0" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-67jjcVvxjXCCStnTW3Z+M7jmaFMuMR7M2JgpDzH4w7JSRrikmzhjfYgP/09ECb8n7whnsgh1ifJ+Ie96qEj+pQ=="], - "@radix-ui/react-checkbox": ["@radix-ui/react-checkbox@1.4.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-size": "1.1.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-KWtwhh+98ML3seZ9vO9yRY2OwaQG90dCiDAxjpSNY2AaZ3Hik3B0dsk6m0ILywo/no3A9/SozadyPMNweVT8yw=="], - "@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.2.1", "", { "dependencies": { "@radix-ui/primitive": "1.2.0", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.11", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-use-controllable-state": "1.3.0", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-fSzLb/qy1wuZSxQBcxpW0hNXYHDMWiIXDGyJGdA4+FSLknOWZsNRrTCUavxb4PI8b8lvHo/CysO6NVi5zLpo5g=="], "@radix-ui/react-collection": ["@radix-ui/react-collection@1.2.0", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.3.0", "@radix-ui/react-primitive": "2.2.0", "@radix-ui/react-slot": "1.5.0", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-+yiQzqcc7Sy7/5s0jrMCjpPRFB3538VNrXPWdTLZhE/SCfgEws4aI6lHWN/vvcnyhHndROWBzqmqB4QBrITZ9Q=="], @@ -1200,7 +1192,7 @@ "ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="], - "nanoid": ["nanoid@6.0.2", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-hIvVOb9Qr1p/9CNNLOe0OlWvgx/ziTsVwKN/GDSsuArN2K0wDiafP3s0SWmsm7o2BdnyS8Z9Z64NFBUbn6ziBg=="], + "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], "napi-windows-process-start-time": ["napi-windows-process-start-time@0.1.0", "", { "os": "win32", "cpu": [ "x64", "arm64", ] }, "sha512-zHxhzKsIFu3elch3eFw69WEUGc79DFhbc3nD/WEOzWL/pFFLZRW13EHnuO0c+0YjncE5uCaS9ICHxOBXkb6vPw=="], @@ -1266,8 +1258,6 @@ "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], - "react-day-picker": ["react-day-picker@10.0.2", "", { "dependencies": { "@date-fns/tz": "^1.4.1", "date-fns": "^4.1.0" }, "peerDependencies": { "@types/react": ">=16.8.0", "react": ">=16.8.0" }, "optionalPeers": ["@types/react"] }, "sha512-QetiKtZWE9Uaw/pM/SYNv6WPYOTRnSJ2puL0GgwkmUFMIwiY0dtjH1W4B7DOVXVNQM0ZOClGpH/heOfBSzWeiA=="], - "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], "react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="], @@ -1510,8 +1500,6 @@ "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], - "postcss/nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], - "serve-handler/bytes": ["bytes@3.0.0", "", {}, "sha512-pMhOfFDPiv9t5jjIXkHosWmkSyQbvsgEVNkz0ERHbuLh2T/7j4Mqqpz523Fe8MVY89KC6Sh/QfS2sM+SjgFDcw=="], "@babel/core/debug/ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], diff --git a/packages/duron-dashboard/package.json b/packages/duron-dashboard/package.json index cb351dc..b44cf99 100644 --- a/packages/duron-dashboard/package.json +++ b/packages/duron-dashboard/package.json @@ -44,7 +44,6 @@ "@maskito/react": "^5.6.1", "@monaco-editor/react": "^4.7.0", "@radix-ui/react-accordion": "^1.3.1", - "@radix-ui/react-checkbox": "^1.4.1", "@radix-ui/react-dialog": "^1.3.1", "@radix-ui/react-dropdown-menu": "^2.2.1", "@radix-ui/react-label": "^2.1.17", @@ -64,11 +63,8 @@ "cmdk": "^1.1.1", "date-fns": "^4.4.0", "lucide-react": "^1.84.0", - "motion": "^14.14.0", - "nanoid": "^6.0.2", "nuqs": "^2.10.3", "react": "^19.3.1", - "react-day-picker": "^10.0.2", "react-dom": "^19.3.1", "react-resizable-panels": "^4.27.0", "tailwind-merge": "^3.7.1", diff --git a/packages/duron-dashboard/src/components/data-table/data-table-action-bar.tsx b/packages/duron-dashboard/src/components/data-table/data-table-action-bar.tsx deleted file mode 100644 index 7e73fe3..0000000 --- a/packages/duron-dashboard/src/components/data-table/data-table-action-bar.tsx +++ /dev/null @@ -1,162 +0,0 @@ -'use client' - -import type { RowData, Table } from '@tanstack/react-table' -import { Loader, X } from 'lucide-react' -import { AnimatePresence, motion } from 'motion/react' -import * as React from 'react' -import * as ReactDOM from 'react-dom' - -import { Button } from '@/components/ui/button' -import { Separator } from '@/components/ui/separator' -import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import type { DataTableFeatures } from '@/lib/data-table-features' -import { cn } from '@/lib/utils' - -interface DataTableActionBarProps extends React.ComponentProps< - typeof motion.div -> { - table: Table - visible?: boolean - portalContainer?: Element | DocumentFragment | null -} - -function DataTableActionBar({ - table, - visible: visibleProp, - portalContainer: portalContainerProp, - children, - className, - ...props -}: DataTableActionBarProps) { - const [mounted, setMounted] = React.useState(false) - - React.useLayoutEffect(() => { - setMounted(true) - }, []) - - React.useEffect(() => { - function onKeyDown(event: KeyboardEvent) { - if (event.key === 'Escape') { - table.toggleAllRowsSelected(false) - } - } - - window.addEventListener('keydown', onKeyDown) - return () => window.removeEventListener('keydown', onKeyDown) - }, [table]) - - const portalContainer = portalContainerProp ?? (mounted ? globalThis.document?.body : null) - - if (!portalContainer) return null - - const visible = visibleProp ?? table.getFilteredSelectedRowModel().rows.length > 0 - - return ReactDOM.createPortal( - - {visible && ( - - {children} - - )} - , - portalContainer, - ) -} - -interface DataTableActionBarActionProps extends React.ComponentProps { - tooltip?: string - isPending?: boolean -} - -function DataTableActionBarAction({ - size = 'sm', - tooltip, - isPending, - disabled, - className, - children, - ...props -}: DataTableActionBarActionProps) { - const trigger = ( - - ) - - if (!tooltip) return trigger - - return ( - - {trigger} - -

{tooltip}

-
-
- ) -} - -interface DataTableActionBarSelectionProps { - table: Table -} - -function DataTableActionBarSelection({ - table, -}: DataTableActionBarSelectionProps) { - const onClearSelection = React.useCallback(() => { - table.toggleAllRowsSelected(false) - }, [table]) - - return ( -
- - {table.getFilteredSelectedRowModel().rows.length} selected - - - - - - - -

Clear selection

- - - Esc - - -
-
-
- ) -} - -export { DataTableActionBar, DataTableActionBarAction, DataTableActionBarSelection } diff --git a/packages/duron-dashboard/src/components/data-table/data-table-advanced-toolbar.tsx b/packages/duron-dashboard/src/components/data-table/data-table-advanced-toolbar.tsx deleted file mode 100644 index 9c344f5..0000000 --- a/packages/duron-dashboard/src/components/data-table/data-table-advanced-toolbar.tsx +++ /dev/null @@ -1,33 +0,0 @@ -'use client' - -import type { RowData, Table } from '@tanstack/react-table' -import type * as React from 'react' - -import { DataTableViewOptions } from '@/components/data-table/data-table-view-options' -import type { DataTableFeatures } from '@/lib/data-table-features' -import { cn } from '@/lib/utils' - -interface DataTableAdvancedToolbarProps extends React.ComponentProps<'div'> { - table: Table -} - -export function DataTableAdvancedToolbar({ - table, - children, - className, - ...props -}: DataTableAdvancedToolbarProps) { - return ( -
-
{children}
-
- -
-
- ) -} diff --git a/packages/duron-dashboard/src/components/data-table/data-table-date-filter.tsx b/packages/duron-dashboard/src/components/data-table/data-table-date-filter.tsx index bca892e..9a4db4e 100644 --- a/packages/duron-dashboard/src/components/data-table/data-table-date-filter.tsx +++ b/packages/duron-dashboard/src/components/data-table/data-table-date-filter.tsx @@ -3,7 +3,6 @@ import type { Column, RowData } from '@tanstack/react-table' import { CalendarIcon, XCircle } from 'lucide-react' import * as React from 'react' -import type { DateRange } from 'react-day-picker' import InputDateTime from '@/components/input-date-time' import { Button } from '@/components/ui/button' @@ -12,6 +11,9 @@ import { Separator } from '@/components/ui/separator' import type { DataTableFeatures } from '@/lib/data-table-features' import { formatDate } from '@/lib/format' +// Same shape as react-day-picker's DateRange (the calendar it came from is no longer used). +type DateRange = { from: Date | undefined; to?: Date | undefined } + type DateSelection = Date[] | DateRange function getIsDateRange(value: DateSelection): value is DateRange { diff --git a/packages/duron-dashboard/src/components/data-table/data-table-filter-list.tsx b/packages/duron-dashboard/src/components/data-table/data-table-filter-list.tsx deleted file mode 100644 index 4e9e125..0000000 --- a/packages/duron-dashboard/src/components/data-table/data-table-filter-list.tsx +++ /dev/null @@ -1,726 +0,0 @@ -'use client' - -import type { Column, ColumnMeta, RowData, Table } from '@tanstack/react-table' -import { CalendarIcon, Check, ChevronsUpDown, GripVertical, ListFilter, Trash2 } from 'lucide-react' -import { parseAsStringEnum, useQueryState } from 'nuqs' -import * as React from 'react' - -import { DataTableRangeFilter } from '@/components/data-table/data-table-range-filter' -import { Badge } from '@/components/ui/badge' -import { Button } from '@/components/ui/button' -import { Calendar } from '@/components/ui/calendar' -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from '@/components/ui/command' -import { - Faceted, - FacetedBadgeList, - FacetedContent, - FacetedEmpty, - FacetedGroup, - FacetedInput, - FacetedItem, - FacetedList, - FacetedTrigger, -} from '@/components/ui/faceted' -import { Input } from '@/components/ui/input' -import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from '@/components/ui/select' -import { - Sortable, - SortableContent, - SortableItem, - SortableItemHandle, - SortableOverlay, -} from '@/components/ui/sortable' -import { dataTableConfig } from '@/config/data-table' -import { useDebouncedCallback } from '@/hooks/use-debounced-callback' -import { getDefaultFilterOperator, getFilterOperators } from '@/lib/data-table' -import type { DataTableFeatures } from '@/lib/data-table-features' -import { formatDate } from '@/lib/format' -import { generateId } from '@/lib/id' -import { getFiltersStateParser } from '@/lib/parsers' -import { cn } from '@/lib/utils' -import type { ExtendedColumnFilter, FilterOperator, JoinOperator } from '@/types/data-table' - -const DEBOUNCE_MS = 300 -const THROTTLE_MS = 50 -const FILTER_SHORTCUT_KEY = 'f' -const REMOVE_FILTER_SHORTCUTS = ['backspace', 'delete'] - -interface DataTableFilterListProps extends React.ComponentProps< - typeof PopoverContent -> { - table: Table - debounceMs?: number - throttleMs?: number - shallow?: boolean -} - -export function DataTableFilterList({ - table, - debounceMs = DEBOUNCE_MS, - throttleMs = THROTTLE_MS, - shallow = true, - ...props -}: DataTableFilterListProps) { - const id = React.useId() - const labelId = React.useId() - const descriptionId = React.useId() - const [open, setOpen] = React.useState(false) - const addButtonRef = React.useRef(null) - - const columns = React.useMemo(() => { - return table.getAllColumns().filter((column) => column.columnDef.enableColumnFilter) - }, [table]) - - const [filters, setFilters] = useQueryState( - table.options.meta?.queryKeys?.filters ?? 'filters', - getFiltersStateParser(columns.map((field) => field.id)) - .withDefault([]) - .withOptions({ - clearOnDefault: true, - shallow, - throttleMs, - }), - ) - const debouncedSetFilters = useDebouncedCallback(setFilters, debounceMs) - - const [joinOperator, setJoinOperator] = useQueryState( - table.options.meta?.queryKeys?.joinOperator ?? '', - parseAsStringEnum(['and', 'or']).withDefault('and').withOptions({ - clearOnDefault: true, - shallow, - }), - ) - - const onFilterAdd = React.useCallback(() => { - const column = columns[0] - - if (!column) return - - debouncedSetFilters([ - ...filters, - { - id: column.id as Extract, - value: '', - variant: column.columnDef.meta?.variant ?? 'text', - operator: getDefaultFilterOperator(column.columnDef.meta?.variant ?? 'text'), - filterId: generateId({ length: 8 }), - }, - ]) - }, [columns, filters, debouncedSetFilters]) - - const onFilterUpdate = React.useCallback( - (filterId: string, updates: Partial, 'filterId'>>) => { - debouncedSetFilters((prevFilters) => { - const updatedFilters = prevFilters.map((filter) => { - if (filter.filterId === filterId) { - return { ...filter, ...updates } as ExtendedColumnFilter - } - return filter - }) - return updatedFilters - }) - }, - [debouncedSetFilters], - ) - - const onFilterRemove = React.useCallback( - (filterId: string) => { - const updatedFilters = filters.filter((filter) => filter.filterId !== filterId) - void setFilters(updatedFilters) - requestAnimationFrame(() => { - addButtonRef.current?.focus() - }) - }, - [filters, setFilters], - ) - - const onFiltersReset = React.useCallback(() => { - void setFilters(null) - void setJoinOperator('and') - }, [setFilters, setJoinOperator]) - - React.useEffect(() => { - function onKeyDown(event: KeyboardEvent) { - if ( - event.target instanceof HTMLInputElement || - event.target instanceof HTMLTextAreaElement || - (event.target instanceof HTMLElement && event.target.contentEditable === 'true') - ) { - return - } - - if ( - event.key.toLowerCase() === FILTER_SHORTCUT_KEY && - (event.ctrlKey || event.metaKey) && - event.shiftKey - ) { - event.preventDefault() - setOpen((prev) => !prev) - } - } - - window.addEventListener('keydown', onKeyDown) - return () => window.removeEventListener('keydown', onKeyDown) - }, []) - - const onTriggerKeyDown = React.useCallback( - (event: React.KeyboardEvent) => { - if (REMOVE_FILTER_SHORTCUTS.includes(event.key.toLowerCase()) && filters.length > 0) { - event.preventDefault() - onFilterRemove(filters[filters.length - 1]?.filterId ?? '') - } - }, - [filters, onFilterRemove], - ) - - return ( - item.filterId}> - - - - - -
-

- {filters.length > 0 ? 'Filters' : 'No filters applied'} -

-

0 && 'sr-only')} - > - {filters.length > 0 - ? 'Modify filters to refine your rows.' - : 'Add filters to refine your rows.'} -

-
- {filters.length > 0 ? ( - -
    - {filters.map((filter, index) => ( - - key={filter.filterId} - filter={filter} - index={index} - filterItemId={`${id}-filter-${filter.filterId}`} - joinOperator={joinOperator} - setJoinOperator={setJoinOperator} - columns={columns} - onFilterUpdate={onFilterUpdate} - onFilterRemove={onFilterRemove} - /> - ))} -
-
- ) : null} -
- - {filters.length > 0 ? ( - - ) : null} -
-
-
- -
-
-
-
-
-
-
-
- - - ) -} - -interface DataTableFilterItemProps { - filter: ExtendedColumnFilter - index: number - filterItemId: string - joinOperator: JoinOperator - setJoinOperator: (value: JoinOperator) => void - columns: Column[] - onFilterUpdate: ( - filterId: string, - updates: Partial, 'filterId'>>, - ) => void - onFilterRemove: (filterId: string) => void -} - -function DataTableFilterItem({ - filter, - index, - filterItemId, - joinOperator, - setJoinOperator, - columns, - onFilterUpdate, - onFilterRemove, -}: DataTableFilterItemProps) { - const [showFieldSelector, setShowFieldSelector] = React.useState(false) - const [showOperatorSelector, setShowOperatorSelector] = React.useState(false) - const [showValueSelector, setShowValueSelector] = React.useState(false) - - const column = columns.find((col) => col.id === filter.id) - - const joinOperatorListboxId = `${filterItemId}-join-operator-listbox` - const fieldListboxId = `${filterItemId}-field-listbox` - const operatorListboxId = `${filterItemId}-operator-listbox` - const inputId = `${filterItemId}-input` - - const columnMeta = column?.columnDef.meta - const filterOperators = getFilterOperators(filter.variant) - - const onItemKeyDown = React.useCallback( - (event: React.KeyboardEvent) => { - if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) { - return - } - - if (showFieldSelector || showOperatorSelector || showValueSelector) { - return - } - - if (REMOVE_FILTER_SHORTCUTS.includes(event.key.toLowerCase())) { - event.preventDefault() - onFilterRemove(filter.filterId) - } - }, - [filter.filterId, showFieldSelector, showOperatorSelector, showValueSelector, onFilterRemove], - ) - - if (!column) return null - - return ( - -
  • -
    - {index === 0 ? ( - Where - ) : index === 1 ? ( - - ) : ( - {joinOperator} - )} -
    - - - - - - - - - No fields found. - - {columns.map((col) => ( - { - onFilterUpdate(filter.filterId, { - id: value as Extract, - variant: col.columnDef.meta?.variant ?? 'text', - operator: getDefaultFilterOperator(col.columnDef.meta?.variant ?? 'text'), - value: '', - }) - - setShowFieldSelector(false) - }} - > - {col.columnDef.meta?.label} - - - ))} - - - - - - -
    - {onFilterInputRender({ - filter, - inputId, - column, - columnMeta, - onFilterUpdate, - showValueSelector, - setShowValueSelector, - })} -
    - - - - -
  • -
    - ) -} - -function onFilterInputRender({ - filter, - inputId, - column, - columnMeta, - onFilterUpdate, - showValueSelector, - setShowValueSelector, -}: { - filter: ExtendedColumnFilter - inputId: string - column: Column - columnMeta?: ColumnMeta - onFilterUpdate: ( - filterId: string, - updates: Partial, 'filterId'>>, - ) => void - showValueSelector: boolean - setShowValueSelector: (value: boolean) => void -}) { - if (filter.operator === 'isEmpty' || filter.operator === 'isNotEmpty') { - return ( -
    - ) - } - - switch (filter.variant) { - case 'text': - case 'number': - case 'range': { - if ( - (filter.variant === 'range' && filter.operator === 'isBetween') || - filter.operator === 'isBetween' - ) { - return ( - - ) - } - - const isNumber = filter.variant === 'number' || filter.variant === 'range' - - return ( - - onFilterUpdate(filter.filterId, { - value: event.target.value, - }) - } - /> - ) - } - - case 'boolean': { - if (Array.isArray(filter.value)) return null - - const inputListboxId = `${inputId}-listbox` - - return ( - - ) - } - - case 'select': - case 'multiSelect': { - const inputListboxId = `${inputId}-listbox` - - const multiple = filter.variant === 'multiSelect' - const selectedValues = multiple - ? Array.isArray(filter.value) - ? filter.value - : [] - : typeof filter.value === 'string' - ? filter.value - : undefined - - return ( - { - onFilterUpdate(filter.filterId, { - value, - }) - }} - multiple={multiple} - > - - - - - - - No options found. - - {columnMeta?.options?.map((option) => ( - - {option.icon && } - {option.label} - {option.count && ( - {option.count} - )} - - ))} - - - - - ) - } - - case 'date': - case 'dateRange': { - const inputListboxId = `${inputId}-listbox` - - const dateValue = Array.isArray(filter.value) - ? filter.value.filter(Boolean) - : [filter.value, filter.value].filter(Boolean) - - const displayValue = - filter.operator === 'isBetween' && dateValue.length === 2 - ? `${formatDate(new Date(Number(dateValue[0])))} - ${formatDate(new Date(Number(dateValue[1])))}` - : dateValue[0] - ? formatDate(new Date(Number(dateValue[0]))) - : 'Pick a date' - - return ( - - - - - - {filter.operator === 'isBetween' ? ( - { - onFilterUpdate(filter.filterId, { - value: date - ? [ - (date.from?.getTime() ?? '').toString(), - (date.to?.getTime() ?? '').toString(), - ] - : [], - }) - }} - /> - ) : ( - { - onFilterUpdate(filter.filterId, { - value: (date?.getTime() ?? '').toString(), - }) - }} - /> - )} - - - ) - } - - default: - return null - } -} diff --git a/packages/duron-dashboard/src/components/data-table/data-table-filter-menu.tsx b/packages/duron-dashboard/src/components/data-table/data-table-filter-menu.tsx deleted file mode 100644 index 7482d0c..0000000 --- a/packages/duron-dashboard/src/components/data-table/data-table-filter-menu.tsx +++ /dev/null @@ -1,797 +0,0 @@ -'use client' - -import type { Column, RowData, Table } from '@tanstack/react-table' -import { BadgeCheck, CalendarIcon, Check, ListFilter, Text, X } from 'lucide-react' -import { useQueryState } from 'nuqs' -import * as React from 'react' - -import { DataTableRangeFilter } from '@/components/data-table/data-table-range-filter' -import { Button } from '@/components/ui/button' -import { Calendar } from '@/components/ui/calendar' -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from '@/components/ui/command' -import { Input } from '@/components/ui/input' -import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from '@/components/ui/select' -import { useDebouncedCallback } from '@/hooks/use-debounced-callback' -import { getDefaultFilterOperator, getFilterOperators } from '@/lib/data-table' -import type { DataTableFeatures } from '@/lib/data-table-features' -import { formatDate } from '@/lib/format' -import { generateId } from '@/lib/id' -import { getFiltersStateParser } from '@/lib/parsers' -import { cn } from '@/lib/utils' -import type { ExtendedColumnFilter, FilterOperator } from '@/types/data-table' - -const DEBOUNCE_MS = 300 -const THROTTLE_MS = 50 -const FILTER_SHORTCUT_KEY = 'f' -const REMOVE_FILTER_SHORTCUTS = ['backspace', 'delete'] - -interface DataTableFilterMenuProps extends React.ComponentProps< - typeof PopoverContent -> { - table: Table - debounceMs?: number - throttleMs?: number - shallow?: boolean -} - -export function DataTableFilterMenu({ - table, - debounceMs = DEBOUNCE_MS, - throttleMs = THROTTLE_MS, - shallow = true, - align = 'start', - ...props -}: DataTableFilterMenuProps) { - const id = React.useId() - - const columns = React.useMemo(() => { - return table.getAllColumns().filter((column) => column.columnDef.enableColumnFilter) - }, [table]) - - const [open, setOpen] = React.useState(false) - const [selectedColumn, setSelectedColumn] = React.useState | null>(null) - const [inputValue, setInputValue] = React.useState('') - const triggerRef = React.useRef(null) - const inputRef = React.useRef(null) - - const onOpenChange = React.useCallback((isOpen: boolean) => { - setOpen(isOpen) - - if (!isOpen) { - setTimeout(() => { - setSelectedColumn(null) - setInputValue('') - }, 100) - } - }, []) - - const onInputKeyDown = React.useCallback( - (event: React.KeyboardEvent) => { - if ( - REMOVE_FILTER_SHORTCUTS.includes(event.key.toLowerCase()) && - !inputValue && - selectedColumn - ) { - event.preventDefault() - setSelectedColumn(null) - } - }, - [inputValue, selectedColumn], - ) - - const [filters, setFilters] = useQueryState( - table.options.meta?.queryKeys?.filters ?? 'filters', - getFiltersStateParser(columns.map((field) => field.id)) - .withDefault([]) - .withOptions({ - clearOnDefault: true, - shallow, - throttleMs, - }), - ) - const debouncedSetFilters = useDebouncedCallback(setFilters, debounceMs) - - const onFilterAdd = React.useCallback( - (column: Column, value: string) => { - if (!value.trim() && column.columnDef.meta?.variant !== 'boolean') { - return - } - - const filterValue = column.columnDef.meta?.variant === 'multiSelect' ? [value] : value - - const newFilter: ExtendedColumnFilter = { - id: column.id as Extract, - value: filterValue, - variant: column.columnDef.meta?.variant ?? 'text', - operator: getDefaultFilterOperator(column.columnDef.meta?.variant ?? 'text'), - filterId: generateId({ length: 8 }), - } - - debouncedSetFilters([...filters, newFilter]) - setOpen(false) - - setTimeout(() => { - setSelectedColumn(null) - setInputValue('') - }, 100) - }, - [filters, debouncedSetFilters], - ) - - const onFilterRemove = React.useCallback( - (filterId: string) => { - const updatedFilters = filters.filter((filter) => filter.filterId !== filterId) - debouncedSetFilters(updatedFilters) - requestAnimationFrame(() => { - triggerRef.current?.focus() - }) - }, - [filters, debouncedSetFilters], - ) - - const onFilterUpdate = React.useCallback( - (filterId: string, updates: Partial, 'filterId'>>) => { - debouncedSetFilters((prevFilters) => { - const updatedFilters = prevFilters.map((filter) => { - if (filter.filterId === filterId) { - return { ...filter, ...updates } as ExtendedColumnFilter - } - return filter - }) - return updatedFilters - }) - }, - [debouncedSetFilters], - ) - - const onFiltersReset = React.useCallback(() => { - debouncedSetFilters([]) - }, [debouncedSetFilters]) - - React.useEffect(() => { - function onKeyDown(event: KeyboardEvent) { - if ( - event.target instanceof HTMLInputElement || - event.target instanceof HTMLTextAreaElement || - (event.target instanceof HTMLElement && event.target.contentEditable === 'true') - ) { - return - } - - if ( - event.key.toLowerCase() === FILTER_SHORTCUT_KEY && - (event.ctrlKey || event.metaKey) && - event.shiftKey - ) { - event.preventDefault() - setOpen((prev) => !prev) - } - } - - window.addEventListener('keydown', onKeyDown) - return () => window.removeEventListener('keydown', onKeyDown) - }, []) - - const onTriggerKeyDown = React.useCallback( - (event: React.KeyboardEvent) => { - if (REMOVE_FILTER_SHORTCUTS.includes(event.key.toLowerCase()) && filters.length > 0) { - event.preventDefault() - onFilterRemove(filters[filters.length - 1]?.filterId ?? '') - } - }, - [filters, onFilterRemove], - ) - - return ( -
    - {filters.map((filter) => ( - - ))} - {filters.length > 0 && ( - - )} - - - - - - - - - {selectedColumn ? ( - <> - {selectedColumn.columnDef.meta?.options && ( - No options found. - )} - onFilterAdd(selectedColumn, value)} - /> - - ) : ( - <> - No fields found. - - {columns.map((column) => ( - { - setSelectedColumn(column) - setInputValue('') - requestAnimationFrame(() => { - inputRef.current?.focus() - }) - }} - > - {column.columnDef.meta?.icon && } - - {column.columnDef.meta?.label ?? column.id} - - - ))} - - - )} - - - - -
    - ) -} - -interface DataTableFilterItemProps { - filter: ExtendedColumnFilter - filterItemId: string - columns: Column[] - onFilterUpdate: ( - filterId: string, - updates: Partial, 'filterId'>>, - ) => void - onFilterRemove: (filterId: string) => void -} - -function DataTableFilterItem({ - filter, - filterItemId, - columns, - onFilterUpdate, - onFilterRemove, -}: DataTableFilterItemProps) { - { - const [showFieldSelector, setShowFieldSelector] = React.useState(false) - const [showOperatorSelector, setShowOperatorSelector] = React.useState(false) - const [showValueSelector, setShowValueSelector] = React.useState(false) - - const column = columns.find((col) => col.id === filter.id) - - const operatorListboxId = `${filterItemId}-operator-listbox` - const inputId = `${filterItemId}-input` - - const columnMeta = column?.columnDef.meta - const filterOperators = getFilterOperators(filter.variant) - - const onItemKeyDown = React.useCallback( - (event: React.KeyboardEvent) => { - if ( - event.target instanceof HTMLInputElement || - event.target instanceof HTMLTextAreaElement - ) { - return - } - - if (showFieldSelector || showOperatorSelector || showValueSelector) { - return - } - - if (REMOVE_FILTER_SHORTCUTS.includes(event.key.toLowerCase())) { - event.preventDefault() - onFilterRemove(filter.filterId) - } - }, - [filter.filterId, showFieldSelector, showOperatorSelector, showValueSelector, onFilterRemove], - ) - - if (!column) return null - - return ( -
    - - - - - - - - - No fields found. - - {columns.map((col) => ( - { - onFilterUpdate(filter.filterId, { - id: col.id as Extract, - variant: col.columnDef.meta?.variant ?? 'text', - operator: getDefaultFilterOperator(col.columnDef.meta?.variant ?? 'text'), - value: '', - }) - - setShowFieldSelector(false) - }} - > - {col.columnDef.meta?.icon && } - {col.columnDef.meta?.label ?? col.id} - - - ))} - - - - - - - {onFilterInputRender({ - filter, - column, - inputId, - onFilterUpdate, - showValueSelector, - setShowValueSelector, - })} - -
    - ) - } -} - -interface FilterValueSelectorProps { - column: Column - value: string - onSelect: (value: string) => void -} - -function FilterValueSelector({ - column, - value, - onSelect, -}: FilterValueSelectorProps) { - const variant = column.columnDef.meta?.variant ?? 'text' - - switch (variant) { - case 'boolean': - return ( - - onSelect('true')}> - True - - onSelect('false')}> - False - - - ) - - case 'select': - case 'multiSelect': - return ( - - {column.columnDef.meta?.options?.map((option) => ( - onSelect(option.value)} - > - {option.icon && } - {option.label} - {option.count && {option.count}} - - ))} - - ) - - case 'date': - case 'dateRange': - return ( - onSelect(date?.getTime().toString() ?? '')} - /> - ) - - default: { - const isEmpty = !value.trim() - - return ( - - onSelect(value)} disabled={isEmpty}> - {isEmpty ? ( - <> - - Type to add filter... - - ) : ( - <> - - Filter by "{value}" - - )} - - - ) - } - } -} - -function onFilterInputRender({ - filter, - column, - inputId, - onFilterUpdate, - showValueSelector, - setShowValueSelector, -}: { - filter: ExtendedColumnFilter - column: Column - inputId: string - onFilterUpdate: ( - filterId: string, - updates: Partial, 'filterId'>>, - ) => void - showValueSelector: boolean - setShowValueSelector: (value: boolean) => void -}) { - if (filter.operator === 'isEmpty' || filter.operator === 'isNotEmpty') { - return ( -
    - ) - } - - switch (filter.variant) { - case 'text': - case 'number': - case 'range': { - if ( - (filter.variant === 'range' && filter.operator === 'isBetween') || - filter.operator === 'isBetween' - ) { - return ( - - ) - } - - const isNumber = filter.variant === 'number' || filter.variant === 'range' - - return ( - onFilterUpdate(filter.filterId, { value: event.target.value })} - /> - ) - } - - case 'boolean': { - const inputListboxId = `${inputId}-listbox` - - return ( - - ) - } - - case 'select': - case 'multiSelect': { - const inputListboxId = `${inputId}-listbox` - - const options = column.columnDef.meta?.options ?? [] - const selectedValues = Array.isArray(filter.value) ? filter.value : [filter.value] - - const selectedOptions = options.filter((option) => selectedValues.includes(option.value)) - - return ( - - - - - - - - - No options found. - - {options.map((option) => ( - { - const value = - filter.variant === 'multiSelect' - ? selectedValues.includes(option.value) - ? selectedValues.filter((v) => v !== option.value) - : [...selectedValues, option.value] - : option.value - onFilterUpdate(filter.filterId, { value }) - }} - > - {option.icon && } - {option.label} - {filter.variant === 'multiSelect' && ( - - )} - - ))} - - - - - - ) - } - - case 'date': - case 'dateRange': { - const inputListboxId = `${inputId}-listbox` - - const dateValue = Array.isArray(filter.value) - ? filter.value.filter(Boolean) - : [filter.value, filter.value].filter(Boolean) - - const displayValue = - filter.operator === 'isBetween' && dateValue.length === 2 - ? `${formatDate(new Date(Number(dateValue[0])))} - ${formatDate(new Date(Number(dateValue[1])))}` - : dateValue[0] - ? formatDate(new Date(Number(dateValue[0]))) - : 'Pick date...' - - return ( - - - - - - {filter.operator === 'isBetween' ? ( - { - onFilterUpdate(filter.filterId, { - value: date - ? [ - (date.from?.getTime() ?? '').toString(), - (date.to?.getTime() ?? '').toString(), - ] - : [], - }) - }} - /> - ) : ( - { - onFilterUpdate(filter.filterId, { - value: (date?.getTime() ?? '').toString(), - }) - }} - /> - )} - - - ) - } - - default: - return null - } -} diff --git a/packages/duron-dashboard/src/components/data-table/data-table-range-filter.tsx b/packages/duron-dashboard/src/components/data-table/data-table-range-filter.tsx deleted file mode 100644 index a86d5e7..0000000 --- a/packages/duron-dashboard/src/components/data-table/data-table-range-filter.tsx +++ /dev/null @@ -1,112 +0,0 @@ -'use client' - -import type { Column, RowData } from '@tanstack/react-table' -import * as React from 'react' - -import { Input } from '@/components/ui/input' -import type { DataTableFeatures } from '@/lib/data-table-features' -import { cn } from '@/lib/utils' -import type { ExtendedColumnFilter } from '@/types/data-table' - -interface DataTableRangeFilterProps extends React.ComponentProps<'div'> { - filter: ExtendedColumnFilter - column: Column - inputId: string - onFilterUpdate: ( - filterId: string, - updates: Partial, 'filterId'>>, - ) => void -} - -export function DataTableRangeFilter({ - filter, - column, - inputId, - onFilterUpdate, - className, - ...props -}: DataTableRangeFilterProps) { - const meta = column.columnDef.meta - - const [min, max] = React.useMemo(() => { - const range = column.columnDef.meta?.range - if (range) return range - - const values = column.getFacetedMinMaxValues() - if (!values) return [0, 100] - - return [values[0], values[1]] - }, [column]) - - const formatValue = React.useCallback((value: string | number | undefined) => { - if (value === undefined || value === '') return '' - const numValue = Number(value) - return Number.isNaN(numValue) - ? '' - : numValue.toLocaleString(undefined, { - maximumFractionDigits: 0, - }) - }, []) - - const value = React.useMemo(() => { - if (Array.isArray(filter.value)) return filter.value.map(formatValue) - return [formatValue(filter.value), ''] - }, [filter.value, formatValue]) - - const onRangeValueChange = React.useCallback( - (newValue: string, isMin?: boolean) => { - const numValue = Number(newValue) - const currentValues = Array.isArray(filter.value) ? filter.value : ['', ''] - const otherValue = isMin ? (currentValues[1] ?? '') : (currentValues[0] ?? '') - - if ( - newValue === '' || - (!Number.isNaN(numValue) && - (isMin - ? numValue >= min && numValue <= (Number(otherValue) || max) - : numValue <= max && numValue >= (Number(otherValue) || min))) - ) { - onFilterUpdate(filter.filterId, { - value: isMin ? [newValue, otherValue] : [otherValue, newValue], - }) - } - }, - [filter.filterId, filter.value, min, max, onFilterUpdate], - ) - - return ( -
    - onRangeValueChange(event.target.value, true)} - /> - to - onRangeValueChange(event.target.value)} - /> -
    - ) -} diff --git a/packages/duron-dashboard/src/components/data-table/data-table-skeleton.tsx b/packages/duron-dashboard/src/components/data-table/data-table-skeleton.tsx deleted file mode 100644 index f50257a..0000000 --- a/packages/duron-dashboard/src/components/data-table/data-table-skeleton.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import { Skeleton } from '@/components/ui/skeleton' -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from '@/components/ui/table' -import { cn } from '@/lib/utils' - -interface DataTableSkeletonProps extends React.ComponentProps<'div'> { - columnCount: number - rowCount?: number - filterCount?: number - cellWidths?: string[] - withViewOptions?: boolean - withPagination?: boolean - shrinkZero?: boolean -} - -export function DataTableSkeleton({ - columnCount, - rowCount = 10, - filterCount = 0, - cellWidths = ['auto'], - withViewOptions = true, - withPagination = true, - shrinkZero = false, - className, - ...props -}: DataTableSkeletonProps) { - const cozyCellWidths = Array.from( - { length: columnCount }, - (_val, index) => cellWidths[index % cellWidths.length] ?? 'auto', - ) - - return ( -
    -
    -
    - {filterCount > 0 - ? Array.from({ length: filterCount }).map((_val, i) => ( - - )) - : null} -
    - {withViewOptions ? : null} -
    -
    - - - {Array.from({ length: 1 }).map((_val, i) => ( - - {Array.from({ length: columnCount }).map((_val2, j) => ( - - - - ))} - - ))} - - - {Array.from({ length: rowCount }).map((_val, i) => ( - - {Array.from({ length: columnCount }).map((_val2, j) => ( - - - - ))} - - ))} - -
    -
    - {withPagination ? ( -
    - -
    -
    - - -
    -
    - -
    -
    - - - - -
    -
    -
    - ) : null} -
    - ) -} diff --git a/packages/duron-dashboard/src/components/data-table/data-table-view-options.tsx b/packages/duron-dashboard/src/components/data-table/data-table-view-options.tsx deleted file mode 100644 index 5adefe8..0000000 --- a/packages/duron-dashboard/src/components/data-table/data-table-view-options.tsx +++ /dev/null @@ -1,78 +0,0 @@ -'use client' - -import type { RowData, Table } from '@tanstack/react-table' -import { Check, Settings2 } from 'lucide-react' -import * as React from 'react' - -import { Button } from '@/components/ui/button' -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from '@/components/ui/command' -import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' -import type { DataTableFeatures } from '@/lib/data-table-features' -import { cn } from '@/lib/utils' - -interface DataTableViewOptionsProps extends React.ComponentProps< - typeof PopoverContent -> { - table: Table -} - -export function DataTableViewOptions({ - table, - ...props -}: DataTableViewOptionsProps) { - const columns = React.useMemo( - () => - table - .getAllColumns() - .filter((column) => typeof column.accessorFn !== 'undefined' && column.getCanHide()), - [table], - ) - - return ( - - - - - - - - - No columns found. - - {columns.map((column) => ( - column.toggleVisibility(!column.getIsVisible())} - > - {column.columnDef.meta?.label ?? column.id} - - - ))} - - - - - - ) -} diff --git a/packages/duron-dashboard/src/components/ui/calendar.tsx b/packages/duron-dashboard/src/components/ui/calendar.tsx deleted file mode 100644 index e144758..0000000 --- a/packages/duron-dashboard/src/components/ui/calendar.tsx +++ /dev/null @@ -1,180 +0,0 @@ -'use client' - -import { ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon } from 'lucide-react' -import * as React from 'react' -import { type DayButton, DayPicker, getDefaultClassNames } from 'react-day-picker' - -import { Button, buttonVariants } from '@/components/ui/button' -import { cn } from '@/lib/utils' - -function Calendar({ - className, - classNames, - showOutsideDays = true, - captionLayout = 'label', - buttonVariant = 'ghost', - formatters, - components, - ...props -}: React.ComponentProps & { - buttonVariant?: React.ComponentProps['variant'] -}) { - const defaultClassNames = getDefaultClassNames() - - return ( - svg]:rotate-180`, - String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`, - className, - )} - captionLayout={captionLayout} - formatters={{ - formatMonthDropdown: (date) => date.toLocaleString('default', { month: 'short' }), - ...formatters, - }} - classNames={{ - root: cn('w-fit', defaultClassNames.root), - months: cn('flex gap-4 flex-col md:flex-row relative', defaultClassNames.months), - month: cn('flex flex-col w-full gap-4', defaultClassNames.month), - nav: cn( - 'flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between', - defaultClassNames.nav, - ), - button_previous: cn( - buttonVariants({ variant: buttonVariant }), - 'size-(--cell-size) aria-disabled:opacity-50 p-0 select-none', - defaultClassNames.button_previous, - ), - button_next: cn( - buttonVariants({ variant: buttonVariant }), - 'size-(--cell-size) aria-disabled:opacity-50 p-0 select-none', - defaultClassNames.button_next, - ), - month_caption: cn( - 'flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)', - defaultClassNames.month_caption, - ), - dropdowns: cn( - 'w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5', - defaultClassNames.dropdowns, - ), - dropdown_root: cn( - 'relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md', - defaultClassNames.dropdown_root, - ), - dropdown: cn('absolute bg-popover inset-0 opacity-0', defaultClassNames.dropdown), - caption_label: cn( - 'select-none font-medium', - captionLayout === 'label' - ? 'text-sm' - : 'rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5', - defaultClassNames.caption_label, - ), - month_grid: cn('w-full border-collapse', defaultClassNames.month_grid), - weekdays: cn('flex', defaultClassNames.weekdays), - weekday: cn( - 'text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none', - defaultClassNames.weekday, - ), - week: cn('flex w-full mt-2', defaultClassNames.week), - week_number_header: cn('select-none w-(--cell-size)', defaultClassNames.week_number_header), - week_number: cn( - 'text-[0.8rem] select-none text-muted-foreground', - defaultClassNames.week_number, - ), - day: cn( - 'relative w-full h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none', - props.showWeekNumber - ? '[&:nth-child(2)[data-selected=true]_button]:rounded-l-md' - : '[&:first-child[data-selected=true]_button]:rounded-l-md', - defaultClassNames.day, - ), - range_start: cn('rounded-l-md bg-accent', defaultClassNames.range_start), - range_middle: cn('rounded-none', defaultClassNames.range_middle), - range_end: cn('rounded-r-md bg-accent', defaultClassNames.range_end), - today: cn( - 'bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none', - defaultClassNames.today, - ), - outside: cn( - 'text-muted-foreground aria-selected:text-muted-foreground', - defaultClassNames.outside, - ), - disabled: cn('text-muted-foreground opacity-50', defaultClassNames.disabled), - hidden: cn('invisible', defaultClassNames.hidden), - ...classNames, - }} - components={{ - Root: ({ className, rootRef, ...props }) => { - return
    - }, - Chevron: ({ className, orientation, ...props }) => { - if (orientation === 'left') { - return - } - - if (orientation === 'right') { - return - } - - return - }, - DayButton: CalendarDayButton, - WeekNumber: ({ children, ...props }) => { - return ( - -
    - {children} -
    - - ) - }, - ...components, - }} - {...props} - /> - ) -} - -function CalendarDayButton({ - className, - day, - modifiers, - ...props -}: React.ComponentProps) { - const defaultClassNames = getDefaultClassNames() - - const ref = React.useRef(null) - React.useEffect(() => { - if (modifiers.focused) ref.current?.focus() - }, [modifiers.focused]) - - return ( - - ) -} - -export { Tabs, TabsList, TabsTrigger } diff --git a/packages/duron-dashboard/src/hooks/use-copy-to-clipboard.ts b/packages/duron-dashboard/src/hooks/use-copy-to-clipboard.ts deleted file mode 100644 index 6d15470..0000000 --- a/packages/duron-dashboard/src/hooks/use-copy-to-clipboard.ts +++ /dev/null @@ -1,32 +0,0 @@ -'use client' - -import * as React from 'react' - -export function useCopyToClipboard({ - timeout = 2000, - onCopy, -}: { timeout?: number; onCopy?: () => void } = {}) { - const [copied, setCopied] = React.useState(false) - - const copy = (value: string) => { - if (typeof window === 'undefined' || !navigator.clipboard.writeText) { - return - } - - if (!value) return - - navigator.clipboard.writeText(value).then(() => { - setCopied(true) - - if (onCopy) { - onCopy() - } - - setTimeout(() => { - setCopied(false) - }, timeout) - }) - } - - return { copied, copy } -} diff --git a/packages/duron-dashboard/src/lib/data-table.ts b/packages/duron-dashboard/src/lib/data-table.ts deleted file mode 100644 index c4f5681..0000000 --- a/packages/duron-dashboard/src/lib/data-table.ts +++ /dev/null @@ -1,67 +0,0 @@ -import type { Column, RowData } from '@tanstack/react-table' - -import { dataTableConfig } from '@/config/data-table.ts' -import type { DataTableFeatures } from '@/lib/data-table-features' -import type { ExtendedColumnFilter, FilterOperator, FilterVariant } from '@/types/data-table.ts' - -export function getCommonPinningStyles({ - column, - withBorder = false, -}: { - column: Column - withBorder?: boolean -}): React.CSSProperties { - const isPinned = column.getIsPinned() - const isLastStartPinnedColumn = isPinned === 'start' && column.getIsLastColumn('start') - const isFirstEndPinnedColumn = isPinned === 'end' && column.getIsFirstColumn('end') - - return { - boxShadow: withBorder - ? isLastStartPinnedColumn - ? '-4px 0 4px -4px var(--border) inset' - : isFirstEndPinnedColumn - ? '4px 0 4px -4px var(--border) inset' - : undefined - : undefined, - left: isPinned === 'start' ? `${column.getStart('start')}px` : undefined, - right: isPinned === 'end' ? `${column.getAfter('end')}px` : undefined, - position: isPinned ? 'sticky' : 'relative', - background: isPinned ? 'hsl(var(--background))' : undefined, - width: column.getSize(), - zIndex: isPinned ? 10 : undefined, - } -} - -export function getFilterOperators(filterVariant: FilterVariant) { - const operatorMap: Record = { - text: dataTableConfig.textOperators, - number: dataTableConfig.numericOperators, - range: dataTableConfig.numericOperators, - date: dataTableConfig.dateOperators, - dateRange: dataTableConfig.dateOperators, - boolean: dataTableConfig.booleanOperators, - select: dataTableConfig.selectOperators, - multiSelect: dataTableConfig.multiSelectOperators, - } - - return operatorMap[filterVariant] ?? dataTableConfig.textOperators -} - -export function getDefaultFilterOperator(filterVariant: FilterVariant) { - const operators = getFilterOperators(filterVariant) - - return operators[0]?.value ?? (filterVariant === 'text' ? 'iLike' : 'eq') -} - -export function getValidFilters( - filters: ExtendedColumnFilter[], -): ExtendedColumnFilter[] { - return filters.filter( - (filter) => - filter.operator === 'isEmpty' || - filter.operator === 'isNotEmpty' || - (Array.isArray(filter.value) - ? filter.value.length > 0 - : filter.value !== '' && filter.value !== null && filter.value !== undefined), - ) -} diff --git a/packages/duron-dashboard/src/lib/id.ts b/packages/duron-dashboard/src/lib/id.ts deleted file mode 100644 index c376332..0000000 --- a/packages/duron-dashboard/src/lib/id.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { customAlphabet } from 'nanoid' - -const prefixes: Record = {} - -interface GenerateIdOptions { - length?: number - separator?: string -} - -export function generateId( - prefixOrOptions?: keyof typeof prefixes | GenerateIdOptions, - inputOptions: GenerateIdOptions = {}, -) { - const finalOptions = typeof prefixOrOptions === 'object' ? prefixOrOptions : inputOptions - - const prefix = typeof prefixOrOptions === 'object' ? undefined : prefixOrOptions - - const { length = 12, separator = '_' } = finalOptions - const id = customAlphabet( - '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', - length, - )() - - return prefix && prefix in prefixes ? `${prefixes[prefix]}${separator}${id}` : id -} diff --git a/packages/duron-dashboard/src/views/job-io.tsx b/packages/duron-dashboard/src/views/job-io.tsx deleted file mode 100644 index ff43bfd..0000000 --- a/packages/duron-dashboard/src/views/job-io.tsx +++ /dev/null @@ -1,61 +0,0 @@ -'use client' - -import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area' -import { useJob } from '@/lib/api' - -import { JsonView } from '../components/json-view' - -interface JobIOProps { - jobId: string | null -} - -export function JobIO({ jobId }: JobIOProps) { - const { data: job, isLoading } = useJob(jobId) - - if (!jobId) { - return ( -
    - Select a job to view input/output -
    - ) - } - - if (isLoading) { - return
    Loading job data...
    - } - - if (!job) { - return ( -
    Job not found
    - ) - } - - return ( - -
    - {job.input && ( -
    -
    Input
    - -
    - )} - - {!job.input && ( -
    No input available
    - )} - - {job.output && ( -
    -
    Output
    - -
    - )} - - {!job.output && ( -
    No output available
    - )} -
    - -
    - ) -} From 381c238444f35c33c95d1b01e408f352a29f2d0c Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 15:41:16 -0300 Subject: [PATCH 050/100] fix(docs): no React #418 when hydrating the home page shell '/' is the SPA shell (spa.prerender.outputPath 'index.html'). Its route area is an empty Suspense boundary. Since Start 1.168.36 / Router 1.170.19 the client renders the index route on its first pass, without that boundary, so hydration throws React #418 (upstream TanStack/router#8473, open). Bisect: Start 1.168.31-1.168.35 are clean. Every version from 1.168.36 to 1.170.0 throws, on Vite 7 and on Vite 8, so no version pin fixes it. The '/' route now sets wrapInSuspense and renders HomeLayout in . The client's first pass then matches the shell. The content renders after hydration, as in the 1.168.31 baseline. index.html is still the shell and the SPA fallback, so the Cloudflare Pages deploy does not change. Remove both when #8473 is fixed. Pre-existing, also in the 1.168.31 baseline, not changed here: - /no-such-page (SPA fallback to the shell) throws React #418. - /docs/no-such-page logs "Unexpected token '<' ... is not valid JSON" because the docs server-fn fetch receives the HTML fallback. --- packages/docs/src/routes/index.tsx | 48 ++++++++++++++++++------------ 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/packages/docs/src/routes/index.tsx b/packages/docs/src/routes/index.tsx index 06007e6..4fd206d 100644 --- a/packages/docs/src/routes/index.tsx +++ b/packages/docs/src/routes/index.tsx @@ -1,33 +1,43 @@ -import { createFileRoute, Link } from '@tanstack/react-router' +import { ClientOnly, createFileRoute, Link } from '@tanstack/react-router' import { HomeLayout } from 'fumadocs-ui/layouts/home' import { Logo } from '@/components/logo' import { baseOptions } from '@/lib/layout.shared' +// Workaround for https://github.com/TanStack/router/issues/8473 (SPA mode: hydrating the +// prerendered shell throws React #418). '/' is the SPA shell (spa.prerender.outputPath +// 'index.html'), so its route area is an empty Suspense boundary. Since Start 1.168.36 / +// Router 1.170.19 the client renders this route on its first pass, without that Suspense +// boundary, so hydration fails. Start <= 1.168.35 was clean. `wrapInSuspense` restores the +// boundary and `ClientOnly` renders nothing until hydration, the same as the shell. Remove +// both when the upstream issue is fixed. export const Route = createFileRoute('/')({ + wrapInSuspense: true, component: Home, }) function Home() { return ( - - {/* fumadocs-ui 16.x: HomeLayout's root contains the navbar, so center the content in a - flex-1 wrapper (as the upstream template does) instead of styling the layout itself. */} -
    -
    - -

    Documentation

    + + + {/* fumadocs-ui 16.x: HomeLayout's root contains the navbar, so center the content in a + flex-1 wrapper (as the upstream template does) instead of styling the layout itself. */} +
    +
    + +

    Documentation

    +
    + + Open Docs +
    - - Open Docs - -
    - + + ) } From bc9b51f491f5832e9c34369aaf9403b462074627 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 15:48:13 -0300 Subject: [PATCH 051/100] chore(dashboard): remove unused exports knip, with the package entrypoints and public type files as entries, plus a grep across packages/, found exports that no module imports. - parsers: remove getFiltersStateParser and the filter item schema/type that only it used. - types/data-table: remove FilterOperator, JoinOperator, DataTableRowAction and ExtendedColumnFilter. FilterVariant becomes module-local (ColumnMeta still uses it). - compose-refs: composeRefs becomes module-local (used by useComposedRefs). - badge-status: statusConfig and Status become module-local. shadcn/diceui files in src/components/ui are unchanged: their unused exports are upstream API, not our own additions. --- .../src/components/badge-status.tsx | 4 +- .../duron-dashboard/src/lib/compose-refs.ts | 2 +- packages/duron-dashboard/src/lib/parsers.ts | 46 +------------------ .../duron-dashboard/src/types/data-table.ts | 17 +------ 4 files changed, 6 insertions(+), 63 deletions(-) diff --git a/packages/duron-dashboard/src/components/badge-status.tsx b/packages/duron-dashboard/src/components/badge-status.tsx index 56f2867..f342458 100644 --- a/packages/duron-dashboard/src/components/badge-status.tsx +++ b/packages/duron-dashboard/src/components/badge-status.tsx @@ -12,7 +12,7 @@ const icons = { cancelled: Ban, } -export const statusConfig = { +const statusConfig = { created: { label: 'Created', variant: 'outline', @@ -48,7 +48,7 @@ export const statusConfig = { }, } as const -export type Status = keyof typeof statusConfig +type Status = keyof typeof statusConfig export function BadgeStatus({ status, justIcon = false }: { status: string; justIcon?: boolean }) { const Icon = icons[status as Status] diff --git a/packages/duron-dashboard/src/lib/compose-refs.ts b/packages/duron-dashboard/src/lib/compose-refs.ts index 234bd24..2ceb297 100644 --- a/packages/duron-dashboard/src/lib/compose-refs.ts +++ b/packages/duron-dashboard/src/lib/compose-refs.ts @@ -59,4 +59,4 @@ function useComposedRefs(...refs: PossibleRef[]): React.RefCallback { return React.useCallback(composeRefs(...refs), refs) } -export { composeRefs, useComposedRefs } +export { useComposedRefs } diff --git a/packages/duron-dashboard/src/lib/parsers.ts b/packages/duron-dashboard/src/lib/parsers.ts index 60be0a3..4dec806 100644 --- a/packages/duron-dashboard/src/lib/parsers.ts +++ b/packages/duron-dashboard/src/lib/parsers.ts @@ -1,8 +1,7 @@ import { createParser } from 'nuqs/server' import * as z from 'zod/mini' -import { dataTableConfig } from '@/config/data-table.ts' -import type { ExtendedColumnFilter, ExtendedColumnSort } from '@/types/data-table.ts' +import type { ExtendedColumnSort } from '@/types/data-table.ts' const sortingItemSchema = z.object({ id: z.string(), @@ -35,46 +34,3 @@ export const getSortingStateParser = (columnIds?: string[] | Set) a.every((item, index) => item.id === b[index]?.id && item.desc === b[index]?.desc), }) } - -const filterItemSchema = z.object({ - id: z.string(), - value: z.union([z.string(), z.array(z.string())]), - variant: z.enum(dataTableConfig.filterVariants), - operator: z.enum(dataTableConfig.operators), - filterId: z.string(), -}) - -export type FilterItemSchema = z.infer - -export const getFiltersStateParser = (columnIds?: string[] | Set) => { - const validKeys = columnIds ? (columnIds instanceof Set ? columnIds : new Set(columnIds)) : null - - return createParser({ - parse: (value) => { - try { - const parsed = JSON.parse(value) - const result = z.array(filterItemSchema).safeParse(parsed) - - if (!result.success) return null - - if (validKeys && result.data.some((item) => !validKeys.has(item.id))) { - return null - } - - return result.data as ExtendedColumnFilter[] - } catch { - return null - } - }, - serialize: (value) => JSON.stringify(value), - eq: (a, b) => - a.length === b.length && - a.every( - (filter, index) => - filter.id === b[index]?.id && - filter.value === b[index]?.value && - filter.variant === b[index]?.variant && - filter.operator === b[index]?.operator, - ), - }) -} diff --git a/packages/duron-dashboard/src/types/data-table.ts b/packages/duron-dashboard/src/types/data-table.ts index 9aa54d9..cee26b4 100644 --- a/packages/duron-dashboard/src/types/data-table.ts +++ b/packages/duron-dashboard/src/types/data-table.ts @@ -1,8 +1,6 @@ -import type { CellData, ColumnSort, Row, RowData, TableFeatures } from '@tanstack/react-table' +import type { CellData, ColumnSort, RowData, TableFeatures } from '@tanstack/react-table' import type { DataTableConfig } from '@/config/data-table' -import type { DataTableFeatures } from '@/lib/data-table-features' -import type { FilterItemSchema } from '@/lib/parsers' declare module '@tanstack/react-table' { // oxlint-disable-next-line no-unused-vars @@ -41,19 +39,8 @@ export interface Option { icon?: React.FC> } -export type FilterOperator = DataTableConfig['operators'][number] -export type FilterVariant = DataTableConfig['filterVariants'][number] -export type JoinOperator = DataTableConfig['joinOperators'][number] +type FilterVariant = DataTableConfig['filterVariants'][number] export interface ExtendedColumnSort extends Omit { id: Extract } - -export interface ExtendedColumnFilter extends FilterItemSchema { - id: Extract -} - -export interface DataTableRowAction { - row: Row - variant: 'update' | 'delete' -} From c5f651faf5bad4f338590fff122338af31db1642 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 15:54:57 -0300 Subject: [PATCH 052/100] chore(dashboard): remove unread dataTableConfig keys The only readers of dataTableConfig are data-table-sort-list (dataTableConfig.sortOrders) and types/data-table (DataTableConfig['filterVariants']). There is no indexed, dynamic or spread access. Remove the per-type operator lists, operators and joinOperators. Nothing read them after getFiltersStateParser was removed. --- .../duron-dashboard/src/config/data-table.ts | 64 ------------------- 1 file changed, 64 deletions(-) diff --git a/packages/duron-dashboard/src/config/data-table.ts b/packages/duron-dashboard/src/config/data-table.ts index 6766cab..b123162 100644 --- a/packages/duron-dashboard/src/config/data-table.ts +++ b/packages/duron-dashboard/src/config/data-table.ts @@ -1,53 +1,6 @@ export type DataTableConfig = typeof dataTableConfig export const dataTableConfig = { - textOperators: [ - { label: 'Contains', value: 'iLike' as const }, - { label: 'Does not contain', value: 'notILike' as const }, - { label: 'Is', value: 'eq' as const }, - { label: 'Is not', value: 'ne' as const }, - { label: 'Is empty', value: 'isEmpty' as const }, - { label: 'Is not empty', value: 'isNotEmpty' as const }, - ], - numericOperators: [ - { label: 'Is', value: 'eq' as const }, - { label: 'Is not', value: 'ne' as const }, - { label: 'Is less than', value: 'lt' as const }, - { label: 'Is less than or equal to', value: 'lte' as const }, - { label: 'Is greater than', value: 'gt' as const }, - { label: 'Is greater than or equal to', value: 'gte' as const }, - { label: 'Is between', value: 'isBetween' as const }, - { label: 'Is empty', value: 'isEmpty' as const }, - { label: 'Is not empty', value: 'isNotEmpty' as const }, - ], - dateOperators: [ - { label: 'Is', value: 'eq' as const }, - { label: 'Is not', value: 'ne' as const }, - { label: 'Is before', value: 'lt' as const }, - { label: 'Is after', value: 'gt' as const }, - { label: 'Is on or before', value: 'lte' as const }, - { label: 'Is on or after', value: 'gte' as const }, - { label: 'Is between', value: 'isBetween' as const }, - { label: 'Is relative to today', value: 'isRelativeToToday' as const }, - { label: 'Is empty', value: 'isEmpty' as const }, - { label: 'Is not empty', value: 'isNotEmpty' as const }, - ], - selectOperators: [ - { label: 'Is', value: 'eq' as const }, - { label: 'Is not', value: 'ne' as const }, - { label: 'Is empty', value: 'isEmpty' as const }, - { label: 'Is not empty', value: 'isNotEmpty' as const }, - ], - multiSelectOperators: [ - { label: 'Has any of', value: 'inArray' as const }, - { label: 'Has none of', value: 'notInArray' as const }, - { label: 'Is empty', value: 'isEmpty' as const }, - { label: 'Is not empty', value: 'isNotEmpty' as const }, - ], - booleanOperators: [ - { label: 'Is', value: 'eq' as const }, - { label: 'Is not', value: 'ne' as const }, - ], sortOrders: [ { label: 'Asc', value: 'asc' as const }, { label: 'Desc', value: 'desc' as const }, @@ -62,21 +15,4 @@ export const dataTableConfig = { 'select', 'multiSelect', ] as const, - operators: [ - 'iLike', - 'notILike', - 'eq', - 'ne', - 'inArray', - 'notInArray', - 'isEmpty', - 'isNotEmpty', - 'lt', - 'lte', - 'gt', - 'gte', - 'isBetween', - 'isRelativeToToday', - ] as const, - joinOperators: ['and', 'or'] as const, } From 1532cb54490aac441e84faba38c5d8d21ec855cd Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 16:02:34 -0300 Subject: [PATCH 053/100] chore(deps): oxlint 1.96, oxfmt 0.81, react-virtual 3.14.31, p-retry 9 - oxlint ^1.96.0, oxfmt ^0.81.0: lint and format are clean without changes. - @tanstack/react-virtual ^3.14.31 (dashboard). - p-retry ^9.0.0 (duron devDependency, used only by test/docker.ts). The breaking changes in 8.0 and 9.0 are the Node 22 requirement, the callback order, abort-signal semantics, shouldConsumeRetry defaults and option validation. docker.ts uses only retries/factor/min/maxTimeout, so no code change is needed. --- bun.lock | 94 +++++++++++++-------------- package.json | 4 +- packages/duron-dashboard/package.json | 2 +- packages/duron/package.json | 2 +- 4 files changed, 51 insertions(+), 51 deletions(-) diff --git a/bun.lock b/bun.lock index 588c8b6..c2fd2f8 100644 --- a/bun.lock +++ b/bun.lock @@ -5,8 +5,8 @@ "": { "name": "duron-workspace", "devDependencies": { - "oxfmt": "^0.80.0", - "oxlint": "^1.95.0", + "oxfmt": "^0.81.0", + "oxlint": "^1.96.0", "typescript": "^7.0.2", }, }, @@ -62,7 +62,7 @@ "@types/node": "^26.6.11", "drizzle-kit": "1.0.0-rc.6", "drizzle-orm": "1.0.0-rc.6", - "p-retry": "^7.1.1", + "p-retry": "^9.0.0", "postgres": "^4.2.0", "typescript": "^7", }, @@ -101,7 +101,7 @@ "@radix-ui/react-tooltip": "^1.4.1", "@tanstack/react-query": "^5.108.4", "@tanstack/react-table": "^9.3.1", - "@tanstack/react-virtual": "^3.14.30", + "@tanstack/react-virtual": "^3.14.31", "bun-plugin-tailwind": "^0.1.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -348,81 +348,81 @@ "@oxc-project/types": ["@oxc-project/types@0.160.0", "", {}, "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA=="], - "@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.80.0", "", { "os": "android", "cpu": "arm" }, "sha512-IKgbKL684l/0zb1yAIr7YkqmUsZmO6O02ELkb+78SLFsDJAJxCtPtLypHGUGNpeOrsdIHXIZMxYGo/9QYSHuhg=="], + "@oxfmt/binding-android-arm-eabi": ["@oxfmt/binding-android-arm-eabi@0.81.0", "", { "os": "android", "cpu": "arm" }, "sha512-wlb5bszpOCKBg52In0Hrqz8zdzjQ8hQtZjdnfC3rZp2ondwPqUwwXuBZku0h6FEvK08DnZhzztB+DvtmmHrByg=="], - "@oxfmt/binding-android-arm64": ["@oxfmt/binding-android-arm64@0.80.0", "", { "os": "android", "cpu": "arm64" }, "sha512-fGqMAgBeKlE1CsnpKNuIlahJmJgYxLrOiwacsYdqK0fv8hu7flDAQN0MTa5joCoc0gfLV/RJKAKp0b6FsODGYQ=="], + "@oxfmt/binding-android-arm64": ["@oxfmt/binding-android-arm64@0.81.0", "", { "os": "android", "cpu": "arm64" }, "sha512-JMHJYkgpIJSeY+pIi2LAm+Qj61xIdqkbI5RAISITWxT8gzuqR0DkA1ZEgIZ+0B/ydTtGQv/+y4CFHDOgwgJwfA=="], - "@oxfmt/binding-darwin-arm64": ["@oxfmt/binding-darwin-arm64@0.80.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-6EyFZdBrB+86OK/C4CqqqRwRPnp/sLxzFf1vWg8Ghd369zAyNLkxAu9JMXnzkXoW491j7X7cRNs/ayuFs7hMwg=="], + "@oxfmt/binding-darwin-arm64": ["@oxfmt/binding-darwin-arm64@0.81.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-/ovt9o0S8CHKhhHjy179vzBg95P5O+brn1/1G02k2JFoABFauJMwlDw/iMScs6WXA1VgPJgTrvc9iiZd1VwO6w=="], - "@oxfmt/binding-darwin-x64": ["@oxfmt/binding-darwin-x64@0.80.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-ZZEKe4O/3qrRTYcMWVBpfBN3+ANDwwEGt5FijDw4Q31zqXDj8WXfnytWsTGu0sh3nJ7tLbIzypY+oYRCfb9ffg=="], + "@oxfmt/binding-darwin-x64": ["@oxfmt/binding-darwin-x64@0.81.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-SbUD/zbob0DVePxtZgoWV0pX5fViC2F12jobjoptW7sl3P0bQhbnD3+9wsd2XcbbwbabK1zSu0MT7FFxiETl+Q=="], - "@oxfmt/binding-freebsd-x64": ["@oxfmt/binding-freebsd-x64@0.80.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-yBTHy84SOBhag+A/KRMp0vctB0t5Vn6PjlVHfYWpqzWhWgvgktzdFplTSSV8Lu9oXY4Xr8EU+01N88J1S2tNCg=="], + "@oxfmt/binding-freebsd-x64": ["@oxfmt/binding-freebsd-x64@0.81.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-u+IgTRPHPYFUUPIVHHecRufdEAH2Q6S57P6KUq1p9/Kqyq3TZcQzg9a2o0ideJKmvI+JBldrB/t5nYYXteEOng=="], - "@oxfmt/binding-linux-arm-gnueabihf": ["@oxfmt/binding-linux-arm-gnueabihf@0.80.0", "", { "os": "linux", "cpu": "arm" }, "sha512-HwSZYzbNF04nwduBcn0KZZ2kwnCuzEf8hCfsZ4bkRbDIzjIjhTsI6O3l+0sIKpU2F718szvkEfVPMkIksZ/NYQ=="], + "@oxfmt/binding-linux-arm-gnueabihf": ["@oxfmt/binding-linux-arm-gnueabihf@0.81.0", "", { "os": "linux", "cpu": "arm" }, "sha512-xLvphnc/ZrGKNHAvk7XjbOGZodn4vPs+cvguo/hrmF62ZF0XS8Myu/YaSKL+/97E6DZSnelQRlgoOkCSRyofaw=="], - "@oxfmt/binding-linux-arm-musleabihf": ["@oxfmt/binding-linux-arm-musleabihf@0.80.0", "", { "os": "linux", "cpu": "arm" }, "sha512-rVPpw9dRTiBLgxdfySNhKihMTPy1SPb1+y+EDrVK0aUj/k8pm51zTANKfFr9bMgVxcDuGO227QwzZRhT0WQcHQ=="], + "@oxfmt/binding-linux-arm-musleabihf": ["@oxfmt/binding-linux-arm-musleabihf@0.81.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N1212QKzbPFcryiPmvCH1u1yAocySPd/zauCJzojKvCReNSB4P6qRqlGZGJc0WbXJBVr63pEn148pkshEvU0UQ=="], - "@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/binding-linux-arm64-gnu@0.80.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-1yZ3eWD9X2TcwpMt/SaQjlclyZqVVmBNh+62svgGBRZJIzWz4EIBq0ZMj5Unn20gzm3y9OLEnWdmJ4b9/izmLw=="], + "@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/binding-linux-arm64-gnu@0.81.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-KfdloRQ14KE9pucAQw57jKyNLgpPQPXMTCvmUXDzdQa8ovMXHBzijkiazSObzR3jw27Rj7PiaBqZt2gFtDVrrQ=="], - "@oxfmt/binding-linux-arm64-musl": ["@oxfmt/binding-linux-arm64-musl@0.80.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-FTCv1p32lqfXNmicCXvluPACYrqqMChrI4bVJWh8UrvwlaxO9YkF3toLu6MaESav0e3X/GA7BkK2c7wyok7qyQ=="], + "@oxfmt/binding-linux-arm64-musl": ["@oxfmt/binding-linux-arm64-musl@0.81.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-x2ByQdlMcs1uPKGD9PvBNwnAuuemOJxjlYYYGOB4+zz/JCKbaB00WT1BjDjqEciYHiiqcLkZmjG3FNPHSyCzag=="], - "@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/binding-linux-ppc64-gnu@0.80.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-jl0ivd2WpjlWbe/sgcvW3E4CbJyxVXNBc9vVTSv1mNN28phPXczG97nXxWhdQu+oAikpXtyf5VAP41P4OT+48A=="], + "@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/binding-linux-ppc64-gnu@0.81.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-YQ1NpjKIox5MZqngqW/2kI6m9FDOQPsLoPod90igYGHCFIwcPmcqGGAlKvVcYl5+5iX+YwLL30BmZDnKUL8pBA=="], - "@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/binding-linux-riscv64-gnu@0.80.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-Iu6q6EsvYtGag7pxQl9HV/k+lEv9SbatZb4fyrWYwIFeAivAl9NNh7o4kizpzsfDOIFKWSmEPkbhzKrucSdQZg=="], + "@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/binding-linux-riscv64-gnu@0.81.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-ZUgG05Q7jTvFeNeLvWHTBRIV4WHIXevLz39OkkDI+uTisEF1znDpWSNwgGVLcVxT3TcdIeoTaf7MfrROOtnemg=="], - "@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/binding-linux-riscv64-musl@0.80.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-e6QIq9l1yHQuNp1u8+veTkQGOHBeayekax5ZfWoi2gwBGJoFVaq9Klovdt8wg/I8R+3eHQVB7yzhXekfMXozQw=="], + "@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/binding-linux-riscv64-musl@0.81.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-4QJhg7Tl6mc1WAcOKUomxVT+laKbxJjDaNGWzkRWTATmA1l4w4c0XqraIZBvM29VXlGQj+PvseLcSk9XFr2Hbw=="], - "@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/binding-linux-s390x-gnu@0.80.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-Fqs2/RNU3MaHvGvLinaRIhZbXJV6MwloGnyK0COfHbF4oTmfgfmdXzrMgk/04DD+0RfdZvdF/82DoaWbYWgfqA=="], + "@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/binding-linux-s390x-gnu@0.81.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-rbSQY9K1pS6v8JCJJNR1FE+qPSOLRnIS8HUVapi210M/FbrmWV/3in+S1wtA72YY0izcB7AuY7Wg3kQUQdziww=="], - "@oxfmt/binding-linux-x64-gnu": ["@oxfmt/binding-linux-x64-gnu@0.80.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-5ZZBWDHwGYsqprHma9UwFXNJfkTo4IXu/obbxhz8y/qsQfl/k00HQsXZYBnIlytEWjE1tZZmSimjIObqj8Jyog=="], + "@oxfmt/binding-linux-x64-gnu": ["@oxfmt/binding-linux-x64-gnu@0.81.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-BhYZ9V/2G/yce6mY2cvraetgy37sdwwXFoUhwdb2rruz9wnQY1qD42CIbgV5Yu43oNz1OhJ6EVK0Iw0dLyoUMQ=="], - "@oxfmt/binding-linux-x64-musl": ["@oxfmt/binding-linux-x64-musl@0.80.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-3hbDeK3hijv3zyoZm0kONLkqJbfd4nr0cfFL/veo1chgcnovp9lyiuFiFltCqFKs0qnuEz7qA99mee0Pcm+fXw=="], + "@oxfmt/binding-linux-x64-musl": ["@oxfmt/binding-linux-x64-musl@0.81.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-IF01AJK7EMc5TWDVf8KCFVNI8HCjzsoycLD18iSbJR4mZ1FMqkbPOKPWuwKCYaXav20lvcz8+GRdDPlJhGZ2PQ=="], - "@oxfmt/binding-openharmony-arm64": ["@oxfmt/binding-openharmony-arm64@0.80.0", "", { "os": "none", "cpu": "arm64" }, "sha512-5ThMiM6QKqfWaOxtzq+HaYyrWe48MGg49pDc9ll5KFvPEPo2Hqagz0JSk6hhZ3vOF/7tIhGIGu3mVnVuulwMQA=="], + "@oxfmt/binding-openharmony-arm64": ["@oxfmt/binding-openharmony-arm64@0.81.0", "", { "os": "none", "cpu": "arm64" }, "sha512-tYZOH03aUtKOOAauAmo45d0ZRUmwIGmcn/mtc19YyqmrAs5iR61T5gjDjq1X70aBDcz+4D+sE8SR3Q0yiqZklQ=="], - "@oxfmt/binding-win32-arm64-msvc": ["@oxfmt/binding-win32-arm64-msvc@0.80.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-YEPyJo02Wc9fzHBqp8OofJVmb9i92PtYTfpUJ5oXmCOGjfiDoqVlIh7vGVts91LnKL8UZ3cyXuM3tuqPKoZ40g=="], + "@oxfmt/binding-win32-arm64-msvc": ["@oxfmt/binding-win32-arm64-msvc@0.81.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-Z7Ia6NuCmgN3Y8/tLuXDoHkm7osNLF8Gux20UrLaO4kYTXNl7X6kbA1umxyyXy/OJqrIzg/CdczDJKRlg5hXhg=="], - "@oxfmt/binding-win32-ia32-msvc": ["@oxfmt/binding-win32-ia32-msvc@0.80.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-vimQJkghBVQO/+YEe6ybFaqUd2oMl2srd/jJFGgVlpdSOIWmOVIsBv9dn9SyjzSFXJnhDrBCtU0pnTutjNWnSg=="], + "@oxfmt/binding-win32-ia32-msvc": ["@oxfmt/binding-win32-ia32-msvc@0.81.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-E0ybKSoI35U9gC8N4STxzZyVmTYT6I1dMTwnPH2hsu/oFPW+R4gmdx3W4sLN4eOXMKub6Zk3Wl1Xf2cS+WBagg=="], - "@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.80.0", "", { "os": "win32", "cpu": "x64" }, "sha512-kfJaMYppxdcTfZe+4Ify0uAVCgwEMFg/yp9WDnZ2Vh4KFd09dN5dgsomYDWN0UhzSTb9/OqDY3S7IczL+XOmaA=="], + "@oxfmt/binding-win32-x64-msvc": ["@oxfmt/binding-win32-x64-msvc@0.81.0", "", { "os": "win32", "cpu": "x64" }, "sha512-fAGnOILTfcJfgVasE/T3FuxBqSsoXtaQxmpuFvxmIRqW5AyA8nWsAJbrB3SCP8C8WyMLfz9agHhHGFtb50Otsw=="], - "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.95.0", "", { "os": "android", "cpu": "arm" }, "sha512-hJna6w3COWJjfMPxomjZL82klTdrITm56PEpCsfO/xMkzQw/fNtJWauQ/YEwQqVttj0L5vDIa8rCcuhfAE3L4w=="], + "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.96.0", "", { "os": "android", "cpu": "arm" }, "sha512-SCINGNIfxMCeONnTjTQdm27XYY3zWv5olN/RIJmoTbMgphJ8JkZMeivswWqPdjwYpTAuskGNpHbevtECumuIxg=="], - "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.95.0", "", { "os": "android", "cpu": "arm64" }, "sha512-uAIGZQ9uJVUeogeWOSboI3F7twOuM4mNuZcHXD9+LdYLcWp7J6kbtRUXJ6GVqcs5E0Cjb4emmSBK9FNrkGuhqQ=="], + "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.96.0", "", { "os": "android", "cpu": "arm64" }, "sha512-jmRRp4pThMoYheXzhDrEMOHMU6X0geGSzJznkF2xhE9l0aViXNBvZrWasR5WLc3FXlc0rQAtV/o9mH1wosXZGQ=="], - "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.95.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Ogh1vfHO5vshKRop/He46r+WqC5BTqonYwhB4fp9e2gvOFvg1Xi6XsHTuM/lBSH85ZcaG+DS99EMAy9GcwDong=="], + "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.96.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RxRoSJY2xa9/dKRzPv1rLn36OvaCwu7Qg9o+NhrSIP7FkLWackAkfbf+5bcgIC5H1r78sdWUvVAIDJKDdfkXPg=="], - "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.95.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-kTrE1xfpQUBMMS50Ws6KY92N8OsJ8LE6JqxKqkHEY3KdsmguQ6kKVGSjzyt1HLwsSi0fQCvNRog8YRBBovD1AA=="], + "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.96.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-pokl9aeRHG0ke37GooIG/Jjd5bIFx9TDZ9//JkO0KDROJ3MIGz+KD9/hlq6siE40+auswpyaolZ4xNqzaX1VWw=="], - "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.95.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-ho7E1VCInK0VnpneRaI1BEpe1ceJE8VjxP2O9THWdReV6bth1Q4+80kYVGGK47mHRyZ2NGztQZ2dWRo6j1lavA=="], + "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.96.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-zV8oqk0kzAFa8hsiBXz431E9DvYZuhIOveTKk7bgKmeYy1KixJ//iwdBMvD6+IGq0HAxxX2eCAbdzecC2Qsrpw=="], - "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.95.0", "", { "os": "linux", "cpu": "arm" }, "sha512-94afnouMHcnHr/OtRh07gG5LehC9M0GjiSoik3xxTtrmq6cWxXOTAhYlBtxa67u/GlycbnHlDoGJfYlTshcr/w=="], + "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.96.0", "", { "os": "linux", "cpu": "arm" }, "sha512-hT4CHT09eiWrwIikLjqiQrcjF1lASaRrJR4rGwXhHQcXC8Z5ohkDOy897tV/+UK/RkDvhtX3YOV3LGultcJTxg=="], - "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.95.0", "", { "os": "linux", "cpu": "arm" }, "sha512-LEeclqV1/fafxPgJWN21Bri6HBBBZpEFluq/ZH7Avvu9HjJh/XOn6WwogJqX9X7pG2aITZ2nRH39+sUKEQt2WA=="], + "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.96.0", "", { "os": "linux", "cpu": "arm" }, "sha512-ro+mX13ijz/Z2IIstN3TnPjoOzMZmvvS6xj/RIkyWZJveU/W5WkuFkISb81M7dxVDywHNUUljs9kGXL+ZpCkAA=="], - "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.95.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-EpXpEQKmgtkvc6RyU84LM1e3CrVDWQkgghVzf1hMGgwjBzgKAJ/QntHgnzmu5cNeLBfa7GPCY+gGXxEll8Adcg=="], + "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.96.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-kpJqgwJ4xCzg0HiZr0IqPumqoskk7z9m+epDKC8cxuC6sS5GeX0u8XpuotC7BKto0htzq+AmpZ6/LPIqOJ2J2w=="], - "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.95.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-+96Md8c2BAgFp8nWHrUrpqba87DoU+HVJYIun6qA+QKFoeNd3xAWq1JYE6da4nVli9GgwRpfncfRePcgmQQaIQ=="], + "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.96.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-sPqrWFuk8IsDx5ftGQVCaxRfnR95b3aXFQrknHDsb0W6UGYkhmhU6ZcirV/9Etyf44dAYo3ZMyA30bRow1sz5w=="], - "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.95.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-6yG99vsXct3Uv536w6Z1s03w2makRKnE0q3eJSmf+W/IwPmO56QLk8XUA6ebu/R5peCbJ67HmcWqACH+kg/6Bg=="], + "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.96.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-41bcNpgz0TDw2bPseL18MWtiyxrkadp5XVqRPr3TmGSDO2NpXdrHQ3UbXOiSpi5Dko7H22iNg9kcl/q/TZrcWA=="], - "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.95.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-Eir0Z4ldh55AsQUqVDlLF4Pw3lSFXIdAl8ZNgU8tp/gTwT9JVCzWY0o3+ys9pCcpTN0vCqBwwuQfAUxzbIgvcQ=="], + "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.96.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-XsuYByplvx4CjLwBTDNiWEB3Igk1NVgg0jqndZA9Op59ssCqO9PYZmg8af+GMOfrOtpdiFiGnogi0PfvCihGrg=="], - "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.95.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-ceRx+K2WJ7C3tIv+XjZS28oAoZ7DY29ZcWChPdXG5M100phI72FRDYwGRlWZEeDfmkROnarLTMKnnrQAtsC42Q=="], + "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.96.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-J+JcvoObB6gsi3TxaY8tu0gc2ZEcxYbKz7t0N85RurdEU1ubXHTJqKOe8D5aH3KPSmlT3+8f81UhVI4qF4WoUQ=="], - "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.95.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-WbD3sM08ZDk2QE6060wK/omihQKbRm+LVzKIg4W5zNTbEhYJChciqX49UZuqW59RGF+wBUxzAup7egUIESTjUA=="], + "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.96.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-wON5n7KlNpVWMhzYt9G3Ew2iuL6hHt0LV69dg51quv78mx7jOWFZp/+2ny2vARWl1542RRSip70hb7DAj2yy+Q=="], - "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.95.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-F4ST2ZkFIiLL9OKyRCyC0KQQpwM5WIv0GTcMiZuYVa6xSRJHR05iVRqst+arOVudEPkhP47EnbuoC9UfVCYDyg=="], + "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.96.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-AURdLIDjJvUK1XjWtnQI6TJs8F3SAQOFsDeL3QQChNwKAWbCZmT4jjflXMb6hjTY6NS1mnP1Z2sWz/yLI1BvTg=="], - "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.95.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-hEpYDZatpuxLrWlTlkwhHZ1e8QkL02aFS55BPQX1XA9iOd+yUEADGFF1iY6z+xkw6RkpzXFrtnDFe4/JNOLSRA=="], + "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.96.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-4+qtiKtCov+b8psbs4/O3nOtNh40bZN/QYxjjmOgV7OHmcD8rBwJqV4AeeXGZ/pSUCGNYGm1sQtiy4AAhJ5xqQ=="], - "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.95.0", "", { "os": "none", "cpu": "arm64" }, "sha512-+JwIH9/uLgQXfxBvOAKzvp616m5i0fBR5ELEBHm5D+++fStBZ+74T7YW4xBpX13zNU2blr52Swoe3GTF1JyqRg=="], + "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.96.0", "", { "os": "none", "cpu": "arm64" }, "sha512-eYZmZlTFgwz3c0+nLlZc+QdFTJJQ9B98vvLSk8LPJm+edhhiuLOe6jIUiLWwc52s95GKz5US05cAsVd8e5BzOA=="], - "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.95.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-pzJgcp3WkOSchukg5y5pn5mVIQ6P83RDI79YJ9gQZKed1pOgjhrmlc5AMizjuq6/P8VifhxzBsMqYI6LLjO2TA=="], + "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.96.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-elsIvBZeDYDO3swjXGBh8kGrsVrlcDNv6X2+ASA7q02UPuAWjH5F8urTa2d32c+f7l9MFohMokdWZ82pV+oZ9Q=="], - "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.95.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-54MeQvLRXkJqF1nEFs7wb73SrnurZJQy9fVK4NdEwumNKVwyUUxpGHhvfDMIY2NqJZS7kz0pY9uVty5664Gt1Q=="], + "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.96.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-Sl6tX5MdGZ886jSHmeg71ijhtsELauPl4ii4pfAtrQV3W7uj+v5QF1eAZB74KySWt6sdZuNDyjfhaKGaCf6NWA=="], - "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.95.0", "", { "os": "win32", "cpu": "x64" }, "sha512-I/Fn+Fed1qzb1k2uRjMe2VRtRN1+ZObyU+E76B6v/Ul3Z6JdeAW5zBHSe0n5d8a0ZyU4iorzVy0Rw9LYgo3MSQ=="], + "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.96.0", "", { "os": "win32", "cpu": "x64" }, "sha512-gLx6y/CsxfNZdfBfSLbVHB75AHDfV2/XdilDqPgh7oNRL6y72s75TCbMt500km+Mk5izFYNYXX8+LYR6U4n/zA=="], "@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="], @@ -614,7 +614,7 @@ "@tanstack/react-table": ["@tanstack/react-table@9.3.1", "", { "dependencies": { "@tanstack/react-store": "^0.11.2", "@tanstack/table-core": "9.3.1" }, "peerDependencies": { "react": ">=18" } }, "sha512-E6Ya5TnY6EaGyZYIUqig/29Lr/gJSAubQkLJFqiWkUl5nRCr0Xr9hvJot+NiRTtG+TzGxHTiqUW3bnLtQxlHug=="], - "@tanstack/react-virtual": ["@tanstack/react-virtual@3.14.30", "", { "dependencies": { "@tanstack/virtual-core": "3.19.15" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-vVq9U2WahGWue0RVPrzGuBM8QxhGKq6WV7AOUyXWR17F3kYNxHMZekYZdKm0X63/S4QZGCDlBqASvAukpXQ8GQ=="], + "@tanstack/react-virtual": ["@tanstack/react-virtual@3.14.31", "", { "dependencies": { "@tanstack/virtual-core": "3.19.16" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-PUCZlf1Lmg8wFrmosu/Nk82OMQTTjzjffqRN33cgzDuAno9wxGf9SaULhHE7VWePsmqaYmQ6V6dNnpX7QPx+Pg=="], "@tanstack/router-core": ["@tanstack/router-core@1.171.39", "", { "dependencies": { "@tanstack/history": "1.162.5", "cookie-es": "^3.0.0", "seroval": "^1.6.7", "seroval-plugins": "^1.6.7" } }, "sha512-qUhoJ0meuSUqGYQbHbcJYdASr06YtK+bulbj6vtrhKYFkLgkSsZ6tXmMyym7sFxiSJSPYgasgozrL01LyyR/6A=="], @@ -640,7 +640,7 @@ "@tanstack/table-core": ["@tanstack/table-core@9.3.1", "", { "dependencies": { "@tanstack/store": "^0.11.2" } }, "sha512-zQvlxSNi2qGM3L4jh85Z6hqMfdIR5qOfD9KHOU32nuKFJGN0RlJ7UvV1lsPb1fPVhpFYI0VP3jJGxLdLDpTKjQ=="], - "@tanstack/virtual-core": ["@tanstack/virtual-core@3.19.15", "", {}, "sha512-XL0RLw2Y1Qm5IrtIuz0cmX2nDc2hjtKr0J+7S+xHaDHcy19u8Fg1o17nCBMIKlrCgmMcgnViexlHGDx8SniuBw=="], + "@tanstack/virtual-core": ["@tanstack/virtual-core@3.19.16", "", {}, "sha512-bdHBFIYGLvR/yb7slnoR+PdbgxBnLG2emsjxpOrXBbY9scz6hNyCYJqA2oXEF/xOYcy8iyxO413qMgBbwkBjmQ=="], "@tanstack/virtual-file-routes": ["@tanstack/virtual-file-routes@1.162.0", "", {}, "sha512-uhOeFyxLcU41HzvrxsGpiWdcMbScY1EDgbZ5K7DVRMYInbLYWAC0EA/kx9wXAoSM8q82bUG2hRl8+EAjE6XAbA=="], @@ -1216,11 +1216,11 @@ "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], - "oxfmt": ["oxfmt@0.80.0", "", { "dependencies": { "tinypool": "2.2.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.80.0", "@oxfmt/binding-android-arm64": "0.80.0", "@oxfmt/binding-darwin-arm64": "0.80.0", "@oxfmt/binding-darwin-x64": "0.80.0", "@oxfmt/binding-freebsd-x64": "0.80.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.80.0", "@oxfmt/binding-linux-arm-musleabihf": "0.80.0", "@oxfmt/binding-linux-arm64-gnu": "0.80.0", "@oxfmt/binding-linux-arm64-musl": "0.80.0", "@oxfmt/binding-linux-ppc64-gnu": "0.80.0", "@oxfmt/binding-linux-riscv64-gnu": "0.80.0", "@oxfmt/binding-linux-riscv64-musl": "0.80.0", "@oxfmt/binding-linux-s390x-gnu": "0.80.0", "@oxfmt/binding-linux-x64-gnu": "0.80.0", "@oxfmt/binding-linux-x64-musl": "0.80.0", "@oxfmt/binding-openharmony-arm64": "0.80.0", "@oxfmt/binding-win32-arm64-msvc": "0.80.0", "@oxfmt/binding-win32-ia32-msvc": "0.80.0", "@oxfmt/binding-win32-x64-msvc": "0.80.0" }, "peerDependencies": { "@astrojs/compiler-rs": "^0.5.0", "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["@astrojs/compiler-rs", "svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-jy8/kYEomtC6g1LqXDl1LEXk5Ih+c7a1jB5wxqEp8qBmDoOD7Ei+XCxU2jGEjGUdBfoPef6rDiSENVLJ5gWq+Q=="], + "oxfmt": ["oxfmt@0.81.0", "", { "dependencies": { "tinypool": "2.2.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.81.0", "@oxfmt/binding-android-arm64": "0.81.0", "@oxfmt/binding-darwin-arm64": "0.81.0", "@oxfmt/binding-darwin-x64": "0.81.0", "@oxfmt/binding-freebsd-x64": "0.81.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.81.0", "@oxfmt/binding-linux-arm-musleabihf": "0.81.0", "@oxfmt/binding-linux-arm64-gnu": "0.81.0", "@oxfmt/binding-linux-arm64-musl": "0.81.0", "@oxfmt/binding-linux-ppc64-gnu": "0.81.0", "@oxfmt/binding-linux-riscv64-gnu": "0.81.0", "@oxfmt/binding-linux-riscv64-musl": "0.81.0", "@oxfmt/binding-linux-s390x-gnu": "0.81.0", "@oxfmt/binding-linux-x64-gnu": "0.81.0", "@oxfmt/binding-linux-x64-musl": "0.81.0", "@oxfmt/binding-openharmony-arm64": "0.81.0", "@oxfmt/binding-win32-arm64-msvc": "0.81.0", "@oxfmt/binding-win32-ia32-msvc": "0.81.0", "@oxfmt/binding-win32-x64-msvc": "0.81.0" }, "peerDependencies": { "@astrojs/compiler-rs": "^0.5.0", "svelte": "^5.0.0", "vite-plus": "*" }, "optionalPeers": ["@astrojs/compiler-rs", "svelte", "vite-plus"], "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-EIuSGUDB9hoHgppuQzTKI3DI1UJzPFTUrf3GGPqSef1tbdY1UNHsy240cOsPDxHFdvW6PJLr3WHS2RG1qvnd8Q=="], - "oxlint": ["oxlint@1.95.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.95.0", "@oxlint/binding-android-arm64": "1.95.0", "@oxlint/binding-darwin-arm64": "1.95.0", "@oxlint/binding-darwin-x64": "1.95.0", "@oxlint/binding-freebsd-x64": "1.95.0", "@oxlint/binding-linux-arm-gnueabihf": "1.95.0", "@oxlint/binding-linux-arm-musleabihf": "1.95.0", "@oxlint/binding-linux-arm64-gnu": "1.95.0", "@oxlint/binding-linux-arm64-musl": "1.95.0", "@oxlint/binding-linux-ppc64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-gnu": "1.95.0", "@oxlint/binding-linux-riscv64-musl": "1.95.0", "@oxlint/binding-linux-s390x-gnu": "1.95.0", "@oxlint/binding-linux-x64-gnu": "1.95.0", "@oxlint/binding-linux-x64-musl": "1.95.0", "@oxlint/binding-openharmony-arm64": "1.95.0", "@oxlint/binding-win32-arm64-msvc": "1.95.0", "@oxlint/binding-win32-ia32-msvc": "1.95.0", "@oxlint/binding-win32-x64-msvc": "1.95.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2008", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-eNzjFjm1TU02/+ohAJjOB7aekRQgTXhOWxMGscEm8VJMokNnnix+PCZn7kqIuGIqxAoBnHxatqlN3Chz3N6PKA=="], + "oxlint": ["oxlint@1.96.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.96.0", "@oxlint/binding-android-arm64": "1.96.0", "@oxlint/binding-darwin-arm64": "1.96.0", "@oxlint/binding-darwin-x64": "1.96.0", "@oxlint/binding-freebsd-x64": "1.96.0", "@oxlint/binding-linux-arm-gnueabihf": "1.96.0", "@oxlint/binding-linux-arm-musleabihf": "1.96.0", "@oxlint/binding-linux-arm64-gnu": "1.96.0", "@oxlint/binding-linux-arm64-musl": "1.96.0", "@oxlint/binding-linux-ppc64-gnu": "1.96.0", "@oxlint/binding-linux-riscv64-gnu": "1.96.0", "@oxlint/binding-linux-riscv64-musl": "1.96.0", "@oxlint/binding-linux-s390x-gnu": "1.96.0", "@oxlint/binding-linux-x64-gnu": "1.96.0", "@oxlint/binding-linux-x64-musl": "1.96.0", "@oxlint/binding-openharmony-arm64": "1.96.0", "@oxlint/binding-win32-arm64-msvc": "1.96.0", "@oxlint/binding-win32-ia32-msvc": "1.96.0", "@oxlint/binding-win32-x64-msvc": "1.96.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2008", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-jyiSvUjzM6GPHNbNQSk9ov63KDusn7FJaIX4LqxJYN/VnRrEgwMplyZaoAfmVclfzxCmVhaIXLixnRJ2IAa0Hw=="], - "p-retry": ["p-retry@7.1.1", "", { "dependencies": { "is-network-error": "^1.1.0" } }, "sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w=="], + "p-retry": ["p-retry@9.0.0", "", { "dependencies": { "is-network-error": "^1.3.2" } }, "sha512-HuEats8gYn/UUYa5uyveyQGv75mQmwdFtuMgnZlS12dj/7bdnJSO6keaTjgcZUhvkANTj5EO3lACUmV3xmgj0Q=="], "parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="], diff --git a/package.json b/package.json index d62f4c4..6b9f6ab 100644 --- a/package.json +++ b/package.json @@ -24,8 +24,8 @@ }, "dependencies": {}, "devDependencies": { - "oxfmt": "^0.80.0", - "oxlint": "^1.95.0", + "oxfmt": "^0.81.0", + "oxlint": "^1.96.0", "typescript": "^7.0.2" } } diff --git a/packages/duron-dashboard/package.json b/packages/duron-dashboard/package.json index b44cf99..3c8e24c 100644 --- a/packages/duron-dashboard/package.json +++ b/packages/duron-dashboard/package.json @@ -56,7 +56,7 @@ "@radix-ui/react-tooltip": "^1.4.1", "@tanstack/react-query": "^5.108.4", "@tanstack/react-table": "^9.3.1", - "@tanstack/react-virtual": "^3.14.30", + "@tanstack/react-virtual": "^3.14.31", "bun-plugin-tailwind": "^0.1.2", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/packages/duron/package.json b/packages/duron/package.json index f9559e5..ca06fd2 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -100,7 +100,7 @@ "@types/node": "^26.6.11", "drizzle-kit": "1.0.0-rc.6", "drizzle-orm": "1.0.0-rc.6", - "p-retry": "^7.1.1", + "p-retry": "^9.0.0", "postgres": "^4.2.0", "typescript": "^7" }, From 314ddd9cb4d41ed3b6610dae7378da9c53d7ee6e Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 16:42:04 -0300 Subject: [PATCH 054/100] fix(time-travel): lossless archive restore keeps sub-millisecond step order Time travel keeps a completed step only if it was created strictly before the target (created_at < target.created_at). Restoring an archived job went through a JS select/insert round trip, which cut created_at, started_at and finished_at to milliseconds. On PostgreSQL, two sequential sibling steps created in the same millisecond then tied, and time travel deleted the completed earlier step: its output was lost and its handler ran again. Confirmed cause of the 'time travel to second child step' flake: equal created_at at the strict comparison. Two sources: the lossy restore (both engines) and PGLite's millisecond clock. - Restore the archived job and its steps with INSERT ... SELECT in the time-travel transaction (ON CONFLICT DO NOTHING, per-job filters as before), so timestamps keep their microseconds. - getJobSteps orders by created_at, then id, so tied steps come back in a stable order. - New test (both engines): archived siblings created 800 microseconds apart; time travel to the second keeps the first. It fails on the old code: the first is deleted and the times are truncated. - The elapsed-shift test pinned the lossy restore. It now expects lossless times from archive storage too (3600530865n, no date_trunc). - PGLite's clock stays millisecond, so ties remain possible there by design. The time-travel test actions wait for the next millisecond after steps that tests expect to be kept, with a comment explaining why. The docs describe which steps are kept and the PGLite limitation. --- packages/docs/content/docs/client-api.mdx | 16 +++ packages/docs/content/docs/server-api.mdx | 2 +- packages/duron/src/adapters/adapter.ts | 5 +- packages/duron/src/adapters/postgres/base.ts | 78 +++++++------- packages/duron/src/client.ts | 2 +- packages/duron/test/time-travel.test.ts | 103 +++++++++++++++---- 6 files changed, 144 insertions(+), 62 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 0eebfc2..20d878d 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -411,6 +411,22 @@ const success = await client.timeTravelJob(jobId, stepId) **Returns:** Promise resolving to `true` if time travel succeeded, `false` otherwise +Which steps are kept: + +- The target step and its ancestor steps are reset to active and run again. +- A completed step is kept if it was created strictly before the target step (by its + `createdAt` timestamp). Kept steps return their stored output when the job runs again. +- Completed `parallel` siblings of the target and of its ancestors are kept with their child + steps, whenever they were created. +- All other steps are deleted, and run again when the job reaches them. + + + With PGLite, step timestamps have millisecond resolution. A completed step created in the same + millisecond as the target step is not "before" it, so time travel deletes it and the step runs + again. PostgreSQL timestamps have microsecond resolution. Mark steps that do not depend on each + other as `parallel: true` to keep them regardless of their timestamps. + + ### `deleteJob(jobId)` Delete a job by its ID. Active jobs cannot be deleted. diff --git a/packages/docs/content/docs/server-api.mdx b/packages/docs/content/docs/server-api.mdx index f3aa1f2..9a5e660 100644 --- a/packages/docs/content/docs/server-api.mdx +++ b/packages/docs/content/docs/server-api.mdx @@ -313,7 +313,7 @@ Retry a failed job. #### `POST /jobs/:id/time-travel` -Time travel a job to restart from a specific step. The job must be in completed, failed, or cancelled status. +Time travel a job to restart from a specific step. The job must be in completed, failed, or cancelled status. Which steps are kept is described in [`timeTravelJob`](/docs/client-api#timetraveljobjobid-stepid). **Request Body:** diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index 1d2941a..e25e930 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -775,7 +775,7 @@ export abstract class Adapter extends EventEmitter { } /** - * Get all matching steps for a job, ordered by created_at ASC, without pagination. + * Get all matching steps for a job, ordered by created_at ASC (ties by id), without pagination. * Search matches step names or output; results omit output. * updatedAfter applies a strict millisecond boundary to every match. * @@ -911,7 +911,8 @@ export abstract class Adapter extends EventEmitter { protected abstract _getJobById(jobId: string): Promise /** - * Internal method to get all matching steps, ordered by created_at ASC, without pagination. + * Internal method to get all matching steps, ordered by created_at ASC (ties by id), without + * pagination. * Search matches step names or output; results omit output. * updatedAfter applies a strict millisecond boundary to every match. * diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index eaeaaf1..ac3b184 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -861,7 +861,8 @@ export abstract class PostgresBaseAdapter< * 1. Validate job is in terminal state (completed/failed/cancelled) * 2. Find the target step and all its ancestors (using parent_step_id) * 3. Determine which steps to keep: - * - Steps completed BEFORE the target step (by created_at) + * - Steps completed BEFORE the target step (strictly earlier created_at; a step created + * at the same timestamp as the target is not before it) * - Branch siblings that are completed (independent) * 4. Delete steps that should not be kept * 5. Reset ancestor steps to active status (they need to re-run) @@ -872,40 +873,43 @@ export abstract class PostgresBaseAdapter< */ protected async _timeTravelJob({ jobId, stepId }: TimeTravelJobOptions): Promise { return this.db.transaction(async (tx) => { - // First, check if the job is in the archive and restore it if needed - const archivedJob = await tx - .select() - .from(this.tables.jobsArchiveTable) + // If the job is archived, restore it and its steps to the active tables. The copy is + // SQL-native so timestamps keep their microseconds: the "created before the target" rule + // below compares created_at, and a millisecond round trip through Date would tie steps + // created in the same millisecond. Each statement is a no-op for a job that is not + // archived. ON CONFLICT DO NOTHING handles concurrent time travel of the same job. + await tx.execute(sql` + INSERT INTO ${this.tables.jobsActiveTable} ( + id, action_name, group_key, description, status, checksum, input, output, error, + timeout_ms, expires_at, started_at, finished_at, client_id, concurrency_limit, + concurrency_step_limit, created_at, updated_at + ) + SELECT + id, action_name, group_key, description, status, checksum, input, output, error, + timeout_ms, expires_at, started_at, finished_at, client_id, concurrency_limit, + concurrency_step_limit, created_at, updated_at + FROM ${this.tables.jobsArchiveTable} + WHERE id = ${jobId} + ON CONFLICT DO NOTHING + `) + await tx.execute(sql` + INSERT INTO ${this.tables.jobStepsActiveTable} ( + id, job_id, parent_step_id, parallel, name, status, output, error, + started_at, finished_at, timeout_ms, expires_at, retries_limit, + retries_count, delayed_ms, history_failed_attempts, created_at, updated_at + ) + SELECT + id, job_id, parent_step_id, parallel, name, status, output, error, + started_at, finished_at, timeout_ms, expires_at, retries_limit, + retries_count, delayed_ms, history_failed_attempts, created_at, updated_at + FROM ${this.tables.jobStepsArchiveTable} + WHERE job_id = ${jobId} + ON CONFLICT DO NOTHING + `) + // Delete the archived job and its steps (cascade via FK on steps) + await tx + .delete(this.tables.jobsArchiveTable) .where(eq(this.tables.jobsArchiveTable.id, jobId)) - .limit(1) - - if (archivedJob.length > 0) { - // Restore job from archive to active - // Use ON CONFLICT DO NOTHING to handle concurrent time-travel gracefully - const job = archivedJob[0]! - await tx - .insert(this.tables.jobsActiveTable) - .values({ ...job }) - .onConflictDoNothing() - - // Restore steps from archive to active - const archivedSteps = await tx - .select() - .from(this.tables.jobStepsArchiveTable) - .where(eq(this.tables.jobStepsArchiveTable.job_id, jobId)) - - if (archivedSteps.length > 0) { - await tx - .insert(this.tables.jobStepsActiveTable) - .values(archivedSteps.map((s) => ({ ...s }))) - .onConflictDoNothing() - } - - // Delete archived job and steps (cascade via FK on steps) - await tx - .delete(this.tables.jobsArchiveTable) - .where(eq(this.tables.jobsArchiveTable.id, jobId)) - } const result = this._map( await tx.execute<{ success: boolean }>(sql` @@ -992,7 +996,7 @@ export abstract class PostgresBaseAdapter< SELECT id FROM parallel_descendants ), -- One elapsed delta from the transaction-frozen SQL time and earliest retained start. - -- UTC intermediates avoid calendar-day/DST shifts; prior Date restoration may lose fractions. + -- UTC intermediates avoid calendar-day/DST shifts. time_offset AS ( SELECT (now() AT TIME ZONE 'UTC') - (MIN(s.started_at) AT TIME ZONE 'UTC') AS offset_interval @@ -1752,7 +1756,7 @@ export abstract class PostgresBaseAdapter< /** * Internal method to get all steps for a job with optional fuzzy search. - * Steps are always ordered by created_at ASC. + * Steps are always ordered by created_at ASC, ties by id. * Steps do not include output data. */ protected async _getJobSteps(options: GetJobStepsOptions): Promise { @@ -1837,7 +1841,7 @@ export abstract class PostgresBaseAdapter< ? sql`${fuzzySearch && fuzzySearch.length > 0 ? sql`AND` : sql`WHERE`} date_trunc('milliseconds', s."updatedAt") > ${options.updatedAfter.toISOString()}::timestamptz` : sql`` } - ORDER BY s."createdAt" ASC + ORDER BY s."createdAt" ASC, s.id ASC `), ) diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 8181538..0c37226 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -894,7 +894,7 @@ export class Client< } /** - * Get all matching steps for a job, ordered by created_at ASC, without pagination. + * Get all matching steps for a job, ordered by created_at ASC (ties by id), without pagination. * Search matches step names or output; results omit output. * updatedAfter applies a strict millisecond boundary to every match. * diff --git a/packages/duron/test/time-travel.test.ts b/packages/duron/test/time-travel.test.ts index 5e5e177..ef9ad86 100644 --- a/packages/duron/test/time-travel.test.ts +++ b/packages/duron/test/time-travel.test.ts @@ -30,6 +30,18 @@ import { getPostgresConnection } from './docker.js' // Test Actions for Time Travel // ============================================================================= +/** + * Time travel keeps a completed step only if it was created strictly before the target step + * (by created_at). PGLite's clock has millisecond resolution, so two sequential steps created + * in the same millisecond tie and the earlier one is not "before" the target. Steps that a + * test expects to be kept wait for the next millisecond before returning, so the next step is + * always created in a later millisecond. + */ +async function waitForNextMillisecond() { + const start = Date.now() + while (Date.now() <= start) await Bun.sleep(1) +} + /** * Simple linear action with 3 steps */ @@ -53,12 +65,14 @@ const linearAction = defineAction()({ await ctx.step('step-1', async () => { if (ctx.input['failAtStep'] === 1) throw new Error('Step 1 failed') steps.push('step-1') + await waitForNextMillisecond() return { completed: 'step-1' } }) await ctx.step('step-2', async () => { if (ctx.input['failAtStep'] === 2) throw new Error('Step 2 failed') steps.push('step-2') + await waitForNextMillisecond() return { completed: 'step-2' } }) @@ -98,6 +112,7 @@ const nestedAction = defineAction()({ await stepCtx.step('child-1-1', async () => { if (ctx.input['failAtStep'] === 'child-1-1') throw new Error('child-1-1 failed') executed.push('child-1-1') + await waitForNextMillisecond() return { done: true } }) @@ -108,6 +123,7 @@ const nestedAction = defineAction()({ }) executed.push('parent-1-end') + await waitForNextMillisecond() return { completed: true } }) @@ -225,6 +241,7 @@ const nestedBranchAction = defineAction()({ await branchBCtx.step('child-b-1', async () => { if (ctx.input['failAtStep'] === 'child-b-1') throw new Error('child-b-1 failed') executed.push('child-b-1') + await waitForNextMillisecond() return { done: true } }) await branchBCtx.step('child-b-2', async () => { @@ -465,6 +482,61 @@ function runTests(name: string, factory: AdapterFactory) { expect(child12After?.status).toBe(STEP_STATUS_ACTIVE) // Target - reset expect(parent2After).toBeUndefined() // Deleted (came after parent-1) }) + + it('keeps an earlier sibling created less than a millisecond before the target', async () => { + // On native PostgreSQL, sequential steps can be created in the same millisecond with + // distinct microseconds. Restoring the archived job must keep those microseconds: + // otherwise both siblings tie, and the strict "created before the target" rule deletes + // the completed earlier one. + const jobId = await client.runAction('nestedAction', {}) + await client.fetch({ batchSize: 1 }) + const job = await client.waitForJob(jobId, { timeout: 5000 }) + expect(job?.status).toBe(JOB_STATUS_COMPLETED) + + const { steps } = await client.getJobSteps({ jobId }) + const child12 = steps.find((s) => s.name === 'child-1-2') + expectToBeDefined(child12) + + // Completed jobs are archived; set sub-millisecond creation times there. + await elapsedSql( + adapterInstance.adapter, + sql` + UPDATE duron.job_steps_archive + SET created_at = CASE name + WHEN 'parent-1' THEN '2026-01-01T00:00:00.000000Z'::timestamptz + WHEN 'child-1-1' THEN '2026-01-01T00:00:00.000100Z'::timestamptz + WHEN 'child-1-2' THEN '2026-01-01T00:00:00.000900Z'::timestamptz + WHEN 'parent-2' THEN '2026-01-01T00:00:00.002000Z'::timestamptz + END + WHERE job_id = ${jobId} + `, + ) + + expect(await client.timeTravelJob(jobId, child12!.id)).toBe(true) + + const after = await elapsedSql<{ + name: string + status: string + output: unknown + us: string + }>( + adapterInstance.adapter, + sql` + SELECT name, status, output, to_char(created_at AT TIME ZONE 'UTC', 'SS.US') AS us + FROM duron.job_steps_active WHERE job_id = ${jobId} ORDER BY created_at + `, + ) + expect(after).toEqual([ + { name: 'parent-1', status: STEP_STATUS_ACTIVE, output: null, us: '00.000000' }, + { + name: 'child-1-1', + status: STEP_STATUS_COMPLETED, + output: { done: true }, + us: '00.000100', + }, + { name: 'child-1-2', status: STEP_STATUS_ACTIVE, output: null, us: '00.000900' }, + ]) + }) }) // ========================================================================= @@ -942,40 +1014,29 @@ function runElapsedTests(factory: AdapterFactory) { WHERE id IN (${retainedId}, ${unfinished!.id}) `, ) - const readTimes = ( - source: ReturnType, - afterDateConversion = false, - ) => { - // Archive restoration passes through Date. Compare the shift against that - // millisecond-normalized input, not an unsupported lossless-restoration promise. - const timestamp = (column: string) => - afterDateConversion - ? sql`date_trunc('milliseconds', ${sql.identifier(column)})` - : sql`${sql.identifier(column)}` - return elapsedSql( + // Archive restoration is SQL-native, so both storages keep microseconds. + const readTimes = (source: ReturnType) => + elapsedSql( adapter, sql` - SELECT id, (extract(epoch FROM ${timestamp('started_at')}) * 1000000)::bigint::text AS start, - (extract(epoch FROM ${timestamp('finished_at')}) * 1000000)::bigint::text AS finish, - ${timestamp('created_at')}::text AS created, ${timestamp('expires_at')}::text AS expires, + SELECT id, (extract(epoch FROM started_at) * 1000000)::bigint::text AS start, + (extract(epoch FROM finished_at) * 1000000)::bigint::text AS finish, + created_at::text AS created, expires_at::text AS expires, history_failed_attempts AS history, status, output, (extract(epoch FROM updated_at) * 1000000)::bigint::text AS updated FROM duron.${source} WHERE id IN (${retainedId}, ${unfinished!.id}) ORDER BY id `, ) - } - const before = await readTimes(table, storage === 'archive') + const before = await readTimes(table) expect(before).toHaveLength(2) expect(await adapter.timeTravelJob({ jobId, stepId: targetId })).toBe(true) const after = await readTimes(sql.identifier('job_steps_active')) expect(after).toHaveLength(2) const retained = after.find((step) => step.id === retainedId)! - // Independent literals: one elapsed hour plus the original fractional - // difference (or its Date-normalized value after archive restoration). - expect(BigInt(retained.finish!) - BigInt(retained.start)).toBe( - storage === 'archive' ? 3600531000n : 3600530865n, - ) + // Independent literal: one elapsed hour plus the original fractional difference, + // from active and archive storage alike. + expect(BigInt(retained.finish!) - BigInt(retained.start)).toBe(3600530865n) const [reference] = await elapsedSql<{ time: string; zone: string; pid: number }>( adapter, sql` From 9b997beaedf119a56adb2fd90340b58e41fdb367 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 17:47:49 -0300 Subject: [PATCH 055/100] fix(postgres): archive the job row with SQL so stored values stay exact complete/fail/cancel copied the job row to jobs_archive through JavaScript, cutting timestamps (created_at, started_at, expires_at) to milliseconds and rounding jsonb numbers. Copy it with INSERT ... SELECT in the same transaction, after the unchanged job-row lock. Recover-expired archival was already SQL. --- packages/duron/src/adapters/postgres/base.ts | 71 +++++--- packages/duron/test/archive.test.ts | 168 +++++++++++++++++++ packages/duron/test/cancel-storage.test.ts | 5 +- 3 files changed, 219 insertions(+), 25 deletions(-) diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index ac3b184..f58dde6 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -73,6 +73,16 @@ export type { Job, JobStep } from '../adapter.js' type DrizzleDatabase = PgAsyncDatabase +/** + * A jsonb SQL value, or SQL NULL for `null` and `undefined`. The parameter is typed + * text: postgres.js would JSON-encode a jsonb-typed string again. + */ +function jsonValue(value: unknown): SQL { + return value === null || value === undefined + ? sql`NULL::jsonb` + : sql`${JSON.stringify(value)}::text::jsonb` +} + export interface PruneSchedulerConfig { olderThan: string | Date | number intervalMs: number @@ -560,6 +570,38 @@ export abstract class PostgresBaseAdapter< return result.id } + /** + * Build the statement that copies an active job row into the archive with its + * terminal status. The copy is SQL-native so stored values stay exact: a round + * trip through JavaScript would cut timestamps to milliseconds and round jsonb + * numbers. `finished_at` and `updated_at` become `finishedAt`; `output` and + * `error` are replaced only when given (`null` or `undefined` stores SQL NULL). + * Callers must already hold the job row lock (see _cancelJob). + */ + #archiveJobRow( + jobId: string, + status: typeof JOB_STATUS_COMPLETED | typeof JOB_STATUS_FAILED | typeof JOB_STATUS_CANCELLED, + finishedAt: Date, + replace: { output?: unknown; error?: unknown } = {}, + ): SQL { + const finished = finishedAt.toISOString() + return sql` + INSERT INTO ${this.tables.jobsArchiveTable} ( + id, action_name, group_key, description, status, checksum, input, output, error, + timeout_ms, expires_at, started_at, finished_at, client_id, concurrency_limit, + concurrency_step_limit, created_at, updated_at + ) + SELECT + id, action_name, group_key, description, ${status}, checksum, input, + ${'output' in replace ? jsonValue(replace.output) : sql`output`}, + ${'error' in replace ? jsonValue(replace.error) : sql`error`}, + timeout_ms, expires_at, started_at, ${finished}::timestamptz, client_id, concurrency_limit, + concurrency_step_limit, created_at, ${finished}::timestamptz + FROM ${this.tables.jobsActiveTable} + WHERE id = ${jobId} + ` + } + /** * Internal method to mark a job as completed. * @@ -571,7 +613,7 @@ export abstract class PostgresBaseAdapter< // 1. Lock the job row first (see _cancelJob), with the unchanged guard const [job] = await tx - .select() + .select({ id: this.tables.jobsActiveTable.id }) .from(this.tables.jobsActiveTable) .where( and( @@ -588,13 +630,7 @@ export abstract class PostgresBaseAdapter< } // 2. Insert job into archive FIRST (required for FK constraints) - await tx.insert(this.tables.jobsArchiveTable).values({ - ...job, - status: JOB_STATUS_COMPLETED, - output, - finished_at: finishedAt, - updated_at: finishedAt, - }) + await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_COMPLETED, finishedAt, { output })) // 3. Archive steps using INSERT ... SELECT (SQL-native, no JS round-trip) await tx.execute(sql` @@ -631,7 +667,7 @@ export abstract class PostgresBaseAdapter< // 1. Lock the job row first (see _cancelJob), with the unchanged guard const [job] = await tx - .select() + .select({ id: this.tables.jobsActiveTable.id }) .from(this.tables.jobsActiveTable) .where( and( @@ -647,13 +683,7 @@ export abstract class PostgresBaseAdapter< } // 2. Insert job into archive FIRST (required for FK constraints) - await tx.insert(this.tables.jobsArchiveTable).values({ - ...job, - status: JOB_STATUS_FAILED, - error, - finished_at: finishedAt, - updated_at: finishedAt, - }) + await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_FAILED, finishedAt, { error })) // 3. Archive steps using INSERT ... SELECT await tx.execute(sql` @@ -700,7 +730,7 @@ export abstract class PostgresBaseAdapter< // 1. Lock the job row first, with the unchanged guard const [job] = await tx - .select() + .select({ id: this.tables.jobsActiveTable.id }) .from(this.tables.jobsActiveTable) .where( and( @@ -728,12 +758,7 @@ export abstract class PostgresBaseAdapter< .where(eq(this.tables.jobStepsActiveTable.job_id, jobId)) // 3. Insert job into archive FIRST (required for FK constraints) - await tx.insert(this.tables.jobsArchiveTable).values({ - ...job, - status: JOB_STATUS_CANCELLED, - finished_at: finishedAt, - updated_at: finishedAt, - }) + await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_CANCELLED, finishedAt)) // 4. Archive steps using INSERT ... SELECT await tx.execute(sql` diff --git a/packages/duron/test/archive.test.ts b/packages/duron/test/archive.test.ts index 786e7be..75aa35c 100644 --- a/packages/duron/test/archive.test.ts +++ b/packages/duron/test/archive.test.ts @@ -1,5 +1,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { type SQL, sql } from 'drizzle-orm' + import { JOB_STATUS_ACTIVE, JOB_STATUS_CANCELLED, @@ -11,6 +13,102 @@ import { import { type Adapter, type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' import { expectToBeDefined } from './asserts.js' +// Native SQL fixture seam: public writers cannot set microsecond timestamps or +// jsonb numbers beyond JavaScript precision. +async function rawSql(adapter: Adapter, query: SQL): Promise { + const { db } = adapter as unknown as { + db: { execute: (query: SQL) => Promise } + } + const result = await db.execute(query) + return 'rows' in result ? result.rows : result +} + +const US = 'YYYY-MM-DD HH24:MI:SS.US' + +// Numbers jsonb keeps but a JavaScript round trip rounds. +const preciseInput = '{"n": 12345678901234567890.123456789}' +const preciseOutput = '{"o": 1.000000000000000000001}' +const preciseError = '{"e": 0.1000000000000000000001, "message": "seeded"}' + +type ArchivedRow = { + status: string + created: string + started: string + expires: string + finished: string + updated: string + input: string + output: string | null + error: string | null + client_id: string + active: number +} + +// An active job owned by `clientId` with sub-millisecond timestamps and precise +// jsonb numbers set by SQL. +async function seedActiveJob(adapter: Adapter, clientId: string, expiresAt: string) { + const jobId = await adapter.createJob({ + queue: 'test-action', + groupKey: 'test-group', + input: {}, + timeoutMs: 10000, + checksum: 'abc123', + concurrencyLimit: 10, + concurrencyStepLimit: 10, + }) + expectToBeDefined(jobId) + expect((await adapter.fetch({ batch: 10 })).map((job) => job.id)).toEqual([jobId]) + await rawSql( + adapter, + sql` + UPDATE duron.jobs_active + SET created_at = '2026-01-01T00:00:00.123456Z'::timestamptz, + started_at = '2026-01-01T00:00:01.234567Z'::timestamptz, + expires_at = ${expiresAt}::timestamptz, + updated_at = '2026-01-01T00:00:02.345678Z'::timestamptz, + input = ${preciseInput}::text::jsonb, + output = ${preciseOutput}::text::jsonb, + error = ${preciseError}::text::jsonb, + client_id = ${clientId} + WHERE id = ${jobId} + `, + ) + return jobId +} + +async function archivedRow(adapter: Adapter, jobId: string) { + const [row] = await rawSql( + adapter, + sql` + SELECT status, + to_char(created_at AT TIME ZONE 'UTC', ${US}) AS created, + to_char(started_at AT TIME ZONE 'UTC', ${US}) AS started, + to_char(expires_at AT TIME ZONE 'UTC', ${US}) AS expires, + to_char(finished_at AT TIME ZONE 'UTC', ${US}) AS finished, + to_char(updated_at AT TIME ZONE 'UTC', ${US}) AS updated, + input::text AS input, output::text AS output, error::text AS error, client_id, + (SELECT count(*)::int FROM duron.jobs_active WHERE id = ${jobId}) AS active + FROM duron.jobs_archive WHERE id = ${jobId} + `, + ) + expectToBeDefined(row) + return row +} + +function expectSeededValues(row: ArchivedRow, clientId: string, expires: string) { + expect(row).toMatchObject({ + created: '2026-01-01 00:00:00.123456', + started: '2026-01-01 00:00:01.234567', + expires, + input: preciseInput, + client_id: clientId, + active: 0, + }) + // finished_at and updated_at are both the terminator's finish time. + expect(row.updated).toBe(row.finished) + expect(row.finished > '2026-01-01 00:00:02.345678').toBe(true) +} + function runArchiveTests(adapterFactory: AdapterFactory) { describe(`Archive Tests with ${adapterFactory.name}`, () => { let adapter: Adapter @@ -314,6 +412,76 @@ function runArchiveTests(adapterFactory: AdapterFactory) { expectToBeDefined(job) expect(job.status).toBe(JOB_STATUS_CREATED) }) + + describe('archived job row keeps stored values exactly', () => { + const future = '2999-01-01T00:00:00.654321Z' + const futureText = '2999-01-01 00:00:00.654321' + + it('completeJob', async () => { + const jobId = await seedActiveJob(adapter, 'test-adapter', future) + expect(await adapter.completeJob({ jobId, output: { result: 'done' } })).toBe(true) + + const row = await archivedRow(adapter, jobId) + expectSeededValues(row, 'test-adapter', futureText) + expect(row).toMatchObject({ + status: JOB_STATUS_COMPLETED, + output: '{"result": "done"}', + error: preciseError, + }) + }) + + it('completeJob and failJob with a null value store SQL NULL', async () => { + const jobId = await seedActiveJob(adapter, 'test-adapter', future) + expect(await adapter.completeJob({ jobId, output: null })).toBe(true) + const failedId = await seedActiveJob(adapter, 'test-adapter', future) + expect(await adapter.failJob({ jobId: failedId, error: null })).toBe(true) + + expect(await archivedRow(adapter, jobId)).toMatchObject({ output: null }) + expect(await archivedRow(adapter, failedId)).toMatchObject({ error: null }) + }) + + it('failJob', async () => { + const jobId = await seedActiveJob(adapter, 'test-adapter', future) + expect(await adapter.failJob({ jobId, error: { message: 'boom', name: 'Error' } })).toBe( + true, + ) + + const row = await archivedRow(adapter, jobId) + expectSeededValues(row, 'test-adapter', futureText) + expect(row).toMatchObject({ + status: JOB_STATUS_FAILED, + output: preciseOutput, + error: '{"name": "Error", "message": "boom"}', + }) + }) + + it('cancelJob', async () => { + const jobId = await seedActiveJob(adapter, 'test-adapter', future) + expect(await adapter.cancelJob({ jobId })).toBe(true) + + const row = await archivedRow(adapter, jobId) + expectSeededValues(row, 'test-adapter', futureText) + expect(row).toMatchObject({ + status: JOB_STATUS_CANCELLED, + output: preciseOutput, + error: preciseError, + }) + }) + + it('recoverJobs archives an expired job', async () => { + // Owned by a client without a liveness row, so recovery treats it as dead. + const jobId = await seedActiveJob(adapter, 'dead-client', '2026-01-01T00:00:03.456789Z') + expect(await adapter.recoverJobs({ checksums: ['abc123'] })).toBe(1) + + const row = await archivedRow(adapter, jobId) + expectSeededValues(row, 'dead-client', '2026-01-01 00:00:03.456789') + expect(row).toMatchObject({ + status: JOB_STATUS_FAILED, + output: preciseOutput, + error: '{"message": "Job expired after exceeding timeout"}', + }) + }) + }) }) } diff --git a/packages/duron/test/cancel-storage.test.ts b/packages/duron/test/cancel-storage.test.ts index f20c4bc..7a18cb6 100644 --- a/packages/duron/test/cancel-storage.test.ts +++ b/packages/duron/test/cancel-storage.test.ts @@ -62,10 +62,11 @@ type StatementStarter = 'select' | 'insert' | 'update' | 'delete' | 'execute' type StatementPause = { beforeStatement: number; starter: StatementStarter } // Statement roles inside the built-in terminators; statement 1 is the job-row lock. +// The job-row archive copy is a raw INSERT ... SELECT, so its builder kind is execute. const CANCEL_AFTER_LOCK: StatementPause = { beforeStatement: 2, starter: 'update' } -const CANCEL_AFTER_STEP_UPDATE: StatementPause = { beforeStatement: 3, starter: 'insert' } +const CANCEL_AFTER_STEP_UPDATE: StatementPause = { beforeStatement: 3, starter: 'execute' } const CANCEL_AFTER_STEP_ARCHIVE: StatementPause = { beforeStatement: 5, starter: 'delete' } -const TERMINATE_AFTER_LOCK: StatementPause = { beforeStatement: 2, starter: 'insert' } +const TERMINATE_AFTER_LOCK: StatementPause = { beforeStatement: 2, starter: 'execute' } // Test-only barrier: pauses the adapter's next transaction before the given // statement (checked by its builder kind), or before COMMIT. fail() rejects From ee667b1ec56113d4bba750cd048c654d13b79af9 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 18:06:00 -0300 Subject: [PATCH 056/100] fix(postgres): keep the driver JSON encoding for archived output and error Bind the replacement output/error with the archive column so drizzle applies the driver codec, as the former insert did. PGlite again stores a nested BigInt as a string instead of failing the job, and custom postgres.js json serializers apply. Tests pin the encoding on both engines and compare every copied column. --- packages/duron/src/adapters/postgres/base.ts | 16 +- packages/duron/test/archive.test.ts | 167 +++++++++++++++++-- 2 files changed, 161 insertions(+), 22 deletions(-) diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index f58dde6..bfdf8ec 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -74,13 +74,13 @@ export type { Job, JobStep } from '../adapter.js' type DrizzleDatabase = PgAsyncDatabase /** - * A jsonb SQL value, or SQL NULL for `null` and `undefined`. The parameter is typed - * text: postgres.js would JSON-encode a jsonb-typed string again. + * A jsonb SQL value bound with `column`, so the driver's JSON encoding applies as + * in an insert of that column. `null` and `undefined` give SQL NULL. */ -function jsonValue(value: unknown): SQL { +function jsonParam(value: unknown, column: PgColumn): SQL { return value === null || value === undefined ? sql`NULL::jsonb` - : sql`${JSON.stringify(value)}::text::jsonb` + : sql`${sql.param(value, column)}::jsonb` } export interface PruneSchedulerConfig { @@ -576,6 +576,7 @@ export abstract class PostgresBaseAdapter< * trip through JavaScript would cut timestamps to milliseconds and round jsonb * numbers. `finished_at` and `updated_at` become `finishedAt`; `output` and * `error` are replaced only when given (`null` or `undefined` stores SQL NULL). + * Replacement values keep the driver's JSON encoding (see jsonParam). * Callers must already hold the job row lock (see _cancelJob). */ #archiveJobRow( @@ -585,16 +586,17 @@ export abstract class PostgresBaseAdapter< replace: { output?: unknown; error?: unknown } = {}, ): SQL { const finished = finishedAt.toISOString() + const archive = this.tables.jobsArchiveTable return sql` - INSERT INTO ${this.tables.jobsArchiveTable} ( + INSERT INTO ${archive} ( id, action_name, group_key, description, status, checksum, input, output, error, timeout_ms, expires_at, started_at, finished_at, client_id, concurrency_limit, concurrency_step_limit, created_at, updated_at ) SELECT id, action_name, group_key, description, ${status}, checksum, input, - ${'output' in replace ? jsonValue(replace.output) : sql`output`}, - ${'error' in replace ? jsonValue(replace.error) : sql`error`}, + ${'output' in replace ? jsonParam(replace.output, archive.output) : sql`output`}, + ${'error' in replace ? jsonParam(replace.error, archive.error) : sql`error`}, timeout_ms, expires_at, started_at, ${finished}::timestamptz, client_id, concurrency_limit, concurrency_step_limit, created_at, ${finished}::timestamptz FROM ${this.tables.jobsActiveTable} diff --git a/packages/duron/test/archive.test.ts b/packages/duron/test/archive.test.ts index 75aa35c..dd8b71f 100644 --- a/packages/duron/test/archive.test.ts +++ b/packages/duron/test/archive.test.ts @@ -30,8 +30,15 @@ const preciseInput = '{"n": 12345678901234567890.123456789}' const preciseOutput = '{"o": 1.000000000000000000001}' const preciseError = '{"e": 0.1000000000000000000001, "message": "seeded"}' +// Columns a terminator replaces; every other column must be copied unchanged. +const REPLACED = sql`ARRAY['status', 'output', 'error', 'finished_at', 'updated_at']` + +// The active row's copied columns, captured after seeding. +const keptBefore = new Map() + type ArchivedRow = { - status: string + id: string + kept: string created: string started: string expires: string @@ -48,13 +55,14 @@ type ArchivedRow = { // jsonb numbers set by SQL. async function seedActiveJob(adapter: Adapter, clientId: string, expiresAt: string) { const jobId = await adapter.createJob({ - queue: 'test-action', - groupKey: 'test-group', + queue: 'lossless-action', + groupKey: 'lossless-group', + description: 'lossless description', input: {}, - timeoutMs: 10000, + timeoutMs: 12345, checksum: 'abc123', - concurrencyLimit: 10, - concurrencyStepLimit: 10, + concurrencyLimit: 3, + concurrencyStepLimit: 7, }) expectToBeDefined(jobId) expect((await adapter.fetch({ batch: 10 })).map((job) => job.id)).toEqual([jobId]) @@ -73,6 +81,12 @@ async function seedActiveJob(adapter: Adapter, clientId: string, expiresAt: stri WHERE id = ${jobId} `, ) + const [active] = await rawSql<{ kept: string }>( + adapter, + sql`SELECT (to_jsonb(j) - ${REPLACED})::text AS kept FROM duron.jobs_active j WHERE id = ${jobId}`, + ) + expectToBeDefined(active) + keptBefore.set(jobId, active.kept) return jobId } @@ -80,7 +94,7 @@ async function archivedRow(adapter: Adapter, jobId: string) { const [row] = await rawSql( adapter, sql` - SELECT status, + SELECT id, status, (to_jsonb(j) - ${REPLACED})::text AS kept, to_char(created_at AT TIME ZONE 'UTC', ${US}) AS created, to_char(started_at AT TIME ZONE 'UTC', ${US}) AS started, to_char(expires_at AT TIME ZONE 'UTC', ${US}) AS expires, @@ -88,7 +102,7 @@ async function archivedRow(adapter: Adapter, jobId: string) { to_char(updated_at AT TIME ZONE 'UTC', ${US}) AS updated, input::text AS input, output::text AS output, error::text AS error, client_id, (SELECT count(*)::int FROM duron.jobs_active WHERE id = ${jobId}) AS active - FROM duron.jobs_archive WHERE id = ${jobId} + FROM duron.jobs_archive j WHERE id = ${jobId} `, ) expectToBeDefined(row) @@ -104,11 +118,80 @@ function expectSeededValues(row: ArchivedRow, clientId: string, expires: string) client_id: clientId, active: 0, }) + // Every column the terminator does not replace is copied exactly. + expect(row.kept).toBe(keptBefore.get(row.id)!) + expect(JSON.parse(row.kept)).toMatchObject({ + action_name: 'lossless-action', + group_key: 'lossless-group', + description: 'lossless description', + checksum: 'abc123', + timeout_ms: 12345, + concurrency_limit: 3, + concurrency_step_limit: 7, + }) // finished_at and updated_at are both the terminator's finish time. expect(row.updated).toBe(row.finished) expect(row.finished > '2026-01-01 00:00:02.345678').toBe(true) } +// Values the former insert accepted for output and error, with their stored jsonb text. +const encodingCases: { name: string; value: unknown; stored: string }[] = [ + { name: 'string', value: 'text', stored: '"text"' }, + { name: 'number', value: 42, stored: '42' }, + { name: 'boolean', value: false, stored: 'false' }, + { name: 'array', value: [1, 'a', null], stored: '[1, "a", null]' }, + { + name: 'object with a Date and an undefined field', + value: { d: new Date('2026-01-01T00:00:00.123Z'), u: undefined, n: { x: 1 } }, + stored: '{"d": "2026-01-01T00:00:00.123Z", "n": {"x": 1}}', + }, +] + +async function activeJob(adapter: Adapter, input: unknown = {}) { + const jobId = await adapter.createJob({ + queue: 'test-action', + groupKey: 'test-group', + input, + timeoutMs: 10000, + checksum: 'abc123', + concurrencyLimit: 10, + concurrencyStepLimit: 10, + }) + expectToBeDefined(jobId) + expect((await adapter.fetch({ batch: 10 })).map((job) => job.id)).toEqual([jobId]) + return jobId +} + +async function storedJson(adapter: Adapter, jobId: string) { + const [row] = await rawSql<{ + input: string + output: string | null + error: string | null + active: number + }>( + adapter, + sql` + SELECT input::text AS input, output::text AS output, error::text AS error, + (SELECT count(*)::int FROM duron.jobs_active WHERE id = ${jobId}) AS active + FROM duron.jobs_archive WHERE id = ${jobId} + `, + ) + return row +} + +// Rejects with a BigInt serialization error, possibly wrapped by drizzle as the cause. +async function expectBigIntRejection(promise: Promise) { + const error = await promise.then( + () => { + throw new Error('Expected a rejection') + }, + (reason: unknown) => reason, + ) + const messages: string[] = [] + for (let e: unknown = error; e instanceof Error; e = e.cause) messages.push(e.message) + expect(messages.join(' | ')).toMatch(/BigInt/) +} + function runArchiveTests(adapterFactory: AdapterFactory) { describe(`Archive Tests with ${adapterFactory.name}`, () => { let adapter: Adapter @@ -413,6 +496,58 @@ function runArchiveTests(adapterFactory: AdapterFactory) { expect(job.status).toBe(JOB_STATUS_CREATED) }) + describe('replacement output and error keep the driver JSON encoding', () => { + for (const { name, value, stored } of encodingCases) { + it(`${name}`, async () => { + const completedId = await activeJob(adapter) + expect(await adapter.completeJob({ jobId: completedId, output: value })).toBe(true) + const failedId = await activeJob(adapter) + expect(await adapter.failJob({ jobId: failedId, error: value })).toBe(true) + + expect(await storedJson(adapter, completedId)).toMatchObject({ + output: stored, + active: 0, + }) + expect(await storedJson(adapter, failedId)).toMatchObject({ error: stored, active: 0 }) + }) + } + + if (adapterFactory.name === 'pglite') { + it('nested BigInt is stored as a string (PGlite serializer)', async () => { + const completedId = await activeJob(adapter, { big: 10n }) + expect( + await adapter.completeJob({ jobId: completedId, output: { n: { big: 10n } } }), + ).toBe(true) + const failedId = await activeJob(adapter) + expect( + await adapter.failJob({ jobId: failedId, error: { message: 'boom', code: 10n } }), + ).toBe(true) + + expect(await storedJson(adapter, completedId)).toMatchObject({ + input: '{"big": "10"}', + output: '{"n": {"big": "10"}}', + active: 0, + }) + expect(await storedJson(adapter, failedId)).toMatchObject({ + error: '{"code": "10", "message": "boom"}', + active: 0, + }) + const job = await adapter.getJobById(completedId) + expect(job?.output).toEqual({ n: { big: '10' } }) + }) + } else { + it('nested BigInt is rejected and the job stays active (postgres.js serializer)', async () => { + await expectBigIntRejection(activeJob(adapter, { big: 10n })) + const jobId = await activeJob(adapter) + await expectBigIntRejection(adapter.completeJob({ jobId, output: { n: { big: 10n } } })) + await expectBigIntRejection( + adapter.failJob({ jobId, error: { message: 'boom', code: 10n } }), + ) + expect((await adapter.getJobById(jobId))?.status).toBe(JOB_STATUS_ACTIVE) + }) + } + }) + describe('archived job row keeps stored values exactly', () => { const future = '2999-01-01T00:00:00.654321Z' const futureText = '2999-01-01 00:00:00.654321' @@ -430,14 +565,16 @@ function runArchiveTests(adapterFactory: AdapterFactory) { }) }) - it('completeJob and failJob with a null value store SQL NULL', async () => { - const jobId = await seedActiveJob(adapter, 'test-adapter', future) - expect(await adapter.completeJob({ jobId, output: null })).toBe(true) - const failedId = await seedActiveJob(adapter, 'test-adapter', future) - expect(await adapter.failJob({ jobId: failedId, error: null })).toBe(true) + it('completeJob and failJob with a null or undefined value store SQL NULL', async () => { + for (const value of [null, undefined]) { + const jobId = await seedActiveJob(adapter, 'test-adapter', future) + expect(await adapter.completeJob({ jobId, output: value })).toBe(true) + const failedId = await seedActiveJob(adapter, 'test-adapter', future) + expect(await adapter.failJob({ jobId: failedId, error: value })).toBe(true) - expect(await archivedRow(adapter, jobId)).toMatchObject({ output: null }) - expect(await archivedRow(adapter, failedId)).toMatchObject({ error: null }) + expect(await archivedRow(adapter, jobId)).toMatchObject({ output: null }) + expect(await archivedRow(adapter, failedId)).toMatchObject({ error: null }) + } }) it('failJob', async () => { From a9352ccf9167099a81b5949d9de112ec938fcd57 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 18:46:37 -0300 Subject: [PATCH 057/100] fix(docs): show the not-found page for unknown paths Unknown paths get the SPA shell from the host. A path no route matches threw React #418 on hydration, and an unknown docs page failed parsing the HTML fallback as the page's static loader data. - Check the slug against a prerendered page list before loading a docs page. - Render not-found pages client-only inside the shell's Suspense boundaries (TanStack/router#8473 workaround, as for the home page). - Center the not-found content without moving the navbar. --- packages/docs/src/components/not-found.tsx | 45 +++++++++++++++++----- packages/docs/src/routes/__root.tsx | 2 + packages/docs/src/routes/docs/$.tsx | 26 +++++++++++++ 3 files changed, 64 insertions(+), 9 deletions(-) diff --git a/packages/docs/src/components/not-found.tsx b/packages/docs/src/components/not-found.tsx index 932e4d0..5b3a31a 100644 --- a/packages/docs/src/components/not-found.tsx +++ b/packages/docs/src/components/not-found.tsx @@ -1,17 +1,44 @@ -import { Link } from '@tanstack/react-router' +import { ClientOnly, Link } from '@tanstack/react-router' import { HomeLayout } from 'fumadocs-ui/layouts/home' +import { Suspense } from 'react' -import { Logo } from '@/components/logo' +import { baseOptions } from '@/lib/layout.shared' +// Workaround for https://github.com/TanStack/router/issues/8473, as in routes/index.tsx. The +// host serves the SPA shell (index.html, the prerendered '/' page) for unknown paths, so a +// not-found page hydrates against the shell's empty route area. `ClientOnly` renders nothing +// until hydration, the same as the shell. + +/** Not-found page of a matched route (unknown docs page). Its route wraps it in Suspense. */ export function NotFound() { return ( - , - }} - className="text-center py-32 justify-center" - > -
    + + + + ) +} + +/** + * Not-found page for a path no route matches. The router renders it in place of the root + * outlet, without the two Suspense boundaries the shell has there (the outlet's and the '/' + * route's), so add them. + */ +export function GlobalNotFound() { + return ( + + + + + + ) +} + +function NotFoundPage() { + return ( + + {/* fumadocs-ui 16.x: HomeLayout's root contains the navbar, so center the content in a + flex-1 wrapper (as on the home page) instead of styling the layout itself. */} +

    404

    Page Not Found

    diff --git a/packages/docs/src/routes/__root.tsx b/packages/docs/src/routes/__root.tsx index a880bd3..2265f56 100644 --- a/packages/docs/src/routes/__root.tsx +++ b/packages/docs/src/routes/__root.tsx @@ -3,6 +3,7 @@ import { createRootRoute, HeadContent, Outlet, Scripts } from '@tanstack/react-r import { RootProvider } from 'fumadocs-ui/provider/tanstack' import type * as React from 'react' +import { GlobalNotFound } from '@/components/not-found' import SearchDialog from '@/components/search' import appCss from '@/styles/app.css?url' @@ -26,6 +27,7 @@ export const Route = createRootRoute({ ], }), component: RootComponent, + notFoundComponent: GlobalNotFound, }) function RootComponent() { diff --git a/packages/docs/src/routes/docs/$.tsx b/packages/docs/src/routes/docs/$.tsx index 88edaec..f655433 100644 --- a/packages/docs/src/routes/docs/$.tsx +++ b/packages/docs/src/routes/docs/$.tsx @@ -12,15 +12,41 @@ import { baseOptions } from '@/lib/layout.shared' import { source } from '@/lib/source' export const Route = createFileRoute('/docs/$')({ + // An unknown page is served the SPA shell, whose route area is an empty Suspense boundary + // (see routes/index.tsx). This boundary matches it while the loader runs during hydration. + wrapInSuspense: true, component: Page, loader: async ({ params }) => { const slugs = params._splat?.split('/') ?? [] + // In the static build, the loader server function reads data prerendered per page. An + // unknown page has none, and the host's SPA fallback would return HTML instead of JSON, + // so check the page list first. + if (!(await knownPagePaths()).has(slugs.join('/'))) throw notFound() const data = await loader({ data: slugs }) await clientLoader.preload(data.path) return data }, }) +const getPagePaths = createServerFn({ + method: 'GET', +}) + .middleware([staticFunctionMiddleware]) + .handler(async () => source.getPages().map((page) => page.slugs.join('/'))) + +let pagePaths: Promise> | undefined + +function knownPagePaths() { + pagePaths ??= getPagePaths().then( + (paths) => new Set(paths), + (error: unknown) => { + pagePaths = undefined + throw error + }, + ) + return pagePaths +} + const loader = createServerFn({ method: 'GET', }) From 528cfb46cfbefdd9c3b3ba5fa60bc9104704b84e Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 19:55:59 -0300 Subject: [PATCH 058/100] chore: test on PostgreSQL 19 and PGlite 0.6 - PGlite devDependency 0.6.1 (PostgreSQL 19); peer range ^0.5.17 || ^0.6.0, since PGlite 0.6 cannot open a data directory created by 0.5. - Native tests default to postgres:19-alpine, overridable with DURON_TEST_POSTGRES_IMAGE. The container name includes the image, an existing container must run the selected image, and a taken port 5440 is reported instead of silently reaching another server. getPostgresConnection() takes no arguments. - Dev docker-compose uses postgres:19-alpine. - Docs: tested with PostgreSQL 16 and 19 and PGlite 0.6.1. --- AGENTS.md | 8 +- README.md | 2 +- bun.lock | 6 +- docker-compose.yml | 2 +- .../docs/content/docs/getting-started.mdx | 12 +- packages/duron/README.md | 2 +- packages/duron/package.json | 4 +- packages/duron/test/adapters.ts | 5 +- packages/duron/test/cancel-storage.test.ts | 5 +- packages/duron/test/claim-isolation.test.ts | 5 +- packages/duron/test/docker.ts | 123 +++++++++++++++--- packages/duron/test/prune-bootstrap.test.ts | 15 +-- packages/duron/test/prune-loss.test.ts | 5 +- packages/duron/test/prune-ownership.test.ts | 50 ++----- packages/duron/test/prune-relay.ts | 4 +- packages/duron/test/prune-replies.test.ts | 5 +- packages/duron/test/prune-scheduler.test.ts | 15 +-- packages/duron/test/prune-scope.test.ts | 9 +- packages/duron/test/prune-transport.test.ts | 5 +- packages/duron/test/recover-own-jobs.test.ts | 5 +- packages/duron/test/recover-snapshot.test.ts | 10 +- packages/duron/test/setup.ts | 16 ++- packages/duron/test/time-travel.test.ts | 5 +- packages/duron/test/wait-context.test.ts | 5 +- packages/duron/test/wait-native.test.ts | 15 +-- packages/duron/test/wait-pool.test.ts | 5 +- packages/duron/test/wait-transport.test.ts | 5 +- 27 files changed, 174 insertions(+), 174 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1726455..b4efe30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,7 @@ bun run build:docs # docs only ## Database -- PostgreSQL for dev: `docker-compose up -d` → `postgres://duron:duron@localhost:5435/duron` +- PostgreSQL 19 for dev: `docker-compose up -d` → `postgres://duron:duron@localhost:5435/duron`. A container created with the earlier PostgreSQL 16 image is recreated empty; its data stays in the old anonymous volume. - PGLite for tests/development. - Generate migrations: ```bash @@ -62,7 +62,11 @@ bun run build:docs # docs only - Tests live in `packages/duron/test/*.test.ts` - Run single file: `bun test specific.test.ts` - Core tests run with `--concurrent` via `bun test` in `packages/duron/package.json` -- Test setup (`test/setup.ts`) auto-creates a Docker container `duron-postgres-test` on port 5440 for PostgreSQL tests. Docker must be running. +- `test/docker.ts` auto-creates a Docker container on port 5440 for PostgreSQL tests. Docker must be running. + - Image: `DURON_TEST_POSTGRES_IMAGE` (default `postgres:19-alpine`). The suite is also verified on `postgres:16-alpine`. + - Container: `duron-postgres-test-` (for example `duron-postgres-test-postgres-19-alpine`), so a changed image never reuses a container of another version. `DURON_TEST_POSTGRES_CONTAINER` overrides the name; an existing container must run the selected image. + - Only one test container can publish port 5440: stop the other one before switching images. + - Native-only tests run with `POSTGRES_TEST=true`. ## Lint / Format (Oxlint/Oxfmt) diff --git a/README.md b/README.md index 21c9c32..60a7c46 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ pnpm add duron postgres drizzle-orm@rc yarn add duron postgres drizzle-orm@rc ``` -Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0, on PostgreSQL 16 and 19, and with PGlite 0.6.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. ### Creating an Action with Context diff --git a/bun.lock b/bun.lock index c2fd2f8..42ddbb5 100644 --- a/bun.lock +++ b/bun.lock @@ -57,7 +57,7 @@ "zod": "^4.6.7", }, "devDependencies": { - "@electric-sql/pglite": "^0.5.17", + "@electric-sql/pglite": "^0.6.1", "@types/bun": "latest", "@types/node": "^26.6.11", "drizzle-kit": "1.0.0-rc.6", @@ -67,7 +67,7 @@ "typescript": "^7", }, "peerDependencies": { - "@electric-sql/pglite": "^0.5.17", + "@electric-sql/pglite": "^0.5.17 || ^0.6.0", "drizzle-orm": "1.0.0-rc.6 || ^1.0.0", "postgres": "^4.1.1", }, @@ -208,7 +208,7 @@ "@dnd-kit/utilities": ["@dnd-kit/utilities@3.2.2", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="], - "@electric-sql/pglite": ["@electric-sql/pglite@0.5.17", "", {}, "sha512-8SvKjiUjaU+0O0dbxjOfN+jXz14TEqDWbwDkYOW1aQ11y/ph2JvFVI27ABBo5nfw+ZfSqy4hKCNlbnbB1TDE+g=="], + "@electric-sql/pglite": ["@electric-sql/pglite@0.6.1", "", {}, "sha512-vdKk6mgzw8uqouCyPa20eNhPafF1OI5LXTvdWBj2plJhDHT2j5ohDdVdZUClJrWwU5MZZB018z68qZec/JmjRw=="], "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], diff --git a/docker-compose.yml b/docker-compose.yml index 3c5fdb9..7165935 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,6 @@ services: postgres: - image: postgres:16-alpine + image: postgres:19-alpine container_name: duron-postgres environment: POSTGRES_USER: duron diff --git a/packages/docs/content/docs/getting-started.mdx b/packages/docs/content/docs/getting-started.mdx index a9d2c74..5266605 100644 --- a/packages/docs/content/docs/getting-started.mdx +++ b/packages/docs/content/docs/getting-started.mdx @@ -26,6 +26,8 @@ bun add duron drizzle-orm@rc Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with PostgreSQL 16 and 19. + Install postgres for the current database: ```bash @@ -46,19 +48,19 @@ Install pglite for the current database: ```bash # Using npm -npm install @electric-sql/pglite@0.5 +npm install @electric-sql/pglite@0.6 # Using pnpm -pnpm add @electric-sql/pglite@0.5 +pnpm add @electric-sql/pglite@0.6 # Using yarn -yarn add @electric-sql/pglite@0.5 +yarn add @electric-sql/pglite@0.6 # Using bun -bun add @electric-sql/pglite@0.5 +bun add @electric-sql/pglite@0.6 ``` -Duron is tested with PGlite 0.5.17 (PostgreSQL 18). PGlite 0.6 runs PostgreSQL 19 and is not tested yet. +Duron is tested with PGlite 0.6.1 (PostgreSQL 19). PGlite 0.5.17 or later 0.5.x (PostgreSQL 18) is also supported. A persistent PGlite data directory only opens with the PostgreSQL major version that created it: PGlite 0.6 cannot open a directory created by PGlite 0.5, so keep 0.5 for an existing directory or dump and restore its data. ## Schema Library diff --git a/packages/duron/README.md b/packages/duron/README.md index c5ae57c..609aff4 100644 --- a/packages/duron/README.md +++ b/packages/duron/README.md @@ -18,7 +18,7 @@ pnpm add duron postgres drizzle-orm@rc yarn add duron postgres drizzle-orm@rc ``` -Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0, on PostgreSQL 16 and 19, and with PGlite 0.6.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. ## Quick Start diff --git a/packages/duron/package.json b/packages/duron/package.json index ca06fd2..84ecaef 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -95,7 +95,7 @@ "zod": "^4.6.7" }, "devDependencies": { - "@electric-sql/pglite": "^0.5.17", + "@electric-sql/pglite": "^0.6.1", "@types/bun": "latest", "@types/node": "^26.6.11", "drizzle-kit": "1.0.0-rc.6", @@ -105,7 +105,7 @@ "typescript": "^7" }, "peerDependencies": { - "@electric-sql/pglite": "^0.5.17", + "@electric-sql/pglite": "^0.5.17 || ^0.6.0", "drizzle-orm": "1.0.0-rc.6 || ^1.0.0", "postgres": "^4.1.1" }, diff --git a/packages/duron/test/adapters.ts b/packages/duron/test/adapters.ts index ae4bef9..3a2305b 100644 --- a/packages/duron/test/adapters.ts +++ b/packages/duron/test/adapters.ts @@ -20,10 +20,7 @@ export interface AdapterFactory { export const postgresFactory: AdapterFactory = { name: 'postgres', create: async (options: any = {}) => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() return { adapter: new PostgresAdapter({ diff --git a/packages/duron/test/cancel-storage.test.ts b/packages/duron/test/cancel-storage.test.ts index 7a18cb6..a564a73 100644 --- a/packages/duron/test/cancel-storage.test.ts +++ b/packages/duron/test/cancel-storage.test.ts @@ -159,10 +159,7 @@ function pauseBeforeStatement( type StepRow = { id: string; status: string } async function cancelDatabase() { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const url = new URL(CONNECTION_URL) const name = url.pathname.slice(1) const session = (applicationName: string, max = 1) => diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 2670599..b77f60b 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -78,10 +78,7 @@ function observe(promise: Promise): Promise> { } async function claimDatabase() { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const url = new URL(CONNECTION_URL) const options = (applicationName: string, max?: number, relayPort?: number) => ({ ...(max ? { max } : {}), diff --git a/packages/duron/test/docker.ts b/packages/duron/test/docker.ts index 6335ccb..3d53b2e 100644 --- a/packages/duron/test/docker.ts +++ b/packages/duron/test/docker.ts @@ -5,9 +5,29 @@ import { promisify } from 'node:util' import pRetry from 'p-retry' const execFile = promisify(baseExecFile) + +/** PostgreSQL image for native tests. Override with `DURON_TEST_POSTGRES_IMAGE`. */ +export const TEST_POSTGRES_IMAGE = process.env['DURON_TEST_POSTGRES_IMAGE'] || 'postgres:19-alpine' + +/** + * Container for native tests. The default name includes the image, so a changed image starts a + * new container instead of reusing one that runs another server version. Override with + * `DURON_TEST_POSTGRES_CONTAINER` (for example to reuse an existing container); an existing + * container must still run `TEST_POSTGRES_IMAGE` (see `createContainer`). + */ +export const TEST_POSTGRES_CONTAINER = + process.env['DURON_TEST_POSTGRES_CONTAINER'] || + `duron-postgres-test-${TEST_POSTGRES_IMAGE.replace(/[^a-zA-Z0-9_.-]/g, '-')}` + +/** Host port of the native test container. */ +export const TEST_POSTGRES_PORT = 5440 + const containersCreated = new Map>() const containersStarted = new Map>() +/** A container precondition failed; its message is shown as is. */ +class ContainerError extends Error {} + interface CreateContainerOptions { image: string containerName: string @@ -37,6 +57,28 @@ export async function ensureImageExists(image: string) { } } +/** Running containers other than `containerName` that publish `port`. */ +async function portHolders(containerName: string, port: number) { + const { stdout } = await execFile('docker', [ + 'ps', + '--filter', + `publish=${port}`, + '--format', + '{{.Names}} ({{.Image}})', + ]).catch(() => ({ stdout: '' })) + return stdout + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith(`${containerName} `)) +} + +function portInUse(containerName: string, image: string, port: number, holders: string[]) { + return ( + `container "${containerName}" (${image}) cannot publish port ${port}: it is used by ` + + `${holders.join(', ') || 'another process'}. Stop that to run the native tests with ${image}.` + ) +} + export async function createContainer({ image, containerName, @@ -48,10 +90,19 @@ export async function createContainer({ } const promise = (async () => { + // Set when this call started the container, so a failed start can stop it again. + let started = true try { // Ensure the image exists before running await ensureImageExists(image) + // Docker publishes no port for a container whose start failed on a taken port, even + // after the port is free, so check for another test container first. + const holders = await portHolders(containerName, ports[0]) + if (holders.length > 0) { + throw new ContainerError(portInUse(containerName, image, ports[0], holders)) + } + await execFile('docker', [ 'run', '--name', @@ -61,21 +112,59 @@ export async function createContainer({ `${ports[0]}:${ports[1]}`, '-d', image, - ]).catch((error) => { - const err = error as Error - if (err.message.includes('is already in use by container')) { - return execFile('docker', ['start', containerName]) + ]).catch(async (error: Error) => { + if (error.message.includes('port is already allocated')) { + // The created container would never publish the port, even once it is free. + await execFile('docker', ['rm', '-f', '-v', containerName]).catch(() => undefined) + throw new ContainerError( + portInUse(containerName, image, ports[0], await portHolders(containerName, ports[0])), + ) + } + if (!error.message.includes('is already in use by container')) throw error + // Reuse the existing container only if it runs the requested image: another image + // would silently test another server version. + const { stdout } = await execFile('docker', [ + 'inspect', + '--format', + '{{.Config.Image}} {{.State.Running}}', + containerName, + ]) + const [existingImage, running] = stdout.trim().split(' ') + if (existingImage !== image) { + throw new ContainerError( + `container "${containerName}" runs image ${existingImage}, not ${image}. Remove it, ` + + 'or set DURON_TEST_POSTGRES_IMAGE / DURON_TEST_POSTGRES_CONTAINER to match it.', + ) + } + started = running !== 'true' + if (started) { + await execFile('docker', ['start', containerName]).catch((startError: Error) => { + if (!startError.message.includes('port is already allocated')) throw startError + }) } - - throw error }) + + // A container that could not bind its host port can still run without it; the tests + // would then reach whatever else serves that port. + const { stdout: published } = await execFile('docker', [ + 'port', + containerName, + `${ports[1]}/tcp`, + ]).catch(() => ({ stdout: '' })) + if (!published.split('\n').some((line) => line.trim().endsWith(`:${ports[0]}`))) { + if (started) await execFile('docker', ['stop', containerName]).catch(() => undefined) + throw new ContainerError( + `${portInUse(containerName, image, ports[0], await portHolders(containerName, ports[0]))} ` + + `If the port is free, the container was started while it was taken: remove it ` + + `(docker rm -f -v ${containerName}).`, + ) + } } catch (error) { + if (error instanceof ContainerError) throw new Error(`❌ ${error.message}`, { cause: error }) const err = error as Error - if (!err.message.includes('Conflict.')) { - throw new Error(`❌ Failed to start container "${containerName}": ${err.message}`, { - cause: error, - }) - } + throw new Error(`❌ Failed to start container "${containerName}": ${err.message}`, { + cause: error, + }) } })() @@ -113,15 +202,11 @@ export async function waitForContainer(containerName: string, expectedMessage: s return promise } -export const getPostgresConnection = async ({ - containerName, - port, -}: { - containerName: string - port: number -}) => { +export const getPostgresConnection = async () => { + const containerName = TEST_POSTGRES_CONTAINER + const port = TEST_POSTGRES_PORT await createContainer({ - image: 'postgres:16-alpine', + image: TEST_POSTGRES_IMAGE, containerName, ports: [port, 5432], environment: { diff --git a/packages/duron/test/prune-bootstrap.test.ts b/packages/duron/test/prune-bootstrap.test.ts index e9ad981..d6dfa99 100644 --- a/packages/duron/test/prune-bootstrap.test.ts +++ b/packages/duron/test/prune-bootstrap.test.ts @@ -35,10 +35,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { it(`bootstrap ${mode} retains one ready reservation or stops without new work`, async () => { const late = mode === 'stop beyond drain' const retry = mode === 'permitted retry' || mode === 'stop during retry' - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const relay = new PruneRelay() relay.hold = (tag, connection) => tag === 'Z' && connection.ready === 1 let reserves = 0 @@ -149,10 +146,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 30_000) } it('bootstrap startup stalled past the driver end timeout still settles the owned close', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const relay = new PruneRelay() // Startup never reaches ready and the held reply is never released. relay.hold = (tag, connection) => tag === 'Z' && connection.ready === 1 @@ -247,10 +241,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { 'close acknowledgment', ] as const) { it(`bootstrap ${failure} failure leaves no later lock backend before relay teardown`, async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const relay = new PruneRelay() relay.hold = (tag, connection) => (failure === 'initial readiness' || failure === 'close acknowledgment') && diff --git a/packages/duron/test/prune-loss.test.ts b/packages/duron/test/prune-loss.test.ts index f68a294..c747ac3 100644 --- a/packages/duron/test/prune-loss.test.ts +++ b/packages/duron/test/prune-loss.test.ts @@ -23,10 +23,7 @@ async function eventually(check: () => Promise, timeout = 7_000): Promise< if (process.env['POSTGRES_TEST'] === 'true') { it('lock loss permits another owner while issued DELETE commits, but blocks its next batch', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const beginPrune = Promise.withResolvers() const unlockTable = Promise.withResolvers() const tableLocked = Promise.withResolvers() diff --git a/packages/duron/test/prune-ownership.test.ts b/packages/duron/test/prune-ownership.test.ts index b89df5e..683aa88 100644 --- a/packages/duron/test/prune-ownership.test.ts +++ b/packages/duron/test/prune-ownership.test.ts @@ -42,10 +42,7 @@ class InstrumentedPrune extends PostgresAdapter { if (process.env['POSTGRES_TEST'] === 'true') { it('retains an early close rejection when stop precedes held-hook settlement', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const finishHook = Promise.withResolvers() const closeFailure = new Error('injected end rejection after native closure before stop') const reports: unknown[] = [] @@ -122,10 +119,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { } }, 20_000) it('failed public startup closes its allocated lock backend along with query and listener resources', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const allocated = Promise.withResolvers() const failure = new Error('injected startup failure after native reservation') let pid = 0 @@ -179,10 +173,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { } }, 20_000) it('retains one backend and reservation across false and successful passes without stacking', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const permitNext = Promise.withResolvers() const acquisitions: { pid: number; acquired: boolean }[] = [] const unlocks: { pid: number; released: boolean }[] = [] @@ -289,10 +280,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 20_000) it('loss during a stop-held ready reservation never returns it and reports cleanup independently', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const continueReserve = Promise.withResolvers() let pid = 0 let returns = 0 @@ -369,10 +357,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 20_000) it('uncertain reserved identity never returns the native reservation as safe', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const reports: unknown[] = [] let reserveCalls = 0 let returnCalls = 0 @@ -446,10 +431,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 20_000) it('stop joins the pending fault close without resetting its deadline or skipping other resources', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const allowEnd = Promise.withResolvers() let endStarted = 0 let endCalls = 0 @@ -541,10 +523,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 25_000) it('pending return acknowledgment cannot consume the independent owned-close opportunity', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const acknowledge = Promise.withResolvers() let returnCalls = 0 let closeCalls = 0 @@ -602,10 +581,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 20_000) it('physical lock-client closure discharges a rejected end reply without repeating it', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const failure = new Error('injected after-physical-close reply failure') let closeCalls = 0 const adapter = new InstrumentedPrune({ @@ -645,10 +621,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 20_000) it('retries a known before-close fault without repeating an uncertain return or replacing its error', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const returnFailure = new Error('injected before-native-return failure') const closeFailure = new Error('injected before-close-method failure') let returns = 0 @@ -724,10 +697,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 25_000) it('a return reply failure still closes all native resources and a later stop uses release evidence', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const failure = new Error('injected after-return reply failure') let returnCalls = 0 let closeCalls = 0 diff --git a/packages/duron/test/prune-relay.ts b/packages/duron/test/prune-relay.ts index 17f0a7c..f1e9531 100644 --- a/packages/duron/test/prune-relay.ts +++ b/packages/duron/test/prune-relay.ts @@ -1,5 +1,7 @@ import type { Socket } from 'bun' +import { TEST_POSTGRES_PORT } from './docker.js' + /** Diagnostic TCP relay only. Never used by production or as adapter transport. */ export type RelayConnection = { number: number @@ -39,7 +41,7 @@ export class PruneRelay { this.connections.push(connection) const work = Bun.connect({ hostname: '127.0.0.1', - port: 5440, + port: TEST_POSTGRES_PORT, data: connection, socket: { open: (up) => { diff --git a/packages/duron/test/prune-replies.test.ts b/packages/duron/test/prune-replies.test.ts index 8a18554..2cbb574 100644 --- a/packages/duron/test/prune-replies.test.ts +++ b/packages/duron/test/prune-replies.test.ts @@ -27,10 +27,7 @@ async function eventually(check: () => Promise): Promise { if (process.env['POSTGRES_TEST'] === 'true') { for (const phase of ['acquired', 'released'] as const) { it(`malformed ${phase} reply closes the real PostgreSQL session without returning it as reusable`, async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const observer = postgres(CONNECTION_URL, { max: 1 }) const reports: unknown[] = [] let installed = false diff --git a/packages/duron/test/prune-scheduler.test.ts b/packages/duron/test/prune-scheduler.test.ts index 9bd5030..d7af11b 100644 --- a/packages/duron/test/prune-scheduler.test.ts +++ b/packages/duron/test/prune-scheduler.test.ts @@ -25,10 +25,7 @@ async function eventually(check: () => Promise, timeout = 2_000): Promise< if (process.env['POSTGRES_TEST'] === 'true') { it('scheduled PostgreSQL ownership leaves the original max-one query pool available', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const release = Promise.withResolvers() class HeldPostgresPrune extends PostgresAdapter { queryPid = 0 @@ -84,10 +81,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 20_000) it('a real false unlock retires and closes only the isolated lock resource', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const reports: unknown[] = [] class FalseUnlockPrune extends PostgresAdapter { calls = 0 @@ -145,10 +139,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 20_000) it('observed owned lock-session loss blocks a held hook continuation but not direct work', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const release = Promise.withResolvers() let entered = false let settled = false diff --git a/packages/duron/test/prune-scope.test.ts b/packages/duron/test/prune-scope.test.ts index 7c15f99..e7e20e8 100644 --- a/packages/duron/test/prune-scope.test.ts +++ b/packages/duron/test/prune-scope.test.ts @@ -38,8 +38,8 @@ class ScopePrune extends PostgresAdapter { if (process.env['POSTGRES_TEST'] === 'true') { it('configured schemas contend database-wide, another database proceeds, and direct prune stays outside coordination', async () => { - const first = await getPostgresConnection({ containerName: 'duron-postgres-test', port: 5440 }) - const other = await getPostgresConnection({ containerName: 'duron-postgres-test', port: 5440 }) + const first = await getPostgresConnection() + const other = await getPostgresConnection() const release = Promise.withResolvers() const pruneArchive = { olderThan: new Date('2099-01-01'), intervalMs: 30 } const owner = new ScopePrune({ connection: first.CONNECTION_URL, pruneArchive }) @@ -123,10 +123,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { }, 25_000) it('without retention the public adapter allocates no lock client and direct pruning still works', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const adapter = new ScopePrune({ connection: CONNECTION_URL }) adapter.setId('opt-out') const observer = postgres(CONNECTION_URL, { max: 1 }) diff --git a/packages/duron/test/prune-transport.test.ts b/packages/duron/test/prune-transport.test.ts index df1b0d7..ad4b40e 100644 --- a/packages/duron/test/prune-transport.test.ts +++ b/packages/duron/test/prune-transport.test.ts @@ -33,10 +33,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { 'unlock reply after prune error', ] as const) { it(`post-boundary ${phase} loss never reconnects or returns the reservation`, async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const relay = new PruneRelay() const pruneFailure = new Error('injected original prune failure before lost unlock reply') const reports: unknown[] = [] diff --git a/packages/duron/test/recover-own-jobs.test.ts b/packages/duron/test/recover-own-jobs.test.ts index 314c1b6..6b45fa2 100644 --- a/packages/duron/test/recover-own-jobs.test.ts +++ b/packages/duron/test/recover-own-jobs.test.ts @@ -44,10 +44,7 @@ const pglite: Engine = { const postgres: Engine = { name: 'postgres', store: async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() return { open: () => new PostgresAdapter({ connection: CONNECTION_URL, migrateOnStart: true }), cleanup: deleteDb, diff --git a/packages/duron/test/recover-snapshot.test.ts b/packages/duron/test/recover-snapshot.test.ts index 9b09fc6..5d8eec6 100644 --- a/packages/duron/test/recover-snapshot.test.ts +++ b/packages/duron/test/recover-snapshot.test.ts @@ -206,10 +206,7 @@ function errorMessages(error: unknown): string { type StepRow = { id: string; status: string } async function recoveryDatabase() { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const url = new URL(CONNECTION_URL) const name = url.pathname.slice(1) const session = (applicationName: string) => @@ -1059,10 +1056,7 @@ const engines: AdapterFactory[] = [ { name: 'postgres' as const, create: async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() return { adapter: new PostgresAdapter({ connection: CONNECTION_URL }), deleteDb, diff --git a/packages/duron/test/setup.ts b/packages/duron/test/setup.ts index 4685d2c..f371cc1 100644 --- a/packages/duron/test/setup.ts +++ b/packages/duron/test/setup.ts @@ -1,12 +1,18 @@ /** oxlint-disable no-console */ -import { createContainer, waitForContainer } from './docker.js' +import { + TEST_POSTGRES_CONTAINER, + TEST_POSTGRES_IMAGE, + TEST_POSTGRES_PORT, + createContainer, + waitForContainer, +} from './docker.js' console.log('🔄 Creating postgres container...') await createContainer({ - image: 'postgres:16-alpine', - containerName: 'duron-postgres-test', - ports: [5440, 5432], + image: TEST_POSTGRES_IMAGE, + containerName: TEST_POSTGRES_CONTAINER, + ports: [TEST_POSTGRES_PORT, 5432], environment: { POSTGRES_USER: 'duron', POSTGRES_PASSWORD: 'duron', @@ -16,6 +22,6 @@ await createContainer({ console.log('✅ Postgres container created') -await waitForContainer('duron-postgres-test', 'PostgreSQL init process complete') +await waitForContainer(TEST_POSTGRES_CONTAINER, 'PostgreSQL init process complete') console.log('✅ Postgres container started') diff --git a/packages/duron/test/time-travel.test.ts b/packages/duron/test/time-travel.test.ts index ef9ad86..f10435c 100644 --- a/packages/duron/test/time-travel.test.ts +++ b/packages/duron/test/time-travel.test.ts @@ -887,10 +887,7 @@ function runIsolationTests(factory: AdapterFactory) { // provisioning and normal database deletion use the existing factory helper. async function createElapsedFixture(factory: AdapterFactory): Promise { if (factory.name === 'pglite') return factory.create() - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const connection = new URL(CONNECTION_URL) return { adapter: new PostgresAdapter({ diff --git a/packages/duron/test/wait-context.test.ts b/packages/duron/test/wait-context.test.ts index 59a7035..b08c7a0 100644 --- a/packages/duron/test/wait-context.test.ts +++ b/packages/duron/test/wait-context.test.ts @@ -18,10 +18,7 @@ async function eventually(check: () => boolean | Promise): Promise { it('interrupts real finite SQL execution rather than only observing elapsed time (owned seeded view)', async () => { const origin = realClock.now() - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const database = new URL(CONNECTION_URL).pathname.slice(1) const adapter = new PostgresAdapter({ connection: CONNECTION_URL }) const client = new Client({ @@ -169,10 +166,7 @@ suite('Native PostgreSQL wait deadlines', () => { 'Adapter._getJobStatus', ] as const) { it(`preserves ${seam} overrides without pinning a transaction around their arbitrary SQL`, async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const adapter = new PostgresAdapter({ connection: CONNECTION_URL }) const client = new Client({ database: adapter, syncPattern: false, logger: 'silent' }) const queries: string[] = [] @@ -221,10 +215,7 @@ suite('Native PostgreSQL wait deadlines', () => { it('bounds a real table-lock read and restores inherited timeout after rollback', async () => { const origin = realClock.now() - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const url = new URL(CONNECTION_URL) const database = url.pathname.slice(1) const adapter = new PostgresAdapter({ diff --git a/packages/duron/test/wait-pool.test.ts b/packages/duron/test/wait-pool.test.ts index 3f73875..fdc3c2d 100644 --- a/packages/duron/test/wait-pool.test.ts +++ b/packages/duron/test/wait-pool.test.ts @@ -13,10 +13,7 @@ suite('Native wait pool and inherited settings', () => { it( scenario, async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() const url = new URL(CONNECTION_URL) const adapter = new PostgresAdapter({ connection: { diff --git a/packages/duron/test/wait-transport.test.ts b/packages/duron/test/wait-transport.test.ts index 200bfe5..351c884 100644 --- a/packages/duron/test/wait-transport.test.ts +++ b/packages/duron/test/wait-transport.test.ts @@ -21,10 +21,7 @@ const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip suite('Owned native wait transport controls', () => { for (const phase of ['read error response', 'rollback response'] as const) { it(`retains actual capacity and drain accounting through withheld ${phase}`, async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection({ - containerName: 'duron-postgres-test', - port: 5440, - }) + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() // Reuse the existing diagnostic relay; only this new database's owned // adapter traffic traverses it. No cancellation packet or native cut. const relay = new PruneRelay() From 470258cefb6e04632aa8c7893b82f056f847c9ab Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 21:03:35 -0300 Subject: [PATCH 059/100] feat(telemetry)!: depend only on @opentelemetry/api, take tracerProvider from the app BREAKING CHANGE: telemetry.traceExporter, serviceName and batchDelayMs are removed. Pass telemetry: { tracerProvider } created by the application. Duron no longer creates a Resource or a tracer provider, and without the telemetry option it does not use the global tracer provider. - @opentelemetry/api is a peer dependency (^1.9.0); resources, sdk-trace-base, sdk-trace-node and semantic-conventions are removed - tests use @opentelemetry/sdk-trace 3 + api 1.10 (dev only) - docs: telemetry migration, client API, install, ADR 0002 --- AGENTS.md | 10 +- CONTEXT.md | 4 +- README.md | 10 +- bun.lock | 27 +- docs/adr/0001-remove-local-span-storage.md | 2 +- docs/adr/0002-opentelemetry-api-only.md | 36 ++ packages/docs/content/docs/client-api.mdx | 25 +- .../docs/content/docs/getting-started.mdx | 10 +- packages/docs/content/docs/telemetry.mdx | 128 +++-- packages/duron/README.md | 10 +- packages/duron/package.json | 9 +- packages/duron/src/client.ts | 104 ++-- packages/duron/test/otel-integration.test.ts | 487 +++++++----------- packages/shared-actions/package.json | 2 +- 14 files changed, 405 insertions(+), 459 deletions(-) create mode 100644 docs/adr/0002-opentelemetry-api-only.md diff --git a/AGENTS.md b/AGENTS.md index b4efe30..6371c6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -123,10 +123,12 @@ Workflow `.github/workflows/test.yml` runs: `bun install` → `typecheck` → `l ## Telemetry -Configured on the Duron client: +Duron depends only on `@opentelemetry/api` (peer dependency `^1.9.0`). The application owns the SDK. -- `telemetry: { traceExporter }` → export to OTel backends -- No config → disabled +- `telemetry: { tracerProvider }` → Duron gets its tracer with `tracerProvider.getTracer('duron')`. The application creates the provider (Resource, span processors, exporters) and shuts it down. +- No config → disabled (no-op tracer; the global tracer provider is not used) +- Duron does not create a Resource and does not register, flush or shut down the provider. +- Tests use `@opentelemetry/sdk-trace` 3 (`TracerProvider` + `InMemorySpanExporter`) as dev dependencies only. ## Key Files @@ -137,5 +139,5 @@ Configured on the Duron client: | `packages/duron/src/server.ts` | REST API server | | `packages/duron/src/step-manager.ts` | Step execution & nested steps | | `packages/duron/src/adapters/adapter.ts` | Base adapter | -| `packages/duron/src/telemetry/` | Telemetry adapters | +| `packages/duron/src/action-job.ts` | Job spans (OTel) | | `packages/duron-dashboard/src/DuronDashboard.tsx` | Dashboard root | diff --git a/CONTEXT.md b/CONTEXT.md index fa265b3..c10474c 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -24,9 +24,9 @@ ## Telemetry -**Telemetry (OpenTelemetry)** — Duron instruments all job and step execution with OTel spans via `@opentelemetry/api`. Users connect external collectors via `telemetry: { traceExporter }`. +**Telemetry (OpenTelemetry)** — Duron instruments all job and step execution with OTel spans via `@opentelemetry/api`, its only OpenTelemetry dependency (a peer dependency). Users enable it with `telemetry: { tracerProvider }`. Without it, telemetry is disabled; the global tracer provider is not used. -**TraceExporter** — An OpenTelemetry `SpanExporter` (or array of exporters) that receives completed spans. Users provide their own (e.g., `OTLPTraceExporter`). +**TracerProvider** — The OpenTelemetry `TracerProvider` (API interface) that the application creates with its own SDK, Resource and exporters, and passes to a Duron client. Duron gets its `duron` tracer from it and never registers, flushes or shuts it down. See ADR 0002. ## Data Model diff --git a/README.md b/README.md index 60a7c46..17303e3 100644 --- a/README.md +++ b/README.md @@ -42,17 +42,19 @@ The complete documentation includes detailed guides on actions, adapters, client ### Installation ```bash -bun add duron postgres drizzle-orm@rc +bun add duron postgres drizzle-orm@rc @opentelemetry/api # or -npm install duron postgres drizzle-orm@rc +npm install duron postgres drizzle-orm@rc @opentelemetry/api # or -pnpm add duron postgres drizzle-orm@rc +pnpm add duron postgres drizzle-orm@rc @opentelemetry/api # or -yarn add duron postgres drizzle-orm@rc +yarn add duron postgres drizzle-orm@rc @opentelemetry/api ``` Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0, on PostgreSQL 16 and 19, and with PGlite 0.6.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +`@opentelemetry/api` (`^1.9.0`) is a peer dependency: Duron uses only the OpenTelemetry API, and your application chooses the SDK. See [Telemetry](https://duron-docs.pages.dev/docs/telemetry). + ### Creating an Action with Context Actions are defined with Zod schemas and have access to a context object that includes input, variables, and a step function. First define your variables type, then use `defineAction` with the variables type as a generic parameter: diff --git a/bun.lock b/bun.lock index 42ddbb5..c17688b 100644 --- a/bun.lock +++ b/bun.lock @@ -43,11 +43,6 @@ "name": "duron", "version": "0.5.0-beta.0", "dependencies": { - "@opentelemetry/api": ">=1.9.0 <1.10.0", - "@opentelemetry/resources": "^2.12.1", - "@opentelemetry/sdk-trace-base": "^2.12.1", - "@opentelemetry/sdk-trace-node": "^2.12.1", - "@opentelemetry/semantic-conventions": "^1.45.0", "@standard-schema/spec": "^1.1.0", "@standard-schema/utils": "^0.3.0", "elysia": "^1.4.32", @@ -58,6 +53,9 @@ }, "devDependencies": { "@electric-sql/pglite": "^0.6.1", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/resources": "^3.1.1", + "@opentelemetry/sdk-trace": "^3.1.1", "@types/bun": "latest", "@types/node": "^26.6.11", "drizzle-kit": "1.0.0-rc.6", @@ -68,6 +66,7 @@ }, "peerDependencies": { "@electric-sql/pglite": "^0.5.17 || ^0.6.0", + "@opentelemetry/api": "^1.9.0", "drizzle-orm": "1.0.0-rc.6 || ^1.0.0", "postgres": "^4.1.1", }, @@ -141,7 +140,7 @@ "dependencies": { "@ai-sdk/openai": "^4.0.126", "@ai-sdk/otel": "^1.0.185", - "@opentelemetry/api": ">=1.9.0 <1.10.0", + "@opentelemetry/api": "^1.10.0", "ai": "^7.0.185", "zod": "^4.6.7", }, @@ -306,19 +305,13 @@ "@oozcitak/util": ["@oozcitak/util@10.0.0", "", {}, "sha512-hAX0pT/73190NLqBPPWSdBVGtbY6VOhWYK3qqHqtXQ1gK7kS2yz4+ivsN07hpJ6I3aeMtKP6J6npsEKOAzuTLA=="], - "@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], + "@opentelemetry/api": ["@opentelemetry/api@1.10.0", "", {}, "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ=="], - "@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@2.12.1", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-1+zgZyD7QvBr0/K6+FVx5UAzdGo0shnQf8pbWUFFbj43qZPIKTtfK4xX4J3bS7AmkifiZzAEMdk8dztiEfkgmg=="], + "@opentelemetry/core": ["@opentelemetry/core@3.1.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "sha512-6wc9r0zrTsAVOd/5UrZBsrHhXWNfwisolgWxd8o3Eu1HKIz8cAxQjOdGrrJB406ceFiGV+ckTcLdXzB+y/QVTA=="], - "@opentelemetry/core": ["@opentelemetry/core@2.12.1", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-3hr6Pj0/G0oVgIGb97IVcw9BjZ6eudonKjrmQxw7JquyU/XmVbJelkmyoU0sT/OvHGkv+r1tcrwv8MbSX7aKHw=="], + "@opentelemetry/resources": ["@opentelemetry/resources@3.1.1", "", { "dependencies": { "@opentelemetry/core": "3.1.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "sha512-dSd0FI1rfl+WHeaZxCTCEvwv6vcmUqkOHHTGWMkmyHg+PyL/wLbCqgsGKgI0wOwT0KGy9IMPAvY85hT8IPwApA=="], - "@opentelemetry/resources": ["@opentelemetry/resources@2.12.1", "", { "dependencies": { "@opentelemetry/core": "2.12.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-IwrNcuLCvnJAnNLkXxx0Uw+rjBkVW6VGQrhd7PanNf0LavOzkTk9sDAjdqegM7p/VdxefNRrii6d+wBRJfz35g=="], - - "@opentelemetry/sdk-trace": ["@opentelemetry/sdk-trace@2.12.1", "", { "dependencies": { "@opentelemetry/core": "2.12.1", "@opentelemetry/resources": "2.12.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-vANdmCYnn+Ka/alBKxwICMl4Koa+aQBlRC9zAZy+Ig1Obbo3RZt2oiyv+8/gET5rrBBYrO3YniPcXfwZrN01rg=="], - - "@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@2.12.1", "", { "dependencies": { "@opentelemetry/core": "2.12.1", "@opentelemetry/resources": "2.12.1", "@opentelemetry/sdk-trace": "2.12.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-CMrcqFxTikYmYQCuHToBO4kQvWIseRk2ztzWidTd7VutIxj1rljvJZCZnFPJEGNOS7FvaSmRL21Jeuu3/wrCAQ=="], - - "@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@2.12.1", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.12.1", "@opentelemetry/core": "2.12.1", "@opentelemetry/sdk-trace-base": "2.12.1" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-nRe0mimXZHknAEW2PKN9VbmML+93il5okotyDIUMhgYJ0QPM999fsh7djH6HDheyAbXO/C24t/B4fOQbNap8Vw=="], + "@opentelemetry/sdk-trace": ["@opentelemetry/sdk-trace@3.1.1", "", { "dependencies": { "@opentelemetry/core": "3.1.1", "@opentelemetry/resources": "3.1.1", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "sha512-DJZXZJu1H3kek9Kh9SqJ46yN3faiNiabnqkEtl9eVnBvs4KuK+ynmk9jOyB0NfWAXWGZlTivCf46uwiXyr2PGA=="], "@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.45.0", "", {}, "sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw=="], @@ -1464,6 +1457,8 @@ "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], + "@ai-sdk/otel/@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], + "@babel/core/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "@babel/traverse/debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], diff --git a/docs/adr/0001-remove-local-span-storage.md b/docs/adr/0001-remove-local-span-storage.md index 06d6d4c..34b9932 100644 --- a/docs/adr/0001-remove-local-span-storage.md +++ b/docs/adr/0001-remove-local-span-storage.md @@ -2,7 +2,7 @@ ## Status -Accepted +Accepted. The `traceExporter` configuration and the OpenTelemetry SDK dependencies described here are superseded by [ADR 0002](0002-opentelemetry-api-only.md). ## Date diff --git a/docs/adr/0002-opentelemetry-api-only.md b/docs/adr/0002-opentelemetry-api-only.md new file mode 100644 index 0000000..0486af9 --- /dev/null +++ b/docs/adr/0002-opentelemetry-api-only.md @@ -0,0 +1,36 @@ +# ADR 0002: Depend Only on the OpenTelemetry API + +## Status + +Accepted. Supersedes the `traceExporter` configuration of [ADR 0001](0001-remove-local-span-storage.md). + +## Context + +Duron created its own `NodeTracerProvider` from `telemetry: { traceExporter, serviceName, batchDelayMs }`. For this it had runtime dependencies on `@opentelemetry/resources`, `@opentelemetry/sdk-trace-base`, `@opentelemetry/sdk-trace-node` and `@opentelemetry/semantic-conventions`, and it pinned `@opentelemetry/api` to `>=1.9.0 <1.10.0`. + +This had these problems: + +- Users were locked to Duron's SDK versions. The trace SDK 2.x requires `@opentelemetry/api` lower than 1.10, and SDK 3.x (`@opentelemetry/sdk-trace`, `@opentelemetry/resources` 3) requires 1.10 or later. Duron could not move to one without breaking users of the other. +- An application with a different SDK or API version got two copies. An API 1.10 copy rejects a global registered by an API 1.9 copy, so context propagation can stop working. +- Duron created a Resource with `service.name` `duron` (or `serviceName`), separate from the Resource of the application. Duron spans and application spans showed up as different services. + +The OpenTelemetry guidance for libraries is to depend only on the API and to let the application own the SDK. + +## Decision + +- Duron depends only on `@opentelemetry/api`, as a peer dependency with the range `^1.9.0`. It is required, because Duron imports the API at runtime even when telemetry is disabled. +- The telemetry option is `telemetry: { tracerProvider: TracerProvider }` (the interface from `@opentelemetry/api`). Duron gets its tracer with `tracerProvider.getTracer('duron')`. `traceExporter`, `serviceName` and `batchDelayMs` are removed (breaking change, pre-1.0). +- Without the `telemetry` option, telemetry is disabled. Duron uses a `ProxyTracerProvider` without a delegate, which returns a no-op tracer. It does not read the global tracer provider. Each client stays scoped to the provider passed to it, as before. +- Duron does not create a Resource. The service name and other resource attributes come from the application's provider. +- Duron does not register, flush or shut down the provider. The application controls its lifecycle. +- Span names, attributes, the context-aware tracer of `ctx.telemetry` / `stepCtx.telemetry` and the explicit parent linking of job and step spans do not change. +- Tests use `@opentelemetry/sdk-trace` 3, `@opentelemetry/resources` 3 and `@opentelemetry/api` 1.10 as dev dependencies only. + +## Consequences + +- **Positive**: Users choose any SDK version (2.x with API 1.9, 3.x with API 1.10) and get one API copy shared by Duron and their SDK. +- **Positive**: Duron spans carry the application's Resource, so they appear under the application's service. +- **Positive**: Duron has four fewer runtime dependencies. +- **Negative**: Users must create a tracer provider (a few lines) instead of passing an exporter. The telemetry docs contain a migration snippet. +- **Negative**: An application that relied on the default service name `duron` must set it on its own Resource. +- **Negative**: An application that registered a global provider and expected Duron to use it implicitly must pass `trace.getTracerProvider()` explicitly. diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 20d878d..1a12dd7 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -232,23 +232,28 @@ Recovery checks for: **Optional.** Telemetry configuration for OpenTelemetry tracing. See [Telemetry](/docs/telemetry) for details. ```ts +import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace' import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http' +const tracerProvider = new TracerProvider({ + spanProcessors: [new BatchSpanProcessor({ exporter: new OTLPTraceExporter() })], +}) + { - telemetry: { - traceExporter: new OTLPTraceExporter({ - url: 'http://localhost:4318/v1/traces', - }), - serviceName: 'my-service', // OpenTelemetry service name (default: 'duron') - }, + telemetry: { tracerProvider }, } ``` **Options:** -- `traceExporter` - Export spans to external systems (`SpanExporter | SpanExporter[]`) -- `serviceName` - Service name for OpenTelemetry resource (default: `'duron'`) -- `batchDelayMs` - Delay in milliseconds between batch exports (default: `5000`) +- `tracerProvider` - **Required in `telemetry`.** An OpenTelemetry `TracerProvider` (interface from `@opentelemetry/api`) created by your application. Duron gets its tracer with `tracerProvider.getTracer('duron')`. The provider's Resource (for example `service.name`), span processors and exporters apply to Duron's spans. Duron does not register, flush or shut down the provider. + +Without `telemetry`, tracing is disabled: Duron uses a no-op tracer and does not read the global tracer provider. + + + Breaking change: `traceExporter`, `serviceName` and `batchDelayMs` are removed. See [Migration + from `traceExporter`](/docs/telemetry#migration-from-traceexporter). + ## Lifecycle Methods @@ -709,7 +714,7 @@ client.logger.info('Client started') ### `tracer` -Access the OpenTelemetry tracer for creating custom spans. Always returns a tracer — it's a no-op tracer when no telemetry SDK is configured. +Access the OpenTelemetry tracer for creating custom spans. Always returns a tracer — it's a no-op tracer when no `telemetry.tracerProvider` is configured. ```ts const span = client.tracer.startSpan('custom-operation') diff --git a/packages/docs/content/docs/getting-started.mdx b/packages/docs/content/docs/getting-started.mdx index 5266605..d4e00c6 100644 --- a/packages/docs/content/docs/getting-started.mdx +++ b/packages/docs/content/docs/getting-started.mdx @@ -12,20 +12,22 @@ Install Duron using your preferred package manager: ```bash # Using npm -npm install duron drizzle-orm@rc +npm install duron drizzle-orm@rc @opentelemetry/api # Using pnpm -pnpm add duron drizzle-orm@rc +pnpm add duron drizzle-orm@rc @opentelemetry/api # Using yarn -yarn add duron drizzle-orm@rc +yarn add duron drizzle-orm@rc @opentelemetry/api # Using bun -bun add duron drizzle-orm@rc +bun add duron drizzle-orm@rc @opentelemetry/api ``` Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +`@opentelemetry/api` (`^1.9.0`) is a peer dependency: Duron uses only the OpenTelemetry API, and your application chooses the SDK. See [Telemetry](/docs/telemetry). + Duron is tested with PostgreSQL 16 and 19. Install postgres for the current database: diff --git a/packages/docs/content/docs/telemetry.mdx b/packages/docs/content/docs/telemetry.mdx index 3c4ad6e..b7d5c73 100644 --- a/packages/docs/content/docs/telemetry.mdx +++ b/packages/docs/content/docs/telemetry.mdx @@ -4,63 +4,124 @@ description: Add observability to your job queue with OpenTelemetry tracing icon: Activity --- -Duron provides built-in OpenTelemetry support for tracing job and step execution. Spans are exported to external systems via standard OpenTelemetry exporters. +Duron provides built-in OpenTelemetry support for tracing job and step execution. Duron depends only on `@opentelemetry/api`. Your application owns the OpenTelemetry SDK: it creates the tracer provider, with its own Resource, span processors and exporters, and passes it to Duron. + +This follows the OpenTelemetry guidance for libraries. You choose the SDK version, and Duron never brings a second copy of the SDK into your application. ## Configuration -Configure telemetry when creating a Duron client: +Create a tracer provider in your application and pass it as `telemetry.tracerProvider`: ```ts +import { resourceFromAttributes } from '@opentelemetry/resources' +import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace' +import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http' +import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions' import { duron } from 'duron' import { postgresAdapter } from 'duron/adapters/postgres' -import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http' + +const tracerProvider = new TracerProvider({ + resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: 'my-service' }), + spanProcessors: [ + new BatchSpanProcessor({ + exporter: new OTLPTraceExporter({ url: 'http://localhost:4318/v1/traces' }), + }), + ], +}) const client = duron({ database: postgresAdapter({ connection: process.env.DATABASE_URL, }), actions: {/* your actions */}, - telemetry: { - traceExporter: new OTLPTraceExporter({ - url: 'http://localhost:4318/v1/traces', - }), - }, + telemetry: { tracerProvider }, }) ``` ### Configuration Options -| Option | Type | Description | -| --------------- | -------------------------------- | ------------------------------------------------------------- | -| `traceExporter` | `SpanExporter \| SpanExporter[]` | Export spans to external systems (OTLP, Jaeger, etc.) | -| `serviceName` | `string` | Service name for OpenTelemetry resource (default: `'duron'`) | -| `batchDelayMs` | `number` | Delay in milliseconds between batch exports (default: `5000`) | +| Option | Type | Description | +| ---------------- | ---------------- | ------------------------------------------------------------------------------------------------------- | +| `tracerProvider` | `TracerProvider` | The provider Duron gets its tracer from (`tracerProvider.getTracer('duron')`). Required in `telemetry`. | + +`TracerProvider` is the interface from `@opentelemetry/api`. Any provider works: `TracerProvider` from `@opentelemetry/sdk-trace` (SDK 3), `NodeTracerProvider` from `@opentelemetry/sdk-trace-node` (SDK 2), or the provider that `NodeSDK` registers globally. -### Single Exporter +Without the `telemetry` option, telemetry is disabled. Duron uses a no-op tracer and does **not** fall back to the global tracer provider. To use a global provider, pass it explicitly: ```ts -import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http' +import { trace } from '@opentelemetry/api' +import { NodeSDK } from '@opentelemetry/sdk-node' -telemetry: { - traceExporter: new OTLPTraceExporter({ - url: 'http://localhost:4318/v1/traces', - }), -} +const sdk = new NodeSDK({/* serviceName, traceExporter, ... */}) +sdk.start() + +const client = duron({ + // ... + telemetry: { tracerProvider: trace.getTracerProvider() }, +}) ``` -### Multiple Exporters +### Service name and Resource + +Duron does not create a Resource. The spans carry the Resource of the provider that you pass, so set `service.name` and any other resource attributes on your provider. Duron's spans use the instrumentation scope `duron`. + +### Exporters, batching and shutdown + +Exporters, span processors and batching options (`scheduledDelayMillis`, and others) are part of your provider. To send spans to several backends, add one span processor per exporter. Duron does not flush or shut down the provider: call `tracerProvider.shutdown()` when your application stops, so that buffered spans are exported. + +### Multiple clients + +Each Duron client uses only the provider passed to it. Two clients with different providers export their spans separately, with their own Resources. -Send spans to multiple backends simultaneously: +### Context propagation + +Duron links its job, step and custom spans explicitly, so its trace hierarchy is correct without a global context manager. Libraries that read `context.active()` (for example, HTTP or database instrumentations) need a context manager registered by your application, for example `AsyncLocalStorageContextManager` from `@opentelemetry/context-async-hooks`, or `NodeSDK`. + +## Migration from `traceExporter` + +The options `traceExporter`, `serviceName` and `batchDelayMs` are removed. Duron no longer creates a tracer provider. Create the provider in your application and pass it as `tracerProvider`. + +Before: ```ts -telemetry: { - traceExporter: [ - new OTLPTraceExporter({ url: 'http://localhost:4318/v1/traces' }), - new JaegerExporter({ endpoint: 'http://localhost:14268/api/traces' }), +const client = duron({ + database, + actions, + telemetry: { + traceExporter: new OTLPTraceExporter(), + serviceName: 'my-service', + batchDelayMs: 1000, + }, +}) +``` + +After: + +```ts +import { resourceFromAttributes } from '@opentelemetry/resources' +import { BatchSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace' +import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions' + +const tracerProvider = new TracerProvider({ + resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: 'my-service' }), + spanProcessors: [ + new BatchSpanProcessor({ exporter: new OTLPTraceExporter(), scheduledDelayMillis: 1000 }), ], -} +}) + +const client = duron({ database, actions, telemetry: { tracerProvider } }) + +// On shutdown +await client.stop() +await tracerProvider.shutdown() ``` +Differences: + +- The default service name was `duron`. Now the service name comes from your provider's Resource. Without one, the SDK default applies (`unknown_service:`). +- An array of exporters becomes one span processor per exporter. +- Without the `telemetry` option, Duron does not use a globally registered provider. + ## Telemetry Context Both action and step handlers have access to `ctx.telemetry` which provides OpenTelemetry APIs: @@ -270,21 +331,22 @@ try { ## Installation -Duron includes the OpenTelemetry SDK packages as dependencies. You only need to install an exporter: +`@opentelemetry/api` is a peer dependency of Duron (`^1.9.0`). Your application installs it once, so Duron and your SDK share the same API instance. Install the SDK and the exporter that you want: ```bash +bun add @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/resources @opentelemetry/semantic-conventions + # For OTLP export bun add @opentelemetry/exporter-trace-otlp-http - -# For Jaeger -bun add @opentelemetry/exporter-jaeger ``` +Duron is tested with `@opentelemetry/api` 1.10 and `@opentelemetry/sdk-trace` 3. SDK 2 (`@opentelemetry/sdk-trace-node`, which requires `@opentelemetry/api` lower than 1.10) also works. + ## Architecture Notes Duron's telemetry implementation: -- **Does not globally register** the tracer provider, avoiding conflicts with other telemetry in your application +- **Depends only on `@opentelemetry/api`**: the application owns the SDK, the Resource and the exporters +- **Does not globally register** a tracer provider and does not read the global one: each client uses only the provider passed to it - Uses a **context-aware tracer wrapper** that automatically links spans to the correct trace hierarchy - Exports spans with `duron.job.id` attribute for job association -- Supports multiple exporters for sending spans to different backends diff --git a/packages/duron/README.md b/packages/duron/README.md index 609aff4..90f7bf7 100644 --- a/packages/duron/README.md +++ b/packages/duron/README.md @@ -6,20 +6,22 @@ A powerful, type-safe job queue system for Node.js and Bun.js. Duron provides a ```bash # Using bun -bun add duron postgres drizzle-orm@rc +bun add duron postgres drizzle-orm@rc @opentelemetry/api # Using npm -npm install duron postgres drizzle-orm@rc +npm install duron postgres drizzle-orm@rc @opentelemetry/api # Using pnpm -pnpm add duron postgres drizzle-orm@rc +pnpm add duron postgres drizzle-orm@rc @opentelemetry/api # Using yarn -yarn add duron postgres drizzle-orm@rc +yarn add duron postgres drizzle-orm@rc @opentelemetry/api ``` Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0, on PostgreSQL 16 and 19, and with PGlite 0.6.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +`@opentelemetry/api` (`^1.9.0`) is a peer dependency: Duron uses only the OpenTelemetry API, and your application chooses the SDK. See [Telemetry](https://duron.dev/docs/telemetry). + ## Quick Start ### 1. Define an Action diff --git a/packages/duron/package.json b/packages/duron/package.json index 84ecaef..c03e66d 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -81,11 +81,6 @@ "typecheck": "bun check --no-script" }, "dependencies": { - "@opentelemetry/api": ">=1.9.0 <1.10.0", - "@opentelemetry/resources": "^2.12.1", - "@opentelemetry/sdk-trace-base": "^2.12.1", - "@opentelemetry/sdk-trace-node": "^2.12.1", - "@opentelemetry/semantic-conventions": "^1.45.0", "@standard-schema/spec": "^1.1.0", "@standard-schema/utils": "^0.3.0", "elysia": "^1.4.32", @@ -96,6 +91,9 @@ }, "devDependencies": { "@electric-sql/pglite": "^0.6.1", + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/resources": "^3.1.1", + "@opentelemetry/sdk-trace": "^3.1.1", "@types/bun": "latest", "@types/node": "^26.6.11", "drizzle-kit": "1.0.0-rc.6", @@ -106,6 +104,7 @@ }, "peerDependencies": { "@electric-sql/pglite": "^0.5.17 || ^0.6.0", + "@opentelemetry/api": "^1.9.0", "drizzle-orm": "1.0.0-rc.6 || ^1.0.0", "postgres": "^4.1.1" }, diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 0c37226..1da6183 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -1,12 +1,9 @@ -import { type Span, type Tracer, trace } from '@opentelemetry/api' -import { resourceFromAttributes } from '@opentelemetry/resources' import { - BatchSpanProcessor, - type SpanExporter, - type SpanProcessor, -} from '@opentelemetry/sdk-trace-base' -import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node' -import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions' + ProxyTracerProvider, + type Span, + type Tracer, + type TracerProvider, +} from '@opentelemetry/api' import type { StandardSchemaV1 } from '@standard-schema/spec' import pino, { type Logger } from 'pino' import * as z from 'zod/mini' @@ -101,29 +98,23 @@ export interface TelemetryContext { /** * Telemetry configuration options. - * Uses OpenTelemetry SDK for tracing. + * + * Duron depends only on `@opentelemetry/api`. The application owns the + * OpenTelemetry SDK: it creates the tracer provider (with its own Resource, + * span processors and exporters) and passes it here. */ export interface TelemetryOptions { /** - * Span exporter(s) to send completed spans to an external OTel collector. - * Accepts a single exporter or an array of exporters. - * Each exporter is wrapped in a BatchSpanProcessor. - */ - traceExporter?: SpanExporter | SpanExporter[] - - /** - * Service name for OpenTelemetry resource. - * @default 'duron' - */ - serviceName?: string - - /** - * Delay in milliseconds between batch exports. - * @default 5000 + * The OpenTelemetry tracer provider that Duron uses to create its spans. + * Duron gets its tracer with `tracerProvider.getTracer('duron')`. + * Duron does not register this provider globally, and it does not + * flush or shut it down: the application controls its lifecycle. */ - batchDelayMs?: number + tracerProvider: TracerProvider } +const TRACER_NAME = 'duron' + /** * Base configuration options for a Duron client instance. * These options control job fetching, concurrency, and recovery behavior. @@ -343,15 +334,16 @@ export interface ClientOptions< /** * Optional telemetry configuration for observability. - * Uses OpenTelemetry SDK for tracing. + * Without this option, telemetry is disabled: Duron uses a no-op tracer and + * does not fall back to the global OpenTelemetry tracer provider. * * @example * ```typescript - * // Export to external systems (e.g., OTLP) - * telemetry: { traceExporter: new OTLPTraceExporter() } - * - * // Multiple exporters - * telemetry: { traceExporter: [new OTLPTraceExporter(), myCustomExporter] } + * const provider = new TracerProvider({ + * resource: resourceFromAttributes({ 'service.name': 'my-service' }), + * spanProcessors: [new BatchSpanProcessor({ exporter: new OTLPTraceExporter() })], + * }) + * telemetry: { tracerProvider: provider } * ``` */ telemetry?: TelemetryOptions @@ -447,49 +439,11 @@ export class Client< this.start === Client.prototype.start, ) - // Initialize OpenTelemetry TracerProvider if telemetry options are provided - // Get tracer from our provider if configured, otherwise use global no-op tracer - // This keeps telemetry scoped to this client instance rather than globally registered - this.#tracer = trace.getTracer('duron') - - // Initialize telemetry if traceExporter is provided - if (options.telemetry) { - this.#initTelemetry(options.telemetry) - } - } - - /** - * Initialize OpenTelemetry TracerProvider with configured processors. - */ - #initTelemetry(options: TelemetryOptions): void { - const serviceName = options.serviceName ?? 'duron' - const processors: SpanProcessor[] = [] - - // Add trace exporter(s) wrapped in BatchSpanProcessor - if (options.traceExporter) { - const exporters = Array.isArray(options.traceExporter) - ? options.traceExporter - : [options.traceExporter] - for (const exporter of exporters) { - processors.push( - new BatchSpanProcessor(exporter, { - scheduledDelayMillis: options.batchDelayMs ?? 5000, - }), - ) - } - } - - // Only create TracerProvider if we have processors - if (processors.length > 0) { - const provider = new NodeTracerProvider({ - resource: resourceFromAttributes({ - [ATTR_SERVICE_NAME]: serviceName, - }), - spanProcessors: processors, - }) - // Rebind the tracer to use the configured provider - this.#tracer = provider.getTracer('duron') - } + // Telemetry is scoped to this client: the tracer comes from the provider the + // application passed in. Without one, a ProxyTracerProvider with no delegate + // gives a no-op tracer. It never reads the global tracer provider. + const tracerProvider = options.telemetry?.tracerProvider ?? new ProxyTracerProvider() + this.#tracer = tracerProvider.getTracer(TRACER_NAME) } #normalizeLogger( @@ -516,7 +470,7 @@ export class Client< /** * Get the OpenTelemetry tracer for creating custom spans. - * Always returns a tracer - it's a no-op tracer when no SDK is configured. + * Always returns a tracer - it's a no-op tracer when no `telemetry.tracerProvider` is configured. */ get tracer(): Tracer { return this.#tracer diff --git a/packages/duron/test/otel-integration.test.ts b/packages/duron/test/otel-integration.test.ts index dcbbae8..0a7ac0a 100644 --- a/packages/duron/test/otel-integration.test.ts +++ b/packages/duron/test/otel-integration.test.ts @@ -1,347 +1,234 @@ -import { afterEach, beforeEach, describe, expect, it } from 'bun:test' - -import { type SpanExporter, type ReadableSpan } from '@opentelemetry/sdk-trace-base' +import { describe, expect, it } from 'bun:test' + +import { trace } from '@opentelemetry/api' +import { resourceFromAttributes } from '@opentelemetry/resources' +import { + InMemorySpanExporter, + type ReadableSpan, + SimpleSpanProcessor, + TracerProvider, +} from '@opentelemetry/sdk-trace' import { z } from 'zod/mini' import { defineAction } from '../src/action.js' import { Client } from '../src/client.js' import { JOB_STATUS_COMPLETED } from '../src/constants.js' -import { type Adapter, pgliteFactory } from './adapters.js' +import { pgliteFactory } from './adapters.js' /** - * In-memory span exporter for testing. - * Collects all exported spans in memory for assertion. + * The application owns the OpenTelemetry SDK. It builds a provider with its own + * Resource and exporter, and passes that provider to Duron. */ -class InMemorySpanExporter implements SpanExporter { - private spans: ReadableSpan[] = [] - - export(spans: ReadableSpan[], resultCallback: (result: { code: number }) => void): void { - this.spans.push(...spans) - resultCallback({ code: 0 }) // SUCCESS - } - - shutdown(): Promise { - this.spans = [] - return Promise.resolve() - } +function createAppTelemetry(serviceName: string) { + const exporter = new InMemorySpanExporter() + const provider = new TracerProvider({ + resource: resourceFromAttributes({ 'service.name': serviceName }), + spanProcessors: [new SimpleSpanProcessor({ exporter })], + }) + return { exporter, provider } +} - getSpans(): ReadableSpan[] { - return [...this.spans] +/** + * The job span ends after the job is completed in the database, so it can end + * after waitForJob() resolves. Poll the exporter until the span is available. + */ +async function waitForSpan( + exporter: InMemorySpanExporter, + name: string, + timeoutMs = 5_000, +): Promise { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + const span = exporter.getFinishedSpans().find((s) => s.name === name) + if (span) return span + await new Promise((resolve) => setTimeout(resolve, 10)) } + throw new Error(`span ${name} was not exported within ${timeoutMs}ms`) +} - reset(): void { - this.spans = [] - } +function parentSpanId(span: ReadableSpan): string | undefined { + return span.parentSpanContext?.spanId } -// Simple action for testing const simpleAction = defineAction()({ name: 'simple-action', version: '1.0.0', - input: z.object({ - value: z.number(), - }), - output: z.object({ - result: z.number(), - }), + input: z.object({ value: z.number() }), + output: z.object({ result: z.number() }), handler: async (ctx) => { return { result: ctx.input.value * 2 } }, }) -// Action with a step const stepAction = defineAction()({ name: 'step-action', version: '1.0.0', - input: z.object({ - value: z.number(), - }), - output: z.object({ - result: z.number(), - }), + input: z.object({ value: z.number() }), + output: z.object({ result: z.number() }), handler: async (ctx) => { - const stepResult = await ctx.step('multiply', async () => { - return { multiplied: ctx.input.value * 2 } - }) - return { result: stepResult.multiplied } - }, -}) - -// Action with custom span -const customSpanAction = defineAction()({ - name: 'custom-span-action', - version: '1.0.0', - input: z.object({ - value: z.number(), - }), - output: z.object({ - result: z.number(), - }), - handler: async (ctx) => { - const result = await ctx.step('with-custom-span', async ({ telemetry }) => { - const customSpan = telemetry.startSpan('custom-operation', { + const outer = await ctx.step('outer', async ({ step, telemetry }) => { + const custom = telemetry.startSpan('custom-operation', { attributes: { 'custom.input': ctx.input.value }, }) - const processed = ctx.input.value * 4 - customSpan.setAttribute('custom.output', processed) - customSpan.end() - return { processed } + custom.setAttribute('custom.output', ctx.input.value * 4) + custom.end() + + const handlerSpan = telemetry.getTracer('app-library').startSpan('library-operation') + handlerSpan.end() + + return step('inner', async () => ({ multiplied: ctx.input.value * 2 })) }) - return { result: result.processed } + return { result: outer.multiplied } }, }) -describe('OpenTelemetry Integration with External Exporter', () => { - let exporter: InMemorySpanExporter - let client: Client< - { - simpleAction: typeof simpleAction - stepAction: typeof stepAction - customSpanAction: typeof customSpanAction - }, - Record - > - let database: Adapter - let deleteDb: () => Promise - - beforeEach( - async () => { - exporter = new InMemorySpanExporter() +const actions = { simpleAction, stepAction } - const adapterInstance = await pgliteFactory.create({}) - database = adapterInstance.adapter - deleteDb = adapterInstance.deleteDb - - client = new Client({ - database, - actions: { - simpleAction, - stepAction, - customSpanAction, - }, - telemetry: { - traceExporter: exporter, - serviceName: 'duron-test', - batchDelayMs: 100, // Fast flush for tests - }, +/** + * Tests in this file run concurrently (`bun test --concurrent`), so each test + * owns its clients and databases and cleans up only those. + */ +async function withClients( + fn: ( + createClient: (telemetry?: { + tracerProvider: TracerProvider + }) => Promise>, + ) => Promise, +) { + const clients: Client[] = [] + const cleanups: (() => Promise)[] = [] + try { + await fn(async (telemetry) => { + const { adapter, deleteDb } = await pgliteFactory.create({}) + cleanups.push(deleteDb) + const client = new Client({ + database: adapter, + actions, + telemetry, syncPattern: false, recoverJobsOnStart: false, logger: 'error', }) - + clients.push(client) await client.start() - }, - { - timeout: 60_000, - }, - ) - - afterEach(async () => { - if (client) { - await client.stop() - } - if (deleteDb) { - await deleteDb() - } - }) - - it('should export spans to external exporter', async () => { - const jobId = await client.runAction('simpleAction', { value: 5 }) - await client.fetch() - - const job = await client.waitForJob(jobId) - expect(job?.status).toBe(JOB_STATUS_COMPLETED) - - // Wait a bit for async export - // Wait for spans to be exported (BatchSpanProcessor has a default 5s delay) - await new Promise((resolve) => setTimeout(resolve, 500)) - - const spans = exporter.getSpans() - expect(spans.length).toBeGreaterThanOrEqual(1) - - // Find the job span - const jobSpan = spans.find((s) => s.name === 'job:simple-action') - expect(jobSpan).toBeDefined() - expect(jobSpan!.attributes['duron.job.id']).toBe(jobId) - }) - - it('should export step spans with proper hierarchy', async () => { - const jobId = await client.runAction('stepAction', { value: 7 }) - await client.fetch() - - const job = await client.waitForJob(jobId) - expect(job?.status).toBe(JOB_STATUS_COMPLETED) - - await new Promise((resolve) => setTimeout(resolve, 500)) - - const spans = exporter.getSpans() - - const jobSpan = spans.find((s) => s.name === 'job:step-action') - const stepSpan = spans.find((s) => s.name === 'step:multiply') - - expect(jobSpan).toBeDefined() - expect(stepSpan).toBeDefined() - - // Step span should be a child of job span (same trace ID) - expect(stepSpan!.spanContext().traceId).toBe(jobSpan!.spanContext().traceId) - // The step span should have a different span ID than the job span - expect(stepSpan!.spanContext().spanId).not.toBe(jobSpan!.spanContext().spanId) - }) - - it('should export custom spans created via telemetry.startSpan()', async () => { - const jobId = await client.runAction('customSpanAction', { value: 5 }) - await client.fetch() - - const job = await client.waitForJob(jobId) - expect(job?.status).toBe(JOB_STATUS_COMPLETED) - - await new Promise((resolve) => setTimeout(resolve, 500)) - - const spans = exporter.getSpans() - - const customSpan = spans.find((s) => s.name === 'custom-operation') - expect(customSpan).toBeDefined() - expect(customSpan!.attributes['custom.input']).toBe(5) - expect(customSpan!.attributes['custom.output']).toBe(20) - }) - - it('should still execute jobs successfully with external exporter', async () => { - const jobId = await client.runAction('simpleAction', { value: 10 }) - await client.fetch() - - const job = await client.waitForJob(jobId) - expect(job?.status).toBe(JOB_STATUS_COMPLETED) - expect(job?.output).toEqual({ result: 20 }) - }) -}) - -describe('OpenTelemetry - Multiple Exporters', () => { - let exporter1: InMemorySpanExporter - let exporter2: InMemorySpanExporter - let client: Client< - { - simpleAction: typeof simpleAction - }, - Record - > - let database: Adapter - let deleteDb: () => Promise - - beforeEach( - async () => { - exporter1 = new InMemorySpanExporter() - exporter2 = new InMemorySpanExporter() - - const adapterInstance = await pgliteFactory.create({}) - database = adapterInstance.adapter - deleteDb = adapterInstance.deleteDb + return client + }) + } finally { + await Promise.all(clients.map((client) => client.stop())) + await Promise.all(cleanups.map((cleanup) => cleanup())) + } +} - client = new Client({ - database, - actions: { - simpleAction, - }, - telemetry: { - traceExporter: [exporter1, exporter2], - serviceName: 'duron-test-multi', - batchDelayMs: 100, // Fast flush for tests - }, - syncPattern: false, - recoverJobsOnStart: false, - logger: 'error', - }) +async function runJob(client: Client, name: keyof typeof actions, value: number) { + const jobId = await client.runAction(name, { value }) + await client.fetch() + const job = await client.waitForJob(jobId) + expect(job?.status).toBe(JOB_STATUS_COMPLETED) + return { jobId, job } +} - await client.start() - }, - { - timeout: 60_000, - }, +describe('OpenTelemetry with an application tracer provider', () => { + it( + 'exports job spans through the application exporter with the application resource', + () => + withClients(async (createClient) => { + const { exporter, provider } = createAppTelemetry('app-service') + const client = await createClient({ tracerProvider: provider }) + + const { jobId } = await runJob(client, 'simpleAction', 5) + + const jobSpan = await waitForSpan(exporter, 'job:simple-action') + expect(jobSpan.attributes['duron.job.id']).toBe(jobId) + expect(jobSpan.attributes['duron.action.name']).toBe('simple-action') + expect(jobSpan.instrumentationScope.name).toBe('duron') + // Duron does not create a Resource: the span carries the application's Resource. + expect(jobSpan.resource.attributes['service.name']).toBe('app-service') + expect(parentSpanId(jobSpan)).toBeUndefined() + }), + { timeout: 60_000 }, ) - afterEach(async () => { - if (client) { - await client.stop() - } - if (deleteDb) { - await deleteDb() - } - }) - - it('should export spans to all exporters', async () => { - const jobId = await client.runAction('simpleAction', { value: 5 }) - await client.fetch() - - const job = await client.waitForJob(jobId) - expect(job?.status).toBe(JOB_STATUS_COMPLETED) - - await new Promise((resolve) => setTimeout(resolve, 500)) - - // Both exporters should have received the spans - expect(exporter1.getSpans().length).toBeGreaterThanOrEqual(1) - expect(exporter2.getSpans().length).toBeGreaterThanOrEqual(1) + it( + 'keeps the parent/child hierarchy of job, steps, nested steps and handler spans', + () => + withClients(async (createClient) => { + const { exporter, provider } = createAppTelemetry('app-service') + const client = await createClient({ tracerProvider: provider }) + + const { job } = await runJob(client, 'stepAction', 7) + expect(job?.output).toEqual({ result: 14 }) + + const jobSpan = await waitForSpan(exporter, 'job:step-action') + const outer = await waitForSpan(exporter, 'step:outer') + const inner = await waitForSpan(exporter, 'step:inner') + const custom = await waitForSpan(exporter, 'custom-operation') + const library = await waitForSpan(exporter, 'library-operation') + + const traceId = jobSpan.spanContext().traceId + for (const span of [outer, inner, custom, library]) { + expect(span.spanContext().traceId).toBe(traceId) + } + expect(parentSpanId(outer)).toBe(jobSpan.spanContext().spanId) + expect(parentSpanId(inner)).toBe(outer.spanContext().spanId) + expect(parentSpanId(custom)).toBe(outer.spanContext().spanId) + expect(parentSpanId(library)).toBe(outer.spanContext().spanId) + expect(custom.attributes['custom.input']).toBe(7) + expect(custom.attributes['custom.output']).toBe(28) + }), + { timeout: 60_000 }, + ) - // Both should have the same job span - const span1 = exporter1.getSpans().find((s) => s.name === 'job:simple-action') - const span2 = exporter2.getSpans().find((s) => s.name === 'job:simple-action') - expect(span1).toBeDefined() - expect(span2).toBeDefined() - }) + it( + 'keeps two clients with different providers isolated', + () => + withClients(async (createClient) => { + const a = createAppTelemetry('service-a') + const b = createAppTelemetry('service-b') + const clientA = await createClient({ tracerProvider: a.provider }) + const clientB = await createClient({ tracerProvider: b.provider }) + + const [jobA, jobB] = await Promise.all([ + runJob(clientA, 'simpleAction', 1), + runJob(clientB, 'simpleAction', 2), + ]) + + const spanA = await waitForSpan(a.exporter, 'job:simple-action') + const spanB = await waitForSpan(b.exporter, 'job:simple-action') + expect(spanA.attributes['duron.job.id']).toBe(jobA.jobId) + expect(spanB.attributes['duron.job.id']).toBe(jobB.jobId) + expect(spanA.resource.attributes['service.name']).toBe('service-a') + expect(spanB.resource.attributes['service.name']).toBe('service-b') + + const idsA = a.exporter.getFinishedSpans().map((s) => s.attributes['duron.job.id']) + const idsB = b.exporter.getFinishedSpans().map((s) => s.attributes['duron.job.id']) + expect(idsA).not.toContain(jobB.jobId) + expect(idsB).not.toContain(jobA.jobId) + }), + { timeout: 60_000 }, + ) }) -describe('OpenTelemetry - No Config', () => { - let client: Client< - { - simpleAction: typeof simpleAction - }, - Record - > - let database: Adapter - let deleteDb: () => Promise - - beforeEach( - async () => { - const adapterInstance = await pgliteFactory.create({}) - database = adapterInstance.adapter - deleteDb = adapterInstance.deleteDb - - // No telemetry config - client = new Client({ - database, - actions: { - simpleAction, - }, - syncPattern: false, - recoverJobsOnStart: false, - logger: 'error', - }) - - await client.start() - }, - { - timeout: 60_000, - }, +describe('OpenTelemetry without a telemetry option', () => { + it( + 'produces no spans, even when the application registered a global provider', + () => + withClients(async (createClient) => { + const global = createAppTelemetry('global-service') + trace.setGlobalTracerProvider(global.provider) + try { + const client = await createClient() + expect(client.tracer.startSpan('probe').isRecording()).toBe(false) + + const { job } = await runJob(client, 'stepAction', 3) + expect(job?.output).toEqual({ result: 6 }) + + await global.provider.forceFlush() + expect(global.exporter.getFinishedSpans()).toEqual([]) + } finally { + trace.disable() + } + }), + { timeout: 60_000 }, ) - - afterEach(async () => { - if (client) { - await client.stop() - } - if (deleteDb) { - await deleteDb() - } - }) - - it('should still have a tracer available (no-op)', () => { - expect(client.tracer).toBeDefined() - }) - - it('should execute jobs successfully without telemetry', async () => { - const jobId = await client.runAction('simpleAction', { value: 5 }) - await client.fetch() - - const job = await client.waitForJob(jobId) - expect(job?.status).toBe(JOB_STATUS_COMPLETED) - expect(job?.output).toEqual({ result: 10 }) - }) }) diff --git a/packages/shared-actions/package.json b/packages/shared-actions/package.json index fb5e5d8..e89b76e 100644 --- a/packages/shared-actions/package.json +++ b/packages/shared-actions/package.json @@ -7,7 +7,7 @@ "dependencies": { "@ai-sdk/openai": "^4.0.126", "@ai-sdk/otel": "^1.0.185", - "@opentelemetry/api": ">=1.9.0 <1.10.0", + "@opentelemetry/api": "^1.10.0", "ai": "^7.0.185", "zod": "^4.6.7" }, From 86a73821f904204217391c4279598a513fc0ebed Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 21:18:32 -0300 Subject: [PATCH 060/100] fix(telemetry): reject un-migrated telemetry config, propagate ids without SDK internals - Client throws a TypeError naming telemetry.tracerProvider and the migration notes when telemetry is set without a valid tracerProvider or with a removed option (traceExporter, serviceName, batchDelayMs) - duron.job.id / duron.step.id on handler spans come from StepManager state, not span.attributes, so any API-compliant provider works; startActiveSpan from getTracer() now carries them too - tests: minimal API-only TracerProvider, validation cases, assert the global provider registration --- docs/adr/0002-opentelemetry-api-only.md | 2 + packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/telemetry.mdx | 4 +- packages/duron/src/client.ts | 41 +++- packages/duron/src/step-manager.ts | 78 ++++--- packages/duron/test/otel-integration.test.ts | 222 ++++++++++++++++++- 6 files changed, 314 insertions(+), 35 deletions(-) diff --git a/docs/adr/0002-opentelemetry-api-only.md b/docs/adr/0002-opentelemetry-api-only.md index 0486af9..fe02438 100644 --- a/docs/adr/0002-opentelemetry-api-only.md +++ b/docs/adr/0002-opentelemetry-api-only.md @@ -21,6 +21,8 @@ The OpenTelemetry guidance for libraries is to depend only on the API and to let - Duron depends only on `@opentelemetry/api`, as a peer dependency with the range `^1.9.0`. It is required, because Duron imports the API at runtime even when telemetry is disabled. - The telemetry option is `telemetry: { tracerProvider: TracerProvider }` (the interface from `@opentelemetry/api`). Duron gets its tracer with `tracerProvider.getTracer('duron')`. `traceExporter`, `serviceName` and `batchDelayMs` are removed (breaking change, pre-1.0). - Without the `telemetry` option, telemetry is disabled. Duron uses a `ProxyTracerProvider` without a delegate, which returns a no-op tracer. It does not read the global tracer provider. Each client stays scoped to the provider passed to it, as before. +- A `telemetry` option without a valid `tracerProvider` (an object with `getTracer()`), or with a removed option, makes the `Client` constructor throw a `TypeError` with a link to the migration notes. An un-migrated `{ traceExporter }` config from an untyped caller must not disable tracing without a notice. +- The `duron.job.id` / `duron.step.id` attributes of handler spans (`ctx.telemetry.startSpan()`, `getTracer().startSpan()` / `startActiveSpan()`) come from Duron's own job and step state. Duron does not read `span.attributes`, which is an SDK detail and not part of the API, so any API-compliant provider works. - Duron does not create a Resource. The service name and other resource attributes come from the application's provider. - Duron does not register, flush or shut down the provider. The application controls its lifecycle. - Span names, attributes, the context-aware tracer of `ctx.telemetry` / `stepCtx.telemetry` and the explicit parent linking of job and step spans do not change. diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 1a12dd7..173c8dc 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -248,7 +248,7 @@ const tracerProvider = new TracerProvider({ - `tracerProvider` - **Required in `telemetry`.** An OpenTelemetry `TracerProvider` (interface from `@opentelemetry/api`) created by your application. Duron gets its tracer with `tracerProvider.getTracer('duron')`. The provider's Resource (for example `service.name`), span processors and exporters apply to Duron's spans. Duron does not register, flush or shut down the provider. -Without `telemetry`, tracing is disabled: Duron uses a no-op tracer and does not read the global tracer provider. +Without `telemetry`, tracing is disabled: Duron uses a no-op tracer and does not read the global tracer provider. If `telemetry` is set without a valid `tracerProvider`, or with a removed option, the constructor throws a `TypeError`. Breaking change: `traceExporter`, `serviceName` and `batchDelayMs` are removed. See [Migration diff --git a/packages/docs/content/docs/telemetry.mdx b/packages/docs/content/docs/telemetry.mdx index b7d5c73..a7a53dc 100644 --- a/packages/docs/content/docs/telemetry.mdx +++ b/packages/docs/content/docs/telemetry.mdx @@ -81,6 +81,8 @@ Duron links its job, step and custom spans explicitly, so its trace hierarchy is The options `traceExporter`, `serviceName` and `batchDelayMs` are removed. Duron no longer creates a tracer provider. Create the provider in your application and pass it as `tracerProvider`. +An un-migrated config does not silently disable tracing: if `telemetry` is set without a `tracerProvider` (an object with `getTracer()`), or contains one of the removed options, the `Client` constructor throws a `TypeError` that links to this section. + Before: ```ts @@ -349,4 +351,4 @@ Duron's telemetry implementation: - **Depends only on `@opentelemetry/api`**: the application owns the SDK, the Resource and the exporters - **Does not globally register** a tracer provider and does not read the global one: each client uses only the provider passed to it - Uses a **context-aware tracer wrapper** that automatically links spans to the correct trace hierarchy -- Exports spans with `duron.job.id` attribute for job association +- Exports spans with `duron.job.id` attribute for job association. Spans created with `ctx.telemetry.startSpan()` or the tracer from `getTracer()` (`startSpan` and `startActiveSpan`) also get `duron.job.id`, and `duron.step.id` inside a step. Duron sets these from its own state and does not read SDK-specific span properties, so they work with any provider that implements the `@opentelemetry/api` interfaces diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 1da6183..98fcf53 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -115,6 +115,44 @@ export interface TelemetryOptions { const TRACER_NAME = 'duron' +const REMOVED_TELEMETRY_OPTIONS = ['traceExporter', 'serviceName', 'batchDelayMs'] as const + +/** + * Reject a telemetry option that would otherwise disable tracing without a + * notice, for example an un-migrated `{ traceExporter }` config from an + * untyped caller. + */ +function assertTelemetryOptions(telemetry: unknown): TelemetryOptions | undefined { + if (telemetry === undefined || telemetry === null) { + return undefined + } + const removed = + typeof telemetry === 'object' ? REMOVED_TELEMETRY_OPTIONS.filter((key) => key in telemetry) : [] + const tracerProvider = + typeof telemetry === 'object' + ? (telemetry as { tracerProvider?: unknown }).tracerProvider + : null + const valid = + removed.length === 0 && + (typeof tracerProvider === 'object' || typeof tracerProvider === 'function') && + tracerProvider !== null && + typeof (tracerProvider as { getTracer?: unknown }).getTracer === 'function' + if (valid) { + return telemetry as TelemetryOptions + } + const removedText = + removed.length > 0 + ? ` The removed option(s) ${removed.join(', ')} are no longer supported.` + : '' + throw new TypeError( + 'Duron: the telemetry option requires telemetry.tracerProvider, an OpenTelemetry ' + + `TracerProvider created by your application.${removedText} Create a TracerProvider ` + + 'with your exporter and Resource, then pass telemetry: { tracerProvider }, or remove ' + + 'the telemetry option to disable tracing. See ' + + 'https://duron-docs.pages.dev/docs/telemetry#migration-from-traceexporter', + ) +} + /** * Base configuration options for a Duron client instance. * These options control job fetching, concurrency, and recovery behavior. @@ -396,6 +434,7 @@ export class Client< * @param options - Configuration options for the client */ constructor(options: ClientOptions) { + const telemetry = assertTelemetryOptions(options.telemetry) this.#options = BaseOptionsSchema.parse(options) this.#id = options.id ?? globalThis.crypto.randomUUID() this.#database = options.database @@ -442,7 +481,7 @@ export class Client< // Telemetry is scoped to this client: the tracer comes from the provider the // application passed in. Without one, a ProxyTracerProvider with no delegate // gives a no-op tracer. It never reads the global tracer provider. - const tracerProvider = options.telemetry?.tracerProvider ?? new ProxyTracerProvider() + const tracerProvider = telemetry?.tracerProvider ?? new ProxyTracerProvider() this.#tracer = tracerProvider.getTracer(TRACER_NAME) } diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index c6ba543..b592075 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -77,16 +77,42 @@ function injectParentSpan(ctx: Context, parentSpan: Span | null): Context { return parentSpan ? trace.setSpan(ctx, parentSpan) : ctx } +/** + * The Duron ids of the job or step that a telemetry context belongs to. + * Duron passes them from its own state. It does not read them back from the + * span, because `span.attributes` is not part of the OpenTelemetry API and + * an application can use any API-compliant tracer provider. + */ +interface TelemetryIds { + jobId: string + stepId?: string +} + +/** + * The `duron.job.id` / `duron.step.id` attributes that handler spans inherit, + * merged under the caller's attributes (the caller's values win). + */ +function withDuronIds(ids: TelemetryIds, options: SpanOptions | undefined): SpanOptions { + return { + ...options, + attributes: { + 'duron.job.id': ids.jobId, + ...(ids.stepId ? { 'duron.step.id': ids.stepId } : {}), + ...options?.attributes, + }, + } +} + /** * Create a context-aware tracer wrapper that automatically injects the parent span. * This ensures spans created by external libraries (like AI SDK) are properly linked * to the current job/step trace hierarchy. */ -function createContextAwareTracer(tracer: Tracer, parentSpan: Span | null): Tracer { - // Extract duron.job.id and duron.step.id from parent span attributes for propagation - const parentJobId = parentSpan ? (parentSpan as any).attributes?.['duron.job.id'] : undefined - const parentStepId = parentSpan ? (parentSpan as any).attributes?.['duron.step.id'] : undefined - +function createContextAwareTracer( + tracer: Tracer, + parentSpan: Span | null, + ids: TelemetryIds, +): Tracer { return { startSpan(name: string, options?: SpanOptions, ctx?: Context): Span { // Always inject our parent span into the context, regardless of what context is passed. @@ -96,12 +122,7 @@ function createContextAwareTracer(tracer: Tracer, parentSpan: Span | null): Trac const baseContext = ctx ?? context.active() const effectiveContext = injectParentSpan(baseContext, parentSpan) // Propagate duron.job.id and duron.step.id so spans can be queried by job - const attributes = { - ...(parentJobId ? { 'duron.job.id': parentJobId } : {}), - ...(parentStepId ? { 'duron.step.id': parentStepId } : {}), - ...options?.attributes, - } - return tracer.startSpan(name, { ...options, attributes }, effectiveContext) + return tracer.startSpan(name, withDuronIds(ids, options), effectiveContext) }, // startActiveSpan has multiple overloads, we need to handle them all startActiveSpan unknown>( @@ -132,7 +153,7 @@ function createContextAwareTracer(tracer: Tracer, parentSpan: Span | null): Trac const baseContext = ctx ?? context.active() const effectiveContext = injectParentSpan(baseContext, parentSpan) - return tracer.startActiveSpan(name, options ?? {}, effectiveContext, callback) + return tracer.startActiveSpan(name, withDuronIds(ids, options), effectiveContext, callback) }, } as Tracer } @@ -140,29 +161,28 @@ function createContextAwareTracer(tracer: Tracer, parentSpan: Span | null): Trac /** * Create a TelemetryContext that wraps an OTel span. */ -function createTelemetryContext(span: Span | null, tracer: Tracer): TelemetryContext { - // Extract duron.job.id and duron.step.id from parent span attributes for propagation - const parentJobId = span ? (span as any).attributes?.['duron.job.id'] : undefined - const parentStepId = span ? (span as any).attributes?.['duron.step.id'] : undefined - +function createTelemetryContext( + span: Span | null, + tracer: Tracer, + ids: TelemetryIds, +): TelemetryContext { return { getActiveSpan(): Span | undefined { return span ?? undefined }, getTracer(_name: string): Tracer { // Return a context-aware tracer that automatically links spans to the current trace - return createContextAwareTracer(tracer, span) + return createContextAwareTracer(tracer, span, ids) }, startSpan(name: string, options?: { attributes?: Record }): Span { // Create a child span linked to the current span (job or step) - // Propagate duron.job.id and duron.step.id from parent so spans can be queried by job - const attributes = { - ...(parentJobId ? { 'duron.job.id': parentJobId } : {}), - ...(parentStepId ? { 'duron.step.id': parentStepId } : {}), - ...options?.attributes, - } + // Propagate duron.job.id and duron.step.id so spans can be queried by job const parentContext = span ? trace.setSpan(context.active(), span) : context.active() - return tracer.startSpan(name, { attributes }, parentContext) + return tracer.startSpan( + name, + withDuronIds(ids, { attributes: options?.attributes }), + parentContext, + ) }, recordMetric(name: string, value: number, attributes?: Record): void { if (span) { @@ -400,7 +420,9 @@ export class StepManager { abortSignal: AbortSignal, logger: Logger, ): Promise> { - const telemetryContext = createTelemetryContext(this.#jobSpan, this.#tracer) + const telemetryContext = createTelemetryContext(this.#jobSpan, this.#tracer, { + jobId: job.id, + }) return ActionContext.create(this, job, action, variables, abortSignal, logger, telemetryContext) } @@ -410,10 +432,10 @@ export class StepManager { createStepTelemetryContext(stepId: string): TelemetryContext { const stepSpan = this.#stepSpans.get(stepId) if (stepSpan) { - return createTelemetryContext(stepSpan, this.#tracer) + return createTelemetryContext(stepSpan, this.#tracer, { jobId: this.#jobId, stepId }) } // Fallback to job span if step span not found - return createTelemetryContext(this.#jobSpan, this.#tracer) + return createTelemetryContext(this.#jobSpan, this.#tracer, { jobId: this.#jobId }) } /** diff --git a/packages/duron/test/otel-integration.test.ts b/packages/duron/test/otel-integration.test.ts index 0a7ac0a..b2a2531 100644 --- a/packages/duron/test/otel-integration.test.ts +++ b/packages/duron/test/otel-integration.test.ts @@ -1,6 +1,19 @@ import { describe, expect, it } from 'bun:test' -import { trace } from '@opentelemetry/api' +import { + type Attributes, + type AttributeValue, + type Context, + context, + type Span, + type SpanContext, + type SpanOptions, + type SpanStatus, + TraceFlags, + type Tracer, + type TracerProvider as ApiTracerProvider, + trace, +} from '@opentelemetry/api' import { resourceFromAttributes } from '@opentelemetry/resources' import { InMemorySpanExporter, @@ -51,6 +64,124 @@ function parentSpanId(span: ReadableSpan): string | undefined { return span.parentSpanContext?.spanId } +interface RecordedSpan { + name: string + spanId: string + traceId: string + parentSpanId: string | undefined + scope: string + recorded: Attributes + ended: boolean +} + +let nextId = 0 +function randomHex(length: number): string { + nextId += 1 + return nextId.toString(16).padStart(length, '0') +} + +/** + * A minimal span written only against the `@opentelemetry/api` interfaces. + * It keeps its attributes in a private field, so Duron cannot read SDK-specific + * properties such as `span.attributes`. + */ +class MinimalSpan implements Span { + readonly #context: SpanContext + readonly #record: RecordedSpan + #attributes: Attributes = {} + + constructor(record: RecordedSpan, attributes: Attributes | undefined) { + this.#record = record + this.#context = { + traceId: record.traceId, + spanId: record.spanId, + traceFlags: TraceFlags.SAMPLED, + } + this.setAttributes(attributes ?? {}) + } + + spanContext(): SpanContext { + return this.#context + } + setAttribute(key: string, value: AttributeValue): this { + this.#attributes = { ...this.#attributes, [key]: value } + this.#record.recorded = this.#attributes + return this + } + setAttributes(attributes: Attributes): this { + for (const [key, value] of Object.entries(attributes)) { + if (value !== undefined) this.setAttribute(key, value) + } + return this + } + addEvent(): this { + return this + } + addLink(): this { + return this + } + addLinks(): this { + return this + } + setStatus(_status: SpanStatus): this { + return this + } + updateName(name: string): this { + this.#record.name = name + return this + } + end(): void { + this.#record.ended = true + } + isRecording(): boolean { + return !this.#record.ended + } + recordException(): void {} +} + +/** A minimal tracer provider written only against the `@opentelemetry/api` interfaces. */ +function createMinimalProvider() { + const spans: RecordedSpan[] = [] + const startSpan = (scope: string, name: string, options?: SpanOptions, ctx?: Context) => { + const parent = trace.getSpanContext(ctx ?? context.active()) + const record: RecordedSpan = { + name, + spanId: randomHex(16), + traceId: parent?.traceId ?? randomHex(32), + parentSpanId: parent?.spanId, + scope, + recorded: {}, + ended: false, + } + spans.push(record) + return new MinimalSpan(record, options?.attributes) + } + const provider: ApiTracerProvider = { + getTracer(scope: string): Tracer { + return { + startSpan: (name, options, ctx) => startSpan(scope, name, options, ctx), + startActiveSpan(name: string, ...args: unknown[]) { + const fn = args.pop() as (span: Span) => unknown + const [options, ctx] = args as [SpanOptions | undefined, Context | undefined] + const span = startSpan(scope, name, options, ctx) + return context.with(trace.setSpan(ctx ?? context.active(), span), fn, undefined, span) + }, + } as Tracer + }, + } + return { provider, spans } +} + +async function waitForRecorded(spans: RecordedSpan[], name: string): Promise { + const deadline = Date.now() + 5_000 + while (Date.now() < deadline) { + const span = spans.find((s) => s.name === name && s.ended) + if (span) return span + await new Promise((resolve) => setTimeout(resolve, 10)) + } + throw new Error(`span ${name} was not ended within 5000ms`) +} + const simpleAction = defineAction()({ name: 'simple-action', version: '1.0.0', @@ -67,6 +198,7 @@ const stepAction = defineAction()({ input: z.object({ value: z.number() }), output: z.object({ result: z.number() }), handler: async (ctx) => { + ctx.telemetry.startSpan('action-operation').end() const outer = await ctx.step('outer', async ({ step, telemetry }) => { const custom = telemetry.startSpan('custom-operation', { attributes: { 'custom.input': ctx.input.value }, @@ -76,6 +208,7 @@ const stepAction = defineAction()({ const handlerSpan = telemetry.getTracer('app-library').startSpan('library-operation') handlerSpan.end() + telemetry.getTracer('app-library').startActiveSpan('library-active', (span) => span.end()) return step('inner', async () => ({ multiplied: ctx.input.value * 2 })) }) @@ -92,7 +225,7 @@ const actions = { simpleAction, stepAction } async function withClients( fn: ( createClient: (telemetry?: { - tracerProvider: TracerProvider + tracerProvider: ApiTracerProvider }) => Promise>, ) => Promise, ) { @@ -164,17 +297,32 @@ describe('OpenTelemetry with an application tracer provider', () => { const inner = await waitForSpan(exporter, 'step:inner') const custom = await waitForSpan(exporter, 'custom-operation') const library = await waitForSpan(exporter, 'library-operation') + const libraryActive = await waitForSpan(exporter, 'library-active') + const actionOperation = await waitForSpan(exporter, 'action-operation') const traceId = jobSpan.spanContext().traceId - for (const span of [outer, inner, custom, library]) { + for (const span of [outer, inner, custom, library, libraryActive, actionOperation]) { expect(span.spanContext().traceId).toBe(traceId) } expect(parentSpanId(outer)).toBe(jobSpan.spanContext().spanId) expect(parentSpanId(inner)).toBe(outer.spanContext().spanId) expect(parentSpanId(custom)).toBe(outer.spanContext().spanId) expect(parentSpanId(library)).toBe(outer.spanContext().spanId) + expect(parentSpanId(libraryActive)).toBe(outer.spanContext().spanId) + expect(parentSpanId(actionOperation)).toBe(jobSpan.spanContext().spanId) expect(custom.attributes['custom.input']).toBe(7) expect(custom.attributes['custom.output']).toBe(28) + + // Handler spans carry the job and step ids of their parent. + const jobId = jobSpan.attributes['duron.job.id'] + const outerStepId = outer.attributes['duron.step.id'] + expect(outerStepId).toBeString() + for (const span of [custom, library, libraryActive]) { + expect(span.attributes['duron.job.id']).toBe(jobId) + expect(span.attributes['duron.step.id']).toBe(outerStepId) + } + expect(actionOperation.attributes['duron.job.id']).toBe(jobId) + expect(actionOperation.attributes['duron.step.id']).toBeUndefined() }), { timeout: 60_000 }, ) @@ -215,7 +363,8 @@ describe('OpenTelemetry without a telemetry option', () => { () => withClients(async (createClient) => { const global = createAppTelemetry('global-service') - trace.setGlobalTracerProvider(global.provider) + // A false return means another global was already registered: the test would prove nothing. + expect(trace.setGlobalTracerProvider(global.provider)).toBe(true) try { const client = await createClient() expect(client.tracer.startSpan('probe').isRecording()).toBe(false) @@ -232,3 +381,68 @@ describe('OpenTelemetry without a telemetry option', () => { { timeout: 60_000 }, ) }) + +describe('OpenTelemetry with a provider that implements only the API', () => { + it( + 'creates the span hierarchy and propagates job and step ids without SDK internals', + () => + withClients(async (createClient) => { + const { provider, spans } = createMinimalProvider() + const client = await createClient({ tracerProvider: provider }) + + const { jobId } = await runJob(client, 'stepAction', 5) + + const jobSpan = await waitForRecorded(spans, 'job:step-action') + const outer = await waitForRecorded(spans, 'step:outer') + const inner = await waitForRecorded(spans, 'step:inner') + const custom = await waitForRecorded(spans, 'custom-operation') + const library = await waitForRecorded(spans, 'library-operation') + const libraryActive = await waitForRecorded(spans, 'library-active') + const actionOperation = await waitForRecorded(spans, 'action-operation') + + expect(jobSpan.scope).toBe('duron') + expect(jobSpan.recorded['duron.job.id']).toBe(jobId) + expect(jobSpan.parentSpanId).toBeUndefined() + expect(outer.parentSpanId).toBe(jobSpan.spanId) + expect(inner.parentSpanId).toBe(outer.spanId) + for (const span of [custom, library, libraryActive]) { + expect(span.parentSpanId).toBe(outer.spanId) + expect(span.traceId).toBe(jobSpan.traceId) + expect(span.recorded['duron.job.id']).toBe(jobId) + expect(span.recorded['duron.step.id']).toBe(outer.recorded['duron.step.id']) + } + expect(outer.recorded['duron.step.id']).toBeString() + expect(actionOperation.parentSpanId).toBe(jobSpan.spanId) + expect(actionOperation.recorded['duron.job.id']).toBe(jobId) + expect(actionOperation.recorded['duron.step.id']).toBeUndefined() + }), + { timeout: 60_000 }, + ) +}) + +describe('Telemetry option validation', () => { + it.each([ + ['an old traceExporter config', { traceExporter: {} }], + ['an empty telemetry object', {}], + ['a tracerProvider without getTracer', { tracerProvider: {} }], + [ + 'a tracerProvider with removed options', + { tracerProvider: trace.getTracerProvider(), serviceName: 'x' }, + ], + ])('throws a migration error for %s', async (_case, telemetry) => { + const { adapter, deleteDb } = await pgliteFactory.create({}) + try { + expect( + () => + new Client({ + database: adapter, + actions, + telemetry: telemetry as any, + logger: 'error', + }), + ).toThrow(/telemetry\.tracerProvider.*migration-from-traceexporter/s) + } finally { + await deleteDb() + } + }) +}) From 3348c95c843fb32bf24cb625c6d54953f4140f81 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Mon, 30 Nov 2026 21:42:15 -0300 Subject: [PATCH 061/100] fix(test): run duron tests without --concurrent 'bun run test' used 'bun test --concurrent', which failed ~221 tests (shared native resources and time-sensitive lifecycle budgets); CI already used plain 'bun test'. 'bun run test' now passes 546/75/0. AGENTS.md updated. --- AGENTS.md | 4 ++-- packages/duron/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6371c6c..9c14de1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ bun run lint # oxlint check bun run lint:fix # oxlint fix bun run fmt:check # oxfmt check bun run fmt # oxfmt fix -bun test # runs packages/duron tests with --concurrent +bun test # runs packages/duron tests (same as `bun run test`) # Build bun run build # all packages @@ -61,7 +61,7 @@ bun run build:docs # docs only - Framework: `bun:test` - Tests live in `packages/duron/test/*.test.ts` - Run single file: `bun test specific.test.ts` -- Core tests run with `--concurrent` via `bun test` in `packages/duron/package.json` +- Core tests run with plain `bun test` (no `--concurrent`: many suites share native resources and time-sensitive lifecycle budgets, and fail under cross-file concurrency) - `test/docker.ts` auto-creates a Docker container on port 5440 for PostgreSQL tests. Docker must be running. - Image: `DURON_TEST_POSTGRES_IMAGE` (default `postgres:19-alpine`). The suite is also verified on `postgres:16-alpine`. - Container: `duron-postgres-test-` (for example `duron-postgres-test-postgres-19-alpine`), so a changed image never reuses a container of another version. `DURON_TEST_POSTGRES_CONTAINER` overrides the name; an existing container must run the selected image. diff --git a/packages/duron/package.json b/packages/duron/package.json index c03e66d..41fc2ed 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -76,7 +76,7 @@ "build": "rm -rf dist && tsc --project tsconfig.node.json", "dev": "tsc --watch --project tsconfig.node.json", "prepublishOnly": "bun run build", - "test": "bun test --concurrent", + "test": "bun test", "generate:postgres": "bunx --bun drizzle-kit generate --config ./drizzle.config.ts", "typecheck": "bun check --no-script" }, From b3544498f9b61ca0bb5ff33a3afa6296582b9dda Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 00:13:46 -0300 Subject: [PATCH 062/100] fix: retry claim conflicts and keep draining job bursts R1: a claim rejected with SQLSTATE 40001 (statement or COMMIT) is retried up to 3 times, each in a new SERIALIZABLE transaction after a 1-20 ms random delay. Retried conflicts are logged at debug level; only an exhausted retry surfaces the original error (and only then does the WorkerDiscovery cooldown apply). Claims still commit before they are returned, and a rolled-back attempt publishes nothing. R2: coalesced hints add one job each to the pending automatic request (capped at B) instead of taking the maximum, and an automatic claim that returns its full batch queues another automatic request of B, subject to room, cooldown and due recovery. A Promise.all burst of 60 jobs (PGlite, hybrid, pullInterval 5000, B 10) now completes in ~0.15 s instead of 29.7 s. --- packages/docs/content/docs/client-api.mdx | 4 +- packages/docs/content/docs/multi-worker.mdx | 6 +- packages/duron/src/adapters/postgres/base.ts | 46 +++++- packages/duron/src/worker-discovery.ts | 18 ++- packages/duron/test/cancel-storage.test.ts | 13 +- packages/duron/test/claim-isolation.test.ts | 79 +++++++++- packages/duron/test/claim-pglite.test.ts | 147 +++++++++++++++++++ packages/duron/test/client.test.ts | 2 +- packages/duron/test/nested-steps.test.ts | 3 +- packages/duron/test/worker-discovery.test.ts | 147 +++++++++++++++++-- 10 files changed, 428 insertions(+), 37 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 173c8dc..a10eba4 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -113,7 +113,7 @@ const client = new Client({ database, waitReadTimeout: 3000 }) For both schedules, a positive finite interval is floored and clamped to `1–2,147,483,647`; other accepted values use `5000`. `getConfig()` still returns the value you passed. -Periodic discovery is not reset or postponed by notifications or `fetch()` calls. Missed ticks are not replayed: while a discovery is running, further demand is merged into one pending request. After any discovery failure (for example, a `40001` serialization failure from a concurrent claim), every trigger waits one interval before the next claim, including notifications and queued `fetch()` calls. The failed claim is not replayed; the next claim is a new one. +Periodic discovery is not reset or postponed by notifications or `fetch()` calls. Missed ticks are not replayed: while a discovery is running, further demand is merged into one pending request. After any discovery failure (for example, a `40001` serialization failure from a concurrent claim that persisted through the claim's retries), every trigger waits one interval before the next claim, including notifications and queued `fetch()` calls. The failed claim is not replayed; the next claim is a new one. ```ts { @@ -125,7 +125,7 @@ Periodic discovery is not reset or postponed by notifications or `fetch()` calls **Optional.** Defaults to `10`. Two meanings: -- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Automatic requests from notifications claim one job; startup and periodic requests claim up to the remaining room. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. +- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Each notification that arrives while a discovery is running adds one job to the next automatic request, and startup and periodic requests ask for B; either way a request claims at most the remaining room. An automatic claim that returns as many jobs as it asked for is followed at once by another automatic request of B (it still waits for room and for a cooldown), so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. - **Default `fetch()` batch.** `fetch()` without `batchSize` passes this value unchanged. B is not the number of handlers that run at once. That is `actionConcurrencyLimit` per action, so with the defaults (B = 10, `actionConcurrencyLimit` = 100) at most ten automatically claimed jobs are outstanding. SQL group admission (`groupConcurrencyLimit` or `groups.concurrency`) is a separate limit across all workers. Jobs claimed by `fetch()` count toward B, and a `fetch()` batch can exceed B; automatic claiming then pauses until enough work settles. B limits claim admission only. It does not bound the rows that recovery examines, the backlog that manual calls create, or the total query rate. diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 8e2c613..4776edf 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -224,7 +224,9 @@ process.on('SIGINT', async () => { The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` transaction per fetch. The claim query itself is unchanged: the latest unexpired job for each action name and group key supplies the concurrency limit, candidates are row-locked with `SKIP LOCKED`, and the oldest eligible jobs are claimed first. Claimed jobs are returned, and their handlers can start, only after the transaction commits. -When concurrent claims from different workers would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. Duron does not retry inside the fetch and does not turn the error into an empty result: a manual `client.fetch()` or `adapter.fetch()` call rejects with the original error. Automatic discovery logs the failure once, waits one `pullInterval`, and then makes a new claim; notifications and queued `client.fetch()` calls also wait for that cooldown. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so occasional conflicts between unrelated groups are possible. Handle the rejection of a `fetch()` you start without awaiting. +When concurrent claims from different workers would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so conflicts between unrelated groups are possible, for example when every worker claims at the same time after a notification. + +The fetch retries a claim rejected with `40001` up to 3 times. Each retry is a new transaction that starts after a random delay of 1–20 ms, so it sees the claims that committed in the meantime. Retried conflicts are logged at debug level. Only when the last retry also fails does the fetch reject with the original error: a manual `client.fetch()` or `adapter.fetch()` call rejects, and automatic discovery logs the failure once, waits one `pullInterval`, and then makes a new claim; notifications and queued `client.fetch()` calls also wait for that cooldown. Other claim errors are not retried. Handle the rejection of a `fetch()` you start without awaiting. Limits of this protection: @@ -256,7 +258,7 @@ This coordination is local to one Client. Other Clients, and direct calls such a Cancelling a job in the database archives the job as `cancelled` and archives every one of its steps as `cancelled`, including steps that had already completed or failed. On PostgreSQL, a cancellation that commits keeps every step committed before it took the job, and no step for that job can be created while it runs. A step creation that arrives while the cancellation holds the job waits for it and then returns `null` (the existing "job is not active" result) instead of failing with a foreign-key error. A step creation that took the job first makes the cancellation wait, and its step is archived as `cancelled`. A step status write that reaches its step first succeeds and is then overwritten to `cancelled`; one that arrives later waits and returns `false`. -The same row lock orders `cancelJob`, `completeJob` and `failJob` on one job: the first to lock it wins and the others return `false`. Recovery skips a job that one of them holds. A claim also skips a `created` job that a cancellation holds, and a claim whose snapshot predates a committed cancellation of its candidate is rejected with `40001` as described above. +The same row lock orders `cancelJob`, `completeJob` and `failJob` on one job: the first to lock it wins and the others return `false`. Recovery skips a job that one of them holds. A claim also skips a `created` job that a cancellation holds, and a claim whose snapshot predates a committed cancellation of its candidate fails with `40001` and is retried as described above. A call that waited rechecks its existing conditions against the latest version of the job. This changes two outcomes when recovery requeues a job whose owner looks dead: diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index bfdf8ec..2c3968b 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -83,6 +83,21 @@ function jsonParam(value: unknown, column: PgColumn): SQL { : sql`${sql.param(value, column)}::jsonb` } +/** Retries of a claim after a serialization failure (SQLSTATE 40001). */ +const CLAIM_CONFLICT_RETRIES = 3 + +/** `error` or its first cause with SQLSTATE 40001 (serialization_failure), if any. */ +function serializationFailure(error: unknown): Error | undefined { + const seen = new Set() + let cause = error + while (cause instanceof Error && !seen.has(cause)) { + seen.add(cause) + if ('code' in cause && cause.code === '40001') return cause + cause = cause.cause + } + return undefined +} + export interface PruneSchedulerConfig { olderThan: string | Date | number intervalMs: number @@ -1170,13 +1185,38 @@ export abstract class PostgresBaseAdapter< * * Each claim runs the unchanged row-locking claim query in its own SERIALIZABLE * transaction, so concurrent claimants cannot both commit admissions from a stale - * group count. Claimed jobs are returned only after COMMIT succeeds. Statement and - * COMMIT errors, including serialization failures (SQLSTATE 40001), propagate - * without retry. SQL `now()` is the transaction's BEGIN time. + * group count. Claimed jobs are returned only after COMMIT succeeds. SQL `now()` is + * the transaction's BEGIN time. + * + * A serialization failure (SQLSTATE 40001, from the claim statement or COMMIT) always + * rolls the whole transaction back, so the claim is retried up to + * {@link CLAIM_CONFLICT_RETRIES} times in a new transaction after a 1-20 ms random + * delay. Retried conflicts are logged at debug level. After the last retry, the + * original 40001 error propagates. Other statement and COMMIT errors propagate + * without retry. * * @returns Promise resolving to an array of fetched jobs */ protected async _fetch({ batch }: FetchOptions) { + for (let attempt = 1; ; attempt++) { + try { + return await this._claim(batch) + } catch (error) { + const conflict = serializationFailure(error) + if (attempt > CLAIM_CONFLICT_RETRIES || !conflict) throw error + // Log the driver's 40001 error, not a wrapper that repeats the claim SQL. + this.logger?.debug( + { err: conflict, attempt, retries: CLAIM_CONFLICT_RETRIES }, + 'Retrying claim conflict (SQLSTATE 40001)', + ) + const delay = 1 + Math.floor(Math.random() * 20) + await new Promise((resolve) => setTimeout(resolve, delay)) + } + } + } + + /** One claim attempt in its own SERIALIZABLE transaction. */ + private async _claim(batch: number): Promise { let claim: Promise | undefined try { return await this.db.transaction( diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index c865af9..e10026a 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -69,7 +69,10 @@ const notAccepting = () => new Error('Lifecycle is not accepting work') * - One actual discovery chain at a time across startup, periodic safety, hints and manual * fetch calls. A chain is: optional due recovery, then at most one Adapter.fetch claim. * - At most one coalesced automatic request. Requests are served FIFO among eligible ones; - * cooldown and automatic claim room decide eligibility. + * cooldown and automatic claim room decide eligibility. Each hint adds one job to its + * demand and startup/periodic requests raise it to B (never above B). An automatic claim + * that returns its full batch queues another automatic request of B, so a backlog keeps + * draining without waiting for the periodic tick. * - Automatic claims use only the room left under a Client-wide ceiling of B outstanding * local claims (claimed, queued, running and finalizing work, plus reservations). Manual * calls keep their own batch and returned jobs and may exceed B. @@ -121,7 +124,7 @@ export class WorkerDiscovery { this.#pump() } - /** Merge automatic demand. Hints request one job; startup/periodic request B. */ + /** Merge automatic demand. Each hint adds one job; startup/periodic request B. */ request(trigger: DiscoveryTrigger): void { if (!this.#options.automatic || this.#stopped || !this.#options.lifecycle.accepting) return this.#mergeAutomatic(trigger === 'hint' ? 1 : this.#batch, [trigger]) @@ -161,9 +164,10 @@ export class WorkerDiscovery { return this.#batch - this.#local.size - this.#reserved } + // Demand adds up (one job per hint, a re-queued request's own batch) and is capped at B. #mergeAutomatic(batch: number, triggers: Iterable): void { if (this.#automatic) { - this.#automatic.batch = Math.max(this.#automatic.batch, batch) + this.#automatic.batch = Math.min(this.#batch, this.#automatic.batch + batch) for (const trigger of triggers) this.#automatic.triggers.add(trigger) return } @@ -265,7 +269,13 @@ export class WorkerDiscovery { } finally { claimed.release() } - if (request.kind === 'manual') request.resolve(claimed.jobs) + if (request.kind === 'manual') { + request.resolve(claimed.jobs) + } else if (claimed.jobs.length >= batch && this.#open) { + // A full claim suggests more claimable work. The follow-up waits for room, + // cooldown and due recovery like any automatic request. + this.#mergeAutomatic(this.#batch, request.triggers) + } } catch (error) { this.#cooldownUntil = monotonicMs() + this.#interval if (request.kind === 'manual') { diff --git a/packages/duron/test/cancel-storage.test.ts b/packages/duron/test/cancel-storage.test.ts index a564a73..3120175 100644 --- a/packages/duron/test/cancel-storage.test.ts +++ b/packages/duron/test/cancel-storage.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'bun:test' +import pino from 'pino' import postgres from 'postgres' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' @@ -760,11 +761,15 @@ suite('Native PostgreSQL cancellation storage', () => { ) it( - 'J3: a claim whose snapshot predates a committed cancellation rejects with 40001 and publishes nothing', + 'J3: a claim whose snapshot predates a committed cancellation conflicts (40001), retries and publishes nothing', async () => { await withDatabase(async (db) => { const c = await db.adapter('c') const f = await db.adapter('f') + const conflicts: Array> = [] + f.setLogger( + pino({ level: 'debug' }, { write: (line: string) => conflicts.push(JSON.parse(line)) }), + ) const jobId = await createJob(c) await db.installClaimBarrier('f') await db.hold() @@ -774,7 +779,11 @@ suite('Native PostgreSQL cancellation storage', () => { await db.waitingAtAdvisory('f') expect(fulfilment(await db.observe(c.cancelJob({ jobId })))).toBe(true) await db.release() - expect(sqlState(rejection(await claim))).toBe('40001') + // The stale attempt rolls back with 40001; the retry no longer sees the job. + expect(fulfilment(await claim)).toEqual([]) + expect( + conflicts.filter((e) => /claim conflict/.test(e['msg'])).map((e) => e['err']['code']), + ).toEqual(['40001']) const job = await db.job(jobId) expect(job.active).toBeNull() expect(job.archive?.['status']).toBe('cancelled') diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index b77f60b..4e0fee1 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'bun:test' +import pino from 'pino' import postgres from 'postgres' import { z } from 'zod' @@ -42,6 +43,18 @@ function fulfilment(settled: Settled): T { return (settled as { value: T }).value } +// Records the adapter's retried claim conflicts (debug level) and its error-level logs. +function captureLogs(adapter: PostgresAdapter) { + const entries: Array> = [] + adapter.setLogger( + pino({ level: 'debug' }, { write: (line: string) => entries.push(JSON.parse(line)) }), + ) + return { + conflicts: () => entries.filter((entry) => /claim conflict/.test(entry['msg'])), + errors: () => entries.filter((entry) => entry['level'] >= 50), + } +} + function driverOf(adapter: PostgresAdapter): postgres.Sql { return (adapter as unknown as { db: { $client: postgres.Sql } }).db.$client } @@ -282,11 +295,12 @@ const schedules = [ const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip suite('Native PostgreSQL claim admission', () => { for (const schedule of schedules) { - it(`rejects a stale overlapping Adapter.fetch instead of exceeding group capacity (${schedule.name})`, async () => { + it(`retries a stale overlapping Adapter.fetch instead of exceeding group capacity (${schedule.name})`, async () => { const db = await claimDatabase() try { const a = db.adapter('claim-a') const b = db.adapter('claim-b') + const logs = captureLogs(b) await a.start() await b.start() await createJobs(a, schedule.jobs, schedule.limit) @@ -306,7 +320,12 @@ suite('Native PostgreSQL claim admission', () => { await db.release() const result = await stale expect(await db.activeCount()).toBe(schedule.limit) - expect(sqlState(rejection(result))).toBe('40001') + // The stale attempt rolled back with 40001; the retry sees the full group. + expect(fulfilment(result)).toEqual([]) + expect(logs.conflicts().map((entry) => [entry['attempt'], entry['err']['code']])).toEqual([ + [1, '40001'], + ]) + expect(logs.errors()).toEqual([]) } catch (error) { db.recordFailure(error) throw error @@ -627,7 +646,7 @@ suite('Native PostgreSQL claim admission', () => { } }, 30_000) - it('rejects a distinct-row write skew at COMMIT without publishing its provisional claim', async () => { + it('retries a distinct-row write skew rejected at COMMIT without publishing its provisional claim', async () => { const db = await claimDatabase() const holder = postgres(db.url, { max: 1, connection: { statement_timeout: 5_000 } }) // Test-owned gates live outside try so finally can always release them. @@ -637,6 +656,7 @@ suite('Native PostgreSQL claim admission', () => { try { const a = db.adapter('claim-a') const b = db.adapter('claim-b', 1) + const logs = captureLogs(b) await a.start() await b.start() const [first, second] = await createJobs(a, 2, 1) @@ -668,10 +688,13 @@ suite('Native PostgreSQL claim admission', () => { const resultB = await claimB const final = await db.admin`SELECT id, status FROM duron.jobs_active ORDER BY created_at, id` expect(final.map((row) => row['status'])).toEqual(['active', 'created']) - // The original driver COMMIT error propagates unwrapped and unconverted. - const commitError = rejection(resultB) as { code?: string; detail?: string } - expect(commitError.code).toBe('40001') - expect(commitError.detail).toContain('during commit attempt') + // B's COMMIT failed with 40001 and published nothing; its retry, a new transaction, + // sees A's claim and the group at its limit. + expect(fulfilment(resultB)).toEqual([]) + const conflicts = logs.conflicts() + expect(conflicts).toHaveLength(1) + expect(conflicts[0]!['err']['code']).toBe('40001') + expect(conflicts[0]!['err']['detail']).toContain('during commit attempt') // The same single pooled B session is reusable at its ordinary isolation. expect(await b.fetch({ batch: 1 })).toEqual([]) const driver = driverOf(b) @@ -863,7 +886,8 @@ suite('Native PostgreSQL claim admission', () => { await Bun.sleep(50) expect(started).toHaveLength(2) expect(await db.activeCount()).toBe(2) - expect(sqlState(rejection(result))).toBe('40001') + // The stale claim conflicted (40001) and its retry found the group at its limit. + expect(fulfilment(result)).toEqual([]) handlers.resolve() await eventually(async () => (await db.activeCount()) === 0) } catch (error) { @@ -876,4 +900,43 @@ suite('Native PostgreSQL claim admission', () => { await db.cleanup() } }, 30_000) + + it('retries natural conflicts between concurrent claimers and claims every job exactly once', async () => { + const db = await claimDatabase() + try { + const claimers = ['claim-a', 'claim-b', 'claim-c', 'claim-d'].map((name) => { + const adapter = db.adapter(name) + return { adapter, logs: captureLogs(adapter) } + }) + for (const { adapter } of claimers) await adapter.start() + const ids = await createJobs(claimers[0]!.adapter, 60, 1_000) + const claimed: string[] = [] + const failures: unknown[] = [] + // Every claimer claims in a tight loop until a claim comes back empty. + await Promise.all( + claimers.map(async ({ adapter }) => { + for (;;) { + const jobs = await adapter.fetch({ batch: 2 }).catch((error: unknown) => { + failures.push(error) + return null + }) + if (jobs === null) continue + if (jobs.length === 0) return + claimed.push(...jobs.map((job) => job.id)) + } + }), + ) + expect(claimed.toSorted()).toEqual(ids.toSorted()) + expect(await db.activeCount()).toBe(60) + // Conflicts are retried, so none surfaces (4 consecutive conflicts are not expected). + expect(failures.map(sqlState)).toEqual([]) + const conflicts = claimers.flatMap(({ logs }) => logs.conflicts()) + expect(conflicts.every((entry) => entry['err']['code'] === '40001')).toBe(true) + } catch (error) { + db.recordFailure(error) + throw error + } finally { + await db.cleanup() + } + }, 30_000) }) diff --git a/packages/duron/test/claim-pglite.test.ts b/packages/duron/test/claim-pglite.test.ts index c23373e..34cfb17 100644 --- a/packages/duron/test/claim-pglite.test.ts +++ b/packages/duron/test/claim-pglite.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'bun:test' import type { PGlite } from '@electric-sql/pglite' +import pino from 'pino' import { z } from 'zod' import { defineAction } from '../src/action.js' @@ -33,6 +34,51 @@ function engineOf(adapter: PGLiteAdapter): PGlite { return (adapter as unknown as { db: { $client: PGlite } }).db.$client } +// Owned test-only fault: the claim UPDATE raises SQLSTATE 40001 for the first `failures` +// attempts (all attempts when null). A sequence counts attempts across rollbacks. +async function injectSerializationFailures(engine: PGlite, failures: number | null) { + await engine.exec(` + CREATE SEQUENCE duron.claim_test_attempts; + CREATE FUNCTION duron.claim_test_conflict() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF nextval('duron.claim_test_attempts') <= ${failures ?? 1_000_000} THEN + RAISE EXCEPTION 'injected claim conflict' USING ERRCODE = '40001'; + END IF; + RETURN NULL; + END $$; + CREATE TRIGGER claim_test_conflict AFTER UPDATE ON duron.jobs_active + FOR EACH STATEMENT EXECUTE FUNCTION duron.claim_test_conflict(); + `) + return async () => { + await engine.exec('DROP TRIGGER claim_test_conflict ON duron.jobs_active') + } +} + +async function claimAttempts(engine: PGlite): Promise { + const rows = await engine.query<{ value: string }>( + 'SELECT last_value::text AS value FROM duron.claim_test_attempts', + ) + return Number(rows.rows[0]!.value) +} + +function captureLogs() { + const entries: Array> = [] + const logger = pino( + { level: 'debug' }, + { write: (line: string) => entries.push(JSON.parse(line)) }, + ) + return { + logger, + at: (level: number) => entries.filter((entry) => entry['level'] === level), + conflicts: () => entries.filter((entry) => /claim conflict/.test(entry['msg'])), + } +} + +function sqlState(error: unknown): unknown { + const value = error as { code?: unknown; cause?: { code?: unknown } } | null + return value?.code ?? value?.cause?.code +} + describe('PGLite claim transaction', () => { it('claims inside a SERIALIZABLE transaction without leaking the isolation level', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) @@ -103,6 +149,107 @@ describe('PGLite claim transaction', () => { } }) + it('retries a 40001 claim conflict in a fresh transaction and claims the job once', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + adapter.setId('claim-pglite') + const logs = captureLogs() + adapter.setLogger(logs.logger) + try { + await adapter.start() + const engine = engineOf(adapter) + await injectSerializationFailures(engine, 2) + const [id] = await createJobs(adapter, 1, 1) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([id!]) + expect(await claimAttempts(engine)).toBe(3) + // Each retried conflict is logged at debug level; nothing is logged at error level. + const conflicts = logs.conflicts() + expect(conflicts.map((entry) => [entry['level'], entry['attempt']])).toEqual([ + [20, 1], + [20, 2], + ]) + expect(conflicts.every((entry) => sqlState(entry['err']) === '40001')).toBe(true) + expect(logs.at(50)).toEqual([]) + // Claimed exactly once: one active row, and no further claim finds it. + const statuses = await engine.query<{ status: string }>( + 'SELECT status FROM duron.jobs_active', + ) + expect(statuses.rows.map((row) => row.status)).toEqual(['active']) + expect(await adapter.fetch({ batch: 1 })).toEqual([]) + } finally { + await adapter.stop() + } + }) + + it('surfaces a persistent 40001 after 3 retries and claims nothing', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + adapter.setId('claim-pglite') + const logs = captureLogs() + adapter.setLogger(logs.logger) + try { + await adapter.start() + const engine = engineOf(adapter) + const disarm = await injectSerializationFailures(engine, null) + const [id] = await createJobs(adapter, 1, 1) + const failed = await adapter.fetch({ batch: 1 }).then( + () => null, + (error: unknown) => error, + ) + expect(sqlState(failed)).toBe('40001') + // One attempt plus 3 retries; the final failure is not logged as a retried conflict. + expect(await claimAttempts(engine)).toBe(4) + expect(logs.conflicts().map((entry) => entry['attempt'])).toEqual([1, 2, 3]) + expect(logs.at(50).map((entry) => entry['msg'])).toEqual(['Error in Adapter.fetch()']) + const statuses = await engine.query<{ status: string }>( + 'SELECT status FROM duron.jobs_active', + ) + expect(statuses.rows.map((row) => row.status)).toEqual(['created']) + await disarm() + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([id!]) + } finally { + await adapter.stop() + } + }) + + it('does not pause Client discovery for a single claim conflict', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + const logs = captureLogs() + let ran = 0 + const action = defineAction()({ + name: 'claim-conflict', + input: z.object({}), + output: z.object({}), + handler: async () => { + ran++ + return {} + }, + }) + const client = new Client({ + database: adapter, + actions: { claimConflict: action }, + syncPattern: 'push', + // A discovery failure would pause every trigger for this long. + pullInterval: 60_000, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: logs.logger, + }) + try { + await client.start() + await injectSerializationFailures(engineOf(adapter), 1) + const id = await client.runAction('claimConflict', {}) + const end = performance.now() + 5_000 + while ((await adapter.getJobStatus(id))?.status !== 'completed') { + if (performance.now() >= end) throw new Error('job was not claimed after one conflict') + await Bun.sleep(10) + } + expect(ran).toBe(1) + expect(logs.conflicts()).toHaveLength(1) + expect(logs.at(50)).toEqual([]) + } finally { + await client.stop() + } + }, 15_000) + it('keeps customized _fetch override dispatch for Adapter.fetch and Client.fetch', async () => { class CountingAdapter extends PGLiteAdapter { calls = 0 diff --git a/packages/duron/test/client.test.ts b/packages/duron/test/client.test.ts index f7f202b..0db3530 100644 --- a/packages/duron/test/client.test.ts +++ b/packages/duron/test/client.test.ts @@ -435,7 +435,7 @@ function runClientTests(adapterFactory: AdapterFactory) { const jobId = await client.runAction('slowAction', {}) // Start processing. A cancel that lands after the SERIALIZABLE claim's - // snapshot can reject the claim with SQLSTATE 40001. + // snapshot makes the claim retry; only a persistent conflict rejects with 40001. const fetching = client.fetch({ batchSize: 10 }).then( () => undefined, (error: { code?: string; cause?: { code?: string } }) => { diff --git a/packages/duron/test/nested-steps.test.ts b/packages/duron/test/nested-steps.test.ts index 639bf7e..75c625f 100644 --- a/packages/duron/test/nested-steps.test.ts +++ b/packages/duron/test/nested-steps.test.ts @@ -691,7 +691,8 @@ function runNestedStepsTests(adapterFactory: AdapterFactory) { const jobId = await client.runAction('deeplyNestedAction', {}) // Start fetching but cancel quickly. A cancel that lands after the - // SERIALIZABLE claim's snapshot can reject the claim with SQLSTATE 40001. + // SERIALIZABLE claim's snapshot makes the claim retry; only a persistent + // conflict rejects with SQLSTATE 40001. const fetchPromise = client.fetch({ batchSize: 10 }).then( () => undefined, (error: { code?: string; cause?: { code?: string } }) => { diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index 36a55c3..5a25ac7 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -509,34 +509,153 @@ for (const factory of factories) { TEST_MS, ) + for (const [hints, followUp] of [ + [3, 3], + [6, 4], + ] as const) { + it( + `coalesces ${hints} hints into one follow-up of one job per hint, capped at B (held)`, + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + try { + const action = defineAction()({ name: 'hinted', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { hinted: action }, + syncPattern: 'push', + pullInterval: 60_000, + batchSize: 4, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await eventually(() => fetch.held === 1, 'startup pass is held') + for (let i = 0; i < hints; i++) { + instance.adapter.emit('job-available', { jobId: `hint-${i}` }) + } + fetch.releaseNext() + await eventually(() => fetch.batches.length === 2, 'one follow-up') + fetch.releaseAll() + await Bun.sleep(50) + // Both claims return empty (not full), so no further automatic claim follows. + expect(fetch.batches).toEqual([4, followUp]) + expect(fetch.maxActive).toBe(1) + } finally { + fetch.releaseAll() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + } + it( - 'coalesces hint-only demand into one single-job follow-up (held)', + 'follows a full automatic claim with another one until a claim is not full (public-only)', async () => { const instance = await factory.create() let client: Client | null = null - const fetch = holdFetch(instance.adapter) try { - const action = defineAction()({ name: 'hinted', handler: async () => ({}) }) + let ran = 0 + const action = defineAction()({ + name: 'backlog-drain', + handler: async () => { + ran++ + return {} + }, + }) client = new Client({ database: instance.adapter, - actions: { hinted: action }, + actions: { 'backlog-drain': action }, syncPattern: 'push', + // No periodic tick and no hint during the test: only follow-ups drain the backlog. pullInterval: 60_000, - batchSize: 4, + batchSize: 2, recoverJobsOnStart: false, + recoverJobsInterval: 0, logger: 'silent', }) + expect(await instance.adapter.start()).toBe(true) + const ids: string[] = [] + for (let i = 0; i < 5; i++) { + ids.push( + (await instance.adapter.createJob({ + queue: action.name, + groupKey: '@default', + input: {}, + timeoutMs: 10_000, + checksum: action.checksum, + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }))!, + ) + } + const batches: number[] = [] + const claimed: number[] = [] + const real = instance.adapter.fetch.bind(instance.adapter) + instance.adapter.fetch = async (options) => { + batches.push(options.batch) + const jobs = await real(options) + claimed.push(jobs.length) + return jobs + } expect(await client.start()).toBe(true) - await eventually(() => fetch.held === 1, 'startup pass is held') - for (let i = 0; i < 6; i++) instance.adapter.emit('job-available', { jobId: `hint-${i}` }) - fetch.releaseNext() - await eventually(() => fetch.batches.length === 2, 'one follow-up') - fetch.releaseAll() - await Bun.sleep(50) - expect(fetch.batches).toEqual([4, 1]) - expect(fetch.maxActive).toBe(1) + await eventually( + async () => count(await statuses(instance.adapter, ids), 'completed') === 5, + 'the backlog drains without a periodic tick', + ) + await Bun.sleep(100) + expect(ran).toBe(5) + // Each full claim is followed by another one within the room left under B; the + // first claim that returns less than its batch ends the drain. + expect(batches.every((batch) => batch >= 1 && batch <= 2)).toBe(true) + expect(claimed.slice(0, -1)).toEqual(batches.slice(0, -1)) + expect(claimed.at(-1)!).toBeLessThan(batches.at(-1)!) + expect(claimed.reduce((sum, n) => sum + n, 0)).toBe(5) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + + it( + 'claims a burst of hinted jobs without waiting for a periodic tick (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + let ran = 0 + const action = defineAction()({ + name: 'burst', + handler: async () => { + ran++ + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { burst: action }, + syncPattern: 'hybrid', + pullInterval: 60_000, + batchSize: 10, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await Bun.sleep(100) // the startup pass has settled + const ids = await Promise.all( + Array.from({ length: 40 }, () => client!.runAction('burst', {})), + ) + await eventually( + async () => count(await statuses(instance.adapter, ids), 'completed') === 40, + 'the whole burst completes', + ) + expect(ran).toBe(40) } finally { - fetch.releaseAll() await closeInstance(client, instance) } }, From 92c0ed4850c53c9c91c4deba22a8d25f9019a4c6 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 00:50:20 -0300 Subject: [PATCH 063/100] fix: address G1 review (follow-up demand, stop gate, docs) - Track automatic demand instead of a capped batch: one job per hint, unbounded for startup/periodic. A full claim is followed up only while demand remains (the rest of it), so one hint claiming one job no longer causes an empty follow-up claim, while B=1 bursts and room-limited claims still drain. - Do not start a claim retry once the stop gate closed (checked before and after the delay): the original 40001 error propagates. - batchSize JSDoc and client-api.mdx describe additive hint demand, the follow-up rule, cooldown/room waits and due recovery. - Native natural-conflict test: repeat bounded rounds until a conflict was retried; allow an exhausted retry to surface only as 40001. --- packages/docs/content/docs/client-api.mdx | 2 +- packages/duron/src/adapters/postgres/base.ts | 11 ++- packages/duron/src/client.ts | 13 +-- packages/duron/src/worker-discovery.ts | 48 ++++++----- packages/duron/test/claim-isolation.test.ts | 53 +++++++----- packages/duron/test/claim-pglite.test.ts | 55 +++++++++++++ packages/duron/test/worker-discovery.test.ts | 84 +++++++++++++++----- 7 files changed, 198 insertions(+), 68 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index a10eba4..b9db28a 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -125,7 +125,7 @@ Periodic discovery is not reset or postponed by notifications or `fetch()` calls **Optional.** Defaults to `10`. Two meanings: -- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Each notification that arrives while a discovery is running adds one job to the next automatic request, and startup and periodic requests ask for B; either way a request claims at most the remaining room. An automatic claim that returns as many jobs as it asked for is followed at once by another automatic request of B (it still waits for room and for a cooldown), so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. +- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Notifications add up: the first one starts an automatic request for one job, and each later notification adds one job to it while it waits (behind a running discovery, for a cooldown, or for room). Startup and periodic checks make the request open-ended. Each claim takes at most B jobs and at most the remaining room. When a claim returns as many jobs as it asked for but did not cover the whole request (more notifications than one claim could take, or an open-ended request), another automatic request for the rest follows at once, so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. That follow-up waits for room and for a cooldown like any automatic request, and a due recovery runs before it claims. A claim that covered all of its notifications, such as one job for one notification, is not followed up. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. - **Default `fetch()` batch.** `fetch()` without `batchSize` passes this value unchanged. B is not the number of handlers that run at once. That is `actionConcurrencyLimit` per action, so with the defaults (B = 10, `actionConcurrencyLimit` = 100) at most ten automatically claimed jobs are outstanding. SQL group admission (`groupConcurrencyLimit` or `groups.concurrency`) is a separate limit across all workers. Jobs claimed by `fetch()` count toward B, and a `fetch()` batch can exceed B; automatic claiming then pauses until enough work settles. B limits claim admission only. It does not bound the rows that recovery examines, the backlog that manual calls create, or the total query rate. diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 2c3968b..302ce5f 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1192,8 +1192,10 @@ export abstract class PostgresBaseAdapter< * rolls the whole transaction back, so the claim is retried up to * {@link CLAIM_CONFLICT_RETRIES} times in a new transaction after a 1-20 ms random * delay. Retried conflicts are logged at debug level. After the last retry, the - * original 40001 error propagates. Other statement and COMMIT errors propagate - * without retry. + * original 40001 error propagates. It also propagates without a retry once the stop + * gate has closed (the lifecycle no longer accepts work), checked before and after the + * delay, so stop never sees a new claim transaction begin. Other statement and COMMIT + * errors propagate without retry. * * @returns Promise resolving to an array of fetched jobs */ @@ -1203,7 +1205,8 @@ export abstract class PostgresBaseAdapter< return await this._claim(batch) } catch (error) { const conflict = serializationFailure(error) - if (attempt > CLAIM_CONFLICT_RETRIES || !conflict) throw error + const lifecycle = lifecycleFor(this) + if (attempt > CLAIM_CONFLICT_RETRIES || !conflict || !lifecycle.accepting) throw error // Log the driver's 40001 error, not a wrapper that repeats the claim SQL. this.logger?.debug( { err: conflict, attempt, retries: CLAIM_CONFLICT_RETRIES }, @@ -1211,6 +1214,8 @@ export abstract class PostgresBaseAdapter< ) const delay = 1 + Math.floor(Math.random() * 20) await new Promise((resolve) => setTimeout(resolve, delay)) + // Stop began during the delay: surface the conflict instead of claiming again. + if (!lifecycle.accepting) throw error } } } diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 98fcf53..a86b7cd 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -211,10 +211,13 @@ export interface BaseOptionsInput { /** * Automatic claim ceiling B and the default `fetch()` batch. * Automatic discovery claims only while fewer than B claimed jobs are outstanding locally - * (queued, running or finalizing); hints claim one job. For the ceiling, positive finite - * values are floored/clamped to 1–Number.MAX_SAFE_INTEGER; otherwise 10. Manual `fetch()` - * batches are passed unchanged and may exceed B. Distinct from `actionConcurrencyLimit` - * and SQL group limits. + * (queued, running or finalizing), and claims at most B jobs at once. Each notification + * hint adds one job to the pending automatic demand; startup and periodic checks make it + * open-ended. A claim that comes back full while demand remains is followed by another + * claim, so a backlog keeps draining between periodic checks. For the ceiling, positive + * finite values are floored/clamped to 1–Number.MAX_SAFE_INTEGER; otherwise 10. Manual + * `fetch()` batches are passed unchanged and may exceed B. Distinct from + * `actionConcurrencyLimit` and SQL group limits. * * @default 10 */ @@ -1309,7 +1312,7 @@ export class Client< /** * Setup the push listener for database notifications. - * Each 'job-available' hint merges one-job demand into worker discovery. + * Each 'job-available' hint adds one job of demand to worker discovery. */ #setupPushListener() { if (this.#pushListenerSetup || !this.#lifecycle.accepting) { diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index e10026a..13161f5 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -7,7 +7,12 @@ export type DiscoveryTrigger = 'startup' | 'periodic' | 'hint' interface AutomaticRequest { kind: 'automatic' - batch: number + /** + * Jobs this request is for: one per hint, Infinity when startup or a periodic check + * asks for a backlog of unknown size, or what a full claim left uncovered. It claims + * min(B, demand, room). + */ + demand: number triggers: Set } @@ -70,9 +75,11 @@ const notAccepting = () => new Error('Lifecycle is not accepting work') * fetch calls. A chain is: optional due recovery, then at most one Adapter.fetch claim. * - At most one coalesced automatic request. Requests are served FIFO among eligible ones; * cooldown and automatic claim room decide eligibility. Each hint adds one job to its - * demand and startup/periodic requests raise it to B (never above B). An automatic claim - * that returns its full batch queues another automatic request of B, so a backlog keeps - * draining without waiting for the periodic tick. + * demand and startup/periodic requests make it unbounded; a claim asks for at most B. + * An automatic claim that returns its full batch while its demand was larger queues + * another automatic request for the rest of that demand, so a backlog keeps draining + * without waiting for the periodic tick. A claim that covered all of its hints (for + * example one job for one hint) is not followed up: later hints add their own demand. * - Automatic claims use only the room left under a Client-wide ceiling of B outstanding * local claims (claimed, queued, running and finalizing work, plus reservations). Manual * calls keep their own batch and returned jobs and may exceed B. @@ -124,10 +131,10 @@ export class WorkerDiscovery { this.#pump() } - /** Merge automatic demand. Each hint adds one job; startup/periodic request B. */ + /** Merge automatic demand. Each hint adds one job; startup/periodic make it unbounded. */ request(trigger: DiscoveryTrigger): void { if (!this.#options.automatic || this.#stopped || !this.#options.lifecycle.accepting) return - this.#mergeAutomatic(trigger === 'hint' ? 1 : this.#batch, [trigger]) + this.#mergeAutomatic(trigger === 'hint' ? 1 : Infinity, [trigger]) this.#pump() } @@ -164,14 +171,14 @@ export class WorkerDiscovery { return this.#batch - this.#local.size - this.#reserved } - // Demand adds up (one job per hint, a re-queued request's own batch) and is capped at B. - #mergeAutomatic(batch: number, triggers: Iterable): void { + // Demand adds up: one job per hint, a re-queued request's own demand. + #mergeAutomatic(demand: number, triggers: Iterable): void { if (this.#automatic) { - this.#automatic.batch = Math.min(this.#batch, this.#automatic.batch + batch) + this.#automatic.demand += demand for (const trigger of triggers) this.#automatic.triggers.add(trigger) return } - this.#automatic = { kind: 'automatic', batch, triggers: new Set(triggers) } + this.#automatic = { kind: 'automatic', demand, triggers: new Set(triggers) } this.#queue.push(this.#automatic) } @@ -247,15 +254,17 @@ export class WorkerDiscovery { if (request.kind === 'manual') request.reject(notAccepting()) return } - let batch = request.batch + let batch: number if (request.kind === 'automatic') { - batch = Math.min(batch, this.#room) + batch = Math.min(this.#batch, request.demand, this.#room) if (batch <= 0) { - this.#mergeAutomatic(request.batch, request.triggers) + this.#mergeAutomatic(request.demand, request.triggers) return } reserved = batch this.#reserved += reserved + } else { + batch = request.batch } this.#options.lifecycle.assertContinuation() const claimed = await this.#options.claim(batch) @@ -271,10 +280,13 @@ export class WorkerDiscovery { } if (request.kind === 'manual') { request.resolve(claimed.jobs) - } else if (claimed.jobs.length >= batch && this.#open) { - // A full claim suggests more claimable work. The follow-up waits for room, - // cooldown and due recovery like any automatic request. - this.#mergeAutomatic(this.#batch, request.triggers) + } else if (claimed.jobs.length >= batch && request.demand > batch && this.#open) { + // A full claim that did not cover the demand (B or room limited it, or the + // backlog size is unknown) suggests more claimable work. The follow-up waits for + // room, cooldown and due recovery like any automatic request. A claim that + // covered all of its hints (one job for one hint) is not followed up. The + // follow-up keeps the uncovered demand (unbounded stays unbounded). + this.#mergeAutomatic(request.demand - batch, request.triggers) } } catch (error) { this.#cooldownUntil = monotonicMs() + this.#interval @@ -287,7 +299,7 @@ export class WorkerDiscovery { ) // A fresh claim after cooldown, never a replay of the uncertain one. if (this.#options.automatic && !this.#stopped && this.#options.lifecycle.accepting) { - this.#mergeAutomatic(request.batch, request.triggers) + this.#mergeAutomatic(request.demand, request.triggers) } } } finally { diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 4e0fee1..43b341f 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -909,29 +909,38 @@ suite('Native PostgreSQL claim admission', () => { return { adapter, logs: captureLogs(adapter) } }) for (const { adapter } of claimers) await adapter.start() - const ids = await createJobs(claimers[0]!.adapter, 60, 1_000) - const claimed: string[] = [] + const conflicts = () => claimers.flatMap(({ logs }) => logs.conflicts()) const failures: unknown[] = [] - // Every claimer claims in a tight loop until a claim comes back empty. - await Promise.all( - claimers.map(async ({ adapter }) => { - for (;;) { - const jobs = await adapter.fetch({ batch: 2 }).catch((error: unknown) => { - failures.push(error) - return null - }) - if (jobs === null) continue - if (jobs.length === 0) return - claimed.push(...jobs.map((job) => job.id)) - } - }), - ) - expect(claimed.toSorted()).toEqual(ids.toSorted()) - expect(await db.activeCount()).toBe(60) - // Conflicts are retried, so none surfaces (4 consecutive conflicts are not expected). - expect(failures.map(sqlState)).toEqual([]) - const conflicts = claimers.flatMap(({ logs }) => logs.conflicts()) - expect(conflicts.every((entry) => entry['err']['code'] === '40001')).toBe(true) + // A round has a natural conflict only sometimes, so rounds repeat (bounded) until + // at least one conflict was retried. + let active = 0 + for (let round = 0; round < 40 && conflicts().length === 0; round++) { + const ids = await createJobs(claimers[0]!.adapter, 30, 10_000) + const claimed: string[] = [] + // Every claimer claims in a tight loop until a claim comes back empty. + await Promise.all( + claimers.map(async ({ adapter }) => { + for (;;) { + const jobs = await adapter.fetch({ batch: 2 }).catch((error: unknown) => { + failures.push(error) + return null + }) + if (jobs === null) continue + if (jobs.length === 0) return + claimed.push(...jobs.map((job) => job.id)) + } + }), + ) + // Each job of the round is claimed exactly once. + expect(claimed.toSorted()).toEqual(ids.toSorted()) + active += ids.length + expect(await db.activeCount()).toBe(active) + } + expect(conflicts().length).toBeGreaterThan(0) + expect(conflicts().every((entry) => entry['err']['code'] === '40001')).toBe(true) + // A claimer can still meet 4 conflicts in a row under this tight-loop contention; + // only that exhausted retry surfaces, as the original 40001. + expect(failures.every((error) => sqlState(error) === '40001')).toBe(true) } catch (error) { db.recordFailure(error) throw error diff --git a/packages/duron/test/claim-pglite.test.ts b/packages/duron/test/claim-pglite.test.ts index 34cfb17..f940eeb 100644 --- a/packages/duron/test/claim-pglite.test.ts +++ b/packages/duron/test/claim-pglite.test.ts @@ -210,6 +210,61 @@ describe('PGLite claim transaction', () => { } }) + for (const when of ['before', 'during'] as const) { + it(`starts no claim retry once stop has begun ${when} the retry delay`, async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + adapter.setId('claim-pglite') + const entries: Array> = [] + let stopping: Promise | undefined + adapter.setLogger( + pino( + { level: 'debug' }, + { + write: (line: string) => { + const entry = JSON.parse(line) + entries.push(entry) + // 'during': stop begins right after the conflict is logged, inside the delay. + if (when === 'during' && /claim conflict/.test(entry['msg'])) { + stopping ??= adapter.stop() + } + }, + }, + ), + ) + try { + await adapter.start() + const engine = engineOf(adapter) + await injectSerializationFailures(engine, 1) + await createJobs(adapter, 1, 1) + // Count claim attempts in-process: stop closes the engine once the claim settles. + const target = adapter as unknown as { _claim: (batch: number) => Promise } + const attempt = target._claim.bind(adapter) + let attempts = 0 + target._claim = (batch) => { + attempts++ + return attempt(batch) + } + const claim = adapter.fetch({ batch: 1 }) + // 'before': stop begins while the first attempt runs, before its conflict. + if (when === 'before') stopping = adapter.stop() + const failed = await claim.then( + () => null, + (error: unknown) => error, + ) + // The original conflict surfaces; no second claim transaction began, so the + // rolled-back attempt left nothing claimed. + expect(sqlState(failed)).toBe('40001') + expect(attempts).toBe(1) + expect(entries.filter((entry) => /claim conflict/.test(entry['msg']))).toHaveLength( + when === 'during' ? 1 : 0, + ) + expect(await stopping).toBe(true) + } finally { + await adapter.stop() + } + }) + } + it('does not pause Client discovery for a single claim conflict', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) const logs = captureLogs() diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index 5a25ac7..7e223cd 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -622,39 +622,42 @@ for (const factory of factories) { ) it( - 'claims a burst of hinted jobs without waiting for a periodic tick (public-only)', + 'does not follow a one-job claim for a lone hint with an empty claim (public-only)', async () => { const instance = await factory.create() let client: Client | null = null try { - let ran = 0 - const action = defineAction()({ - name: 'burst', - handler: async () => { - ran++ - return {} - }, - }) + const action = defineAction()({ name: 'lone', handler: async () => ({}) }) client = new Client({ database: instance.adapter, - actions: { burst: action }, - syncPattern: 'hybrid', + actions: { lone: action }, + syncPattern: 'push', pullInterval: 60_000, - batchSize: 10, + batchSize: 4, recoverJobsOnStart: false, recoverJobsInterval: 0, logger: 'silent', }) + const batches: number[] = [] + const claimed: number[] = [] + const real = instance.adapter.fetch.bind(instance.adapter) + instance.adapter.fetch = async (options) => { + batches.push(options.batch) + const jobs = await real(options) + claimed.push(jobs.length) + return jobs + } expect(await client.start()).toBe(true) - await Bun.sleep(100) // the startup pass has settled - const ids = await Promise.all( - Array.from({ length: 40 }, () => client!.runAction('burst', {})), - ) + await eventually(() => claimed.length === 1, 'the startup pass settles') + const jobId = await client.runAction('lone', {}) await eventually( - async () => count(await statuses(instance.adapter, ids), 'completed') === 40, - 'the whole burst completes', + async () => (await status(instance.adapter, jobId)) === 'completed', + 'the hinted job completes', ) - expect(ran).toBe(40) + await Bun.sleep(100) + // Startup (empty), then one claim of one job for the one hint, and nothing else. + expect(batches).toEqual([4, 1]) + expect(claimed).toEqual([0, 1]) } finally { await closeInstance(client, instance) } @@ -662,6 +665,49 @@ for (const factory of factories) { TEST_MS, ) + for (const batchSize of [10, 1]) { + it( + `claims a burst of hinted jobs without waiting for a periodic tick (B ${batchSize}, public-only)`, + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + let ran = 0 + const action = defineAction()({ + name: 'burst', + handler: async () => { + ran++ + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { burst: action }, + syncPattern: 'hybrid', + pullInterval: 60_000, + batchSize, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await Bun.sleep(100) // the startup pass has settled + const ids = await Promise.all( + Array.from({ length: 40 }, () => client!.runAction('burst', {})), + ) + await eventually( + async () => count(await statuses(instance.adapter, ids), 'completed') === 40, + 'the whole burst completes', + ) + expect(ran).toBe(40) + } finally { + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + } + for (const [pullInterval, interval] of [ [0, 5_000], [-3, 5_000], From 66d108e81cf93f13288bfba6afc1bfd95472e901 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 01:08:05 -0300 Subject: [PATCH 064/100] fix: back off claim conflict retries exponentially Retry a 40001 claim up to 5 times with exponential full-jitter backoff: a random 1..min(160, 5 * 2^n) ms before retry n (at most 310 ms in total), still checking the stop gate before and after each delay. Debug logs now include the delay. Measured with the native 4-claimer natural-conflict test (20 runs of 10 fixed rounds plus 20 runs of the test as committed, per version): the previous policy (3 retries, 1-20 ms) surfaced exhausted retries in 6/20 (PG19) and 3/20 (PG16) heavy runs; this policy surfaced none in 40/40 runs on each of PG19 and PG16. The slowest fetch that retried took 132 ms. --- packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/src/adapters/postgres/base.ts | 20 +++++++++++++++----- packages/duron/test/claim-isolation.test.ts | 5 +++-- packages/duron/test/claim-pglite.test.ts | 16 ++++++++++++---- 5 files changed, 32 insertions(+), 13 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index b9db28a..baa1b3e 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -113,7 +113,7 @@ const client = new Client({ database, waitReadTimeout: 3000 }) For both schedules, a positive finite interval is floored and clamped to `1–2,147,483,647`; other accepted values use `5000`. `getConfig()` still returns the value you passed. -Periodic discovery is not reset or postponed by notifications or `fetch()` calls. Missed ticks are not replayed: while a discovery is running, further demand is merged into one pending request. After any discovery failure (for example, a `40001` serialization failure from a concurrent claim that persisted through the claim's retries), every trigger waits one interval before the next claim, including notifications and queued `fetch()` calls. The failed claim is not replayed; the next claim is a new one. +Periodic discovery is not reset or postponed by notifications or `fetch()` calls. Missed ticks are not replayed: while a discovery is running, further demand is merged into one pending request. After any discovery failure (for example, a `40001` serialization failure from a concurrent claim that persisted through the claim's 5 retries; see [Claim Admission and Group Capacity](/docs/multi-worker#claim-admission-and-group-capacity)), every trigger waits one interval before the next claim, including notifications and queued `fetch()` calls. The failed claim is not replayed; the next claim is a new one. ```ts { diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 4776edf..2837df5 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -226,7 +226,7 @@ The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` t When concurrent claims from different workers would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so conflicts between unrelated groups are possible, for example when every worker claims at the same time after a notification. -The fetch retries a claim rejected with `40001` up to 3 times. Each retry is a new transaction that starts after a random delay of 1–20 ms, so it sees the claims that committed in the meantime. Retried conflicts are logged at debug level. Only when the last retry also fails does the fetch reject with the original error: a manual `client.fetch()` or `adapter.fetch()` call rejects, and automatic discovery logs the failure once, waits one `pullInterval`, and then makes a new claim; notifications and queued `client.fetch()` calls also wait for that cooldown. Other claim errors are not retried. Handle the rejection of a `fetch()` you start without awaiting. +The fetch retries a claim rejected with `40001` up to 5 times. Each retry is a new transaction, so it sees the claims that committed in the meantime. It starts after a random delay that grows with each retry (exponential backoff with full jitter): up to 10, 20, 40, 80 and then 160 ms, so the retries add at most about 310 ms to a claim. Retried conflicts are logged at debug level. Only when the last retry also fails does the fetch reject with the original error: a manual `client.fetch()` or `adapter.fetch()` call rejects, and automatic discovery logs the failure once, waits one `pullInterval`, and then makes a new claim; notifications and queued `client.fetch()` calls also wait for that cooldown. Other claim errors are not retried. Handle the rejection of a `fetch()` you start without awaiting. Limits of this protection: diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 302ce5f..aad03a6 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -84,7 +84,15 @@ function jsonParam(value: unknown, column: PgColumn): SQL { } /** Retries of a claim after a serialization failure (SQLSTATE 40001). */ -const CLAIM_CONFLICT_RETRIES = 3 +const CLAIM_CONFLICT_RETRIES = 5 +/** Backoff before retry n (1-based): a random 1..min(cap, base * 2^n) ms ("full jitter"). */ +const CLAIM_RETRY_BASE_MS = 5 +const CLAIM_RETRY_CAP_MS = 160 + +function claimRetryDelay(retry: number): number { + const ceiling = Math.min(CLAIM_RETRY_CAP_MS, CLAIM_RETRY_BASE_MS * 2 ** retry) + return 1 + Math.floor(Math.random() * ceiling) +} /** `error` or its first cause with SQLSTATE 40001 (serialization_failure), if any. */ function serializationFailure(error: unknown): Error | undefined { @@ -1190,8 +1198,10 @@ export abstract class PostgresBaseAdapter< * * A serialization failure (SQLSTATE 40001, from the claim statement or COMMIT) always * rolls the whole transaction back, so the claim is retried up to - * {@link CLAIM_CONFLICT_RETRIES} times in a new transaction after a 1-20 ms random - * delay. Retried conflicts are logged at debug level. After the last retry, the + * {@link CLAIM_CONFLICT_RETRIES} (5) times, each in a new transaction after an + * exponential full-jitter delay: a random 1..min(160, 5 * 2^n) ms before retry n, so at + * most 10, 20, 40, 80 and 160 ms (310 ms in total). Retried conflicts are logged at + * debug level. After the last retry, the * original 40001 error propagates. It also propagates without a retry once the stop * gate has closed (the lifecycle no longer accepts work), checked before and after the * delay, so stop never sees a new claim transaction begin. Other statement and COMMIT @@ -1207,12 +1217,12 @@ export abstract class PostgresBaseAdapter< const conflict = serializationFailure(error) const lifecycle = lifecycleFor(this) if (attempt > CLAIM_CONFLICT_RETRIES || !conflict || !lifecycle.accepting) throw error + const delay = claimRetryDelay(attempt) // Log the driver's 40001 error, not a wrapper that repeats the claim SQL. this.logger?.debug( - { err: conflict, attempt, retries: CLAIM_CONFLICT_RETRIES }, + { err: conflict, attempt, retries: CLAIM_CONFLICT_RETRIES, delay }, 'Retrying claim conflict (SQLSTATE 40001)', ) - const delay = 1 + Math.floor(Math.random() * 20) await new Promise((resolve) => setTimeout(resolve, delay)) // Stop began during the delay: surface the conflict instead of claiming again. if (!lifecycle.accepting) throw error diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 43b341f..63d5f68 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -938,8 +938,9 @@ suite('Native PostgreSQL claim admission', () => { } expect(conflicts().length).toBeGreaterThan(0) expect(conflicts().every((entry) => entry['err']['code'] === '40001')).toBe(true) - // A claimer can still meet 4 conflicts in a row under this tight-loop contention; - // only that exhausted retry surfaces, as the original 40001. + // Exhaustion (6 conflicts in a row for one claim) was not observed in 40 runs per + // PostgreSQL version of this tight-loop contention, but it is not impossible; only + // that exhausted retry surfaces, as the original 40001. expect(failures.every((error) => sqlState(error) === '40001')).toBe(true) } catch (error) { db.recordFailure(error) diff --git a/packages/duron/test/claim-pglite.test.ts b/packages/duron/test/claim-pglite.test.ts index f940eeb..4c5e80b 100644 --- a/packages/duron/test/claim-pglite.test.ts +++ b/packages/duron/test/claim-pglite.test.ts @@ -180,7 +180,7 @@ describe('PGLite claim transaction', () => { } }) - it('surfaces a persistent 40001 after 3 retries and claims nothing', async () => { + it('surfaces a persistent 40001 after 5 backed-off retries and claims nothing', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) adapter.setId('claim-pglite') const logs = captureLogs() @@ -195,9 +195,17 @@ describe('PGLite claim transaction', () => { (error: unknown) => error, ) expect(sqlState(failed)).toBe('40001') - // One attempt plus 3 retries; the final failure is not logged as a retried conflict. - expect(await claimAttempts(engine)).toBe(4) - expect(logs.conflicts().map((entry) => entry['attempt'])).toEqual([1, 2, 3]) + // One attempt plus 5 retries; the final failure is not logged as a retried conflict. + expect(await claimAttempts(engine)).toBe(6) + const conflicts = logs.conflicts() + expect(conflicts.map((entry) => entry['attempt'])).toEqual([1, 2, 3, 4, 5]) + // Exponential full-jitter backoff: retry n waits 1..min(160, 5 * 2^n) ms. + const ceilings = [10, 20, 40, 80, 160] + expect( + conflicts.every( + (entry, index) => entry['delay'] >= 1 && entry['delay'] <= ceilings[index]!, + ), + ).toBe(true) expect(logs.at(50).map((entry) => entry['msg'])).toEqual(['Error in Adapter.fetch()']) const statuses = await engine.query<{ status: string }>( 'SELECT status FROM duron.jobs_active', From c9b2cb94408961f9f96c1f2cb4411a5767ac32b4 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 02:01:39 -0300 Subject: [PATCH 065/100] fix: recover this worker's own abandoned jobs, never its held ones R3: after the first successful recovery the adapter skipped its own client id for good, so an own job that a rejected cancel write, or rejected final completeJob/failJob writes, left active stayed active (and held a group slot) until the process stopped. - Recovery includes the adapter's own id again in every pass, except the job ids its Client holds locally, passed in the internal `heldJobIds` recovery option. The Client holds a job from dispatch until its actual local settlement (claimed, queued, running, finalizing, a lingering timed-out handler, a suppressed claim until its cancel writes settle). `null` skips the own id (used while a Client claim reply is pending, and by default for direct recoverJobs calls on an adapter a Client uses, which cannot see the held jobs). An adapter without a Client includes its own id. - Worker discovery no longer gates claiming on a first successful recovery: that rule only protected claims from the own-id pass, which now skips held jobs. A failed recovery still skips that turn's claim and cools down. - Docs/JSDoc (client.ts recoverJobsOnStart, recoverJobsInterval, cancelJob; client-api.mdx, multi-worker.mdx, adapters.mdx) describe the rescue. --- packages/docs/content/docs/adapters.mdx | 2 +- packages/docs/content/docs/client-api.mdx | 8 +- packages/docs/content/docs/multi-worker.mdx | 6 +- packages/duron/src/adapters/adapter.ts | 8 + packages/duron/src/adapters/postgres/base.ts | 25 ++- packages/duron/src/adapters/schemas.ts | 8 + packages/duron/src/client.ts | 65 ++++-- packages/duron/src/local-cancellation.ts | 5 + packages/duron/src/recovery-scope.ts | 18 ++ packages/duron/src/worker-discovery.ts | 17 +- packages/duron/test/heartbeat-clock.test.ts | 9 +- .../duron/test/local-cancellation.test.ts | 32 +-- packages/duron/test/recover-own-jobs.test.ts | 91 ++++++--- packages/duron/test/worker-discovery.test.ts | 10 +- packages/duron/test/worker-recovery.test.ts | 190 ++++++++++++++++-- 15 files changed, 382 insertions(+), 112 deletions(-) create mode 100644 packages/duron/src/recovery-scope.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index eb6cf01..e9a878d 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -340,7 +340,7 @@ See the [Adapter API Reference](/docs/adapters) for all required methods. `Adapter.fetch()` dispatches to your `_fetch` override, and so does `Client.fetch()` when the Client has actions configured. A custom `_fetch` is responsible for its own cross-worker capacity safety; it only receives the built-in `SERIALIZABLE` claim protection when it delegates to the built-in PostgreSQL/PGLite `_fetch` (see [Multi-Worker Setup](/docs/multi-worker#claim-admission-and-group-capacity)). -Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). +Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). The Client passes an internal `heldJobIds` field in the recovery options: the job ids it holds locally, which the built-in `_recoverJobs` leaves alone while it rescues the adapter's other own jobs (`null` means skip the adapter's own id). A custom `_recoverJobs` that ignores it keeps its own behavior for the adapter's own jobs. ## Best Practices diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index baa1b3e..0eeb1e6 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -170,7 +170,7 @@ B is not the number of handlers that run at once. That is `actionConcurrencyLimi **Optional.** Whether to recover stuck jobs on startup. Defaults to `true`. -Startup recovery also rescues jobs that a previous process with the same Client `id` left active. Only the first successful recovery after start does this. When `recoverJobsOnStart` is `false`, the first periodic recovery does it instead. When `recoverJobsOnStart` is `false` and `recoverJobsInterval` is `0`, Duron runs no recovery, so these leftovers are never rescued automatically. In that configuration, the first successful direct `client.database.recoverJobs()` call after start includes this Client's own `id`, and it can requeue jobs this Client is running. Call it before the Client claims jobs, or keep startup recovery on. +Startup recovery, like every recovery Duron runs for this Client, also rescues jobs that a previous process with the same Client `id` left active. When `recoverJobsOnStart` is `false`, the first periodic recovery does it instead. When `recoverJobsOnStart` is `false` and `recoverJobsInterval` is `0`, Duron runs no recovery, so this Client never rescues these leftovers itself: a direct `client.database.recoverJobs()` call skips this Client's own `id` (see [`recoverJobsInterval`](#recoverjobsinterval)). Other workers rescue them only once this Client stops and its heartbeat goes stale. ```ts { @@ -182,9 +182,9 @@ Startup recovery also rescues jobs that a previous process with the same Client **Optional.** Interval in milliseconds between periodic job recovery runs. Defaults to `60000` (1 minute). Set to `0` to disable periodic recovery (only runs on startup). -Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Until one recovery has succeeded (startup or periodic), every discovery turn recovers first, so without startup recovery the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies. So, while periodic recovery is enabled, the Client claims no job before a recovery succeeds. +Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Without startup recovery, the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies; later turns claim as usual until the next recovery is due. -Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs. This guarantee covers Duron's own startup and periodic recovery. It does not cover direct `client.database.recoverJobs()` calls: the first successful recovery after start includes this Client's own `id` (see [`recoverJobsOnStart`](#recoverjobsonstart)). A direct call that starts before that first success, and that is still running when the Client begins to claim, can also requeue a job this Client just claimed. As a trade-off, if one of this Client's own jobs is lost locally while the process keeps running, periodic recovery does not rescue it; its own timeout and expiry handling still applies. One recovery call can affect any number of jobs and has no time limit. +Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. It rescues other workers' abandoned jobs and this Client's own active jobs that it no longer holds locally, and it never touches a job this Client holds: claimed, queued behind `actionConcurrencyLimit`, running or writing its result, including a timed-out handler that still runs. So an own job that a rejected write left active (a failed `cancelJob` before the handler started, or a failed final `completeJob`/`failJob` write) is requeued and runs again, or is archived as `failed` if it expired, by the next recovery. This covers Duron's own startup and periodic recovery. A direct `client.database.recoverJobs()` call cannot see which jobs this Client holds, so it skips this Client's own `id` entirely and rescues only other owners. One recovery call can affect any number of jobs and has no time limit. Recovery checks for: @@ -330,7 +330,7 @@ What happens depends on where the job is: - **Running on this Client** (its handler has started, including while it finishes up after an abort): the handler is aborted in memory and the call returns `true`. The job writes its own cancellation when it settles. - **Anything else**: the call issues its own `Adapter.cancelJob` and returns `false`, even when the database cancellation succeeds. If that write rejects, the rejection reaches this caller only. Concurrent calls each issue their own write and get their own result. -- **Claimed by this Client but not started**: the claim reply is still pending, or the job is queued behind `actionConcurrencyLimit`. Once a call is admitted, the job's handler never starts, even if the write rejects. Duron does not retry, replay or compensate the write. A job that a rejected write left active can later be recovered: requeued (and run again) if it has not expired, or archived as `failed` if it has. The suppressed claim keeps its slot in the automatic claim ceiling until the overlapping cancellation writes settle. +- **Claimed by this Client but not started**: the claim reply is still pending, or the job is queued behind `actionConcurrencyLimit`. Once a call is admitted, the job's handler never starts, even if the write rejects. Duron does not retry, replay or compensate the write. A job that a rejected write left active is rescued by this Client's next startup or periodic recovery (see [`recoverJobsInterval`](#recoverjobsinterval)): requeued (and run again) if it has not expired, or archived as `failed` if it has. With `recoverJobsInterval: 0` it stays active until a later startup recovery with this Client's `id`, or until this Client stops and another worker's recovery rescues it. The suppressed claim keeps its slot in the automatic claim ceiling until the overlapping cancellation writes settle. - **Running on another Client**: the database cancellation does not stop it. Its handler continues until a step write finds the job inactive, then follows the normal failed-job path. A job that another Client has claimed or queued is not suppressed by a cancellation made elsewhere: its handler can still start and then fail when step creation returns `null`. This is in-process handling for this Client's own claims, not a durable or fenced cancellation guarantee. Cancellation never waits for worker discovery or recovery. After `stop()`, new external calls reject; a call made from a running handler during shutdown is still admitted, starts no handler, and its write is observed (or reported as incomplete) by the drain. diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 2837df5..6d1ad8d 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -282,11 +282,11 @@ Limits: Duron uses heartbeat-based liveness detection for crashed-instance recovery: 1. **Heartbeat**: Each instance periodically upserts a liveness record in the `clients` table (every `heartbeatInterval`). PostgreSQL and PGLite use SQL `now()` for both the first write and subsequent updates. -2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). Until one recovery has succeeded, every discovery turn recovers first, and a failed recovery skips that turn's claim, so while periodic recovery is enabled the worker claims no job while recovery still includes its own client ID. There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. +2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). Without startup recovery, the first discovery turn recovers. A failed recovery skips that turn's claim and applies the `pullInterval` cooldown; later turns claim as usual. There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. 3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. 4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery does not newly include null owners. - - **Own jobs**: Only the first successful recovery after the adapter starts also includes the current client ID, regardless of its heartbeat. That is startup recovery, or the first periodic recovery when `recoverJobsOnStart` is `false`. This rescues jobs that a previous process with the same ID left active. After that first success, later recoveries never touch this client's own jobs, and this includes direct `client.database.recoverJobs()` calls. A failed first attempt does not count; the next attempt includes the client ID again. - - **Direct calls**: The guarantee that recovery never touches this worker's running jobs covers Duron's own startup and periodic recovery. With `recoverJobsOnStart: false` and `recoverJobsInterval: 0`, Duron runs no recovery. Leftovers from a previous process with the same ID are then never rescued automatically. The first successful direct `client.database.recoverJobs()` call after start still includes this worker's own ID and can requeue jobs it is running. Call it before the worker claims jobs, or keep startup recovery on. A direct call that starts before the first success and is still running when the worker begins to claim can also requeue a job the worker just claimed. + - **Own jobs**: Every startup and periodic recovery also includes the current client ID, regardless of its heartbeat, except for the jobs this Client holds locally: claimed, queued, running or writing their result (including a timed-out handler that still runs). Discovery runs recovery and claims one after the other, so no claim of this Client is in flight during it. This rescues jobs that a previous process with the same ID left active, and this process's own jobs that a rejected write left active (a failed `cancelJob` before the handler started, or a failed final `completeJob`/`failJob` write), while a job this worker is running is never requeued. + - **Direct calls**: A direct `client.database.recoverJobs()` call cannot see which jobs the Client holds, so it skips this worker's own ID and rescues only other owners. With `recoverJobsOnStart: false` and `recoverJobsInterval: 0`, Duron runs no recovery, so this worker's own leftovers stay active until this worker stops and its heartbeat goes stale; then other workers' recovery rescues them. 5. **Recovery behavior**: - **Expired jobs** (exceeded timeout): Archived as failed with error information - **Stuck jobs** (not expired): Reset to `created` status and can be picked up by any worker diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index e25e930..7e73f7f 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -10,6 +10,7 @@ import { type JobStatus, } from '../constants.js' import { lifecycleFor } from '../lifecycle.js' +import { usedByClient } from '../recovery-scope.js' import { ArchiveStatsSchema, @@ -462,6 +463,10 @@ export abstract class Adapter extends EventEmitter { /** * Recover stuck jobs (jobs that were active but the process that owned them is no longer running). * + * Without the internal `heldJobIds` option, a call on an adapter used by a Client skips the + * adapter's own id (it cannot tell which own jobs the Client is running); a call on an + * adapter without a Client includes it. + * * @returns Promise resolving to the number of jobs recovered */ async recoverJobs(options: RecoverJobsOptions): Promise { @@ -471,6 +476,9 @@ export abstract class Adapter extends EventEmitter { throw new Error('Adapter is not accepting work') } const parsedOptions = RecoverJobsOptionsSchema.parse(options) + if (parsedOptions.heldJobIds === undefined) { + parsedOptions.heldJobIds = usedByClient(this) ? null : [] + } const result = await this._recoverJobs(parsedOptions) return NumberResultSchema.parse(result) } catch (error) { diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index aad03a6..d48ed22 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -142,7 +142,6 @@ export abstract class PostgresBaseAdapter< private lastPrunedAt: Date | null = null private initialized = false // Set by the first successful recovery after start; later recoveries skip own jobs. - private ownJobsRecovered = false protected ownedClosed = false private listenerObligations: Array<{ done: boolean }> = [] private readonly waitReadContext = new AsyncLocalStorage<{ @@ -258,7 +257,6 @@ export abstract class PostgresBaseAdapter< * @returns Promise resolving to `true` if started successfully, `false` otherwise */ protected async _start() { - this.ownJobsRecovered = false if (!lifecycleFor(this).accepting) return // Prune ancient client liveness rows (garbage collection for instances // that died long ago without a graceful release). The threshold is @@ -1350,19 +1348,25 @@ export abstract class PostgresBaseAdapter< /** * Internal method to recover stuck jobs (jobs that were active but the process that owned them is no longer running). * Uses the clients liveness table to detect dead owners: a client whose heartbeat is older than staleTimeoutMs (or missing) is considered dead. - * This adapter's own id is included only until one call succeeds after start, to rescue jobs left - * by a previous process with the same id. Later calls never touch this adapter's own jobs. - * Expired archival and then requeue each run in their own transaction (see `_recoverLockedJobs`). + * This adapter's own id is included too, except for the jobs listed in `heldJobIds` (the jobs + * its Client holds locally), so own jobs a previous process left, or that a rejected write + * left active, are rescued while held jobs are never touched. `heldJobIds: null` skips the own + * id. Expired archival and then requeue each run in their own transaction (see + * `_recoverLockedJobs`). * * @returns Promise resolving to the number of jobs recovered */ protected async _recoverJobs(options: RecoverJobsOptions): Promise { - const { checksums, staleTimeoutMs = 15_000 } = options + const { checksums, staleTimeoutMs = 15_000, heldJobIds = [] } = options // Find owners of active jobs that are dead: no liveness row or stale heartbeat. - // This instance's own id is included until the first successful recovery after start, - // to recover jobs left behind by a previous run of the same client. - const includeOwn = !this.ownJobsRecovered + // This instance's own id is added below, apart from its held jobs (null: skipped). + const includeOwn = heldJobIds !== null + // Applied to the lock statements; the re-checks keep only locked ids. + const notHeld = + heldJobIds && heldJobIds.length > 0 + ? sql`AND NOT (j.client_id = ${this.id} AND j.id::text = ANY(${sql.param(heldJobIds)}::text[]))` + : sql`` const deadOwners: { client_id: string }[] = this._map( await this.db.execute<{ client_id: string }>(sql` SELECT DISTINCT j.client_id @@ -1395,6 +1399,7 @@ export abstract class PostgresBaseAdapter< AND j.expires_at IS NOT NULL AND j.expires_at <= now() AND j.client_id IN ${unresponsiveClientIds} + ${notHeld} FOR UPDATE OF j SKIP LOCKED `, (lockedIds) => sql` @@ -1455,6 +1460,7 @@ export abstract class PostgresBaseAdapter< WHERE j.status = ${JOB_STATUS_ACTIVE} AND j.client_id IN ${unresponsiveClientIds} AND (j.expires_at IS NULL OR j.expires_at > now()) + ${notHeld} FOR UPDATE OF j SKIP LOCKED `, (lockedIds) => sql` @@ -1492,7 +1498,6 @@ export abstract class PostgresBaseAdapter< ) } - if (includeOwn) this.ownJobsRecovered = true return recoveredCount } diff --git a/packages/duron/src/adapters/schemas.ts b/packages/duron/src/adapters/schemas.ts index a99cb65..c4c951b 100644 --- a/packages/duron/src/adapters/schemas.ts +++ b/packages/duron/src/adapters/schemas.ts @@ -173,6 +173,14 @@ export const RecoverJobsOptionsSchema = z.object({ staleTimeoutMs: z.optional(z.number()), /** AbortSignal to cancel recovery (e.g., during shutdown) */ signal: z.optional(z.instanceof(AbortSignal)), + /** + * Internal: set by Duron's Client, not a public option. The job ids the adapter's Client + * holds locally. An array: the adapter's own id counts as an unresponsive owner too, except + * for these jobs. `null`: skip the adapter's own id. When omitted, `Adapter.recoverJobs()` + * uses `null` for an adapter used by a Client and `[]` otherwise. Adapters that do not + * support it ignore it. + */ + heldJobIds: z.optional(z.nullable(z.array(z.string()))), }) export const FetchOptionsSchema = z.object({ diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index a86b7cd..dcc7824 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -26,6 +26,7 @@ import type { JobStatusResult, JobStepStatusResult } from './adapters/schemas.js import { JOB_STATUS_CANCELLED, JOB_STATUS_FAILED, type JobStatus } from './constants.js' import { type Lifecycle, lifecycleFor } from './lifecycle.js' import { type FetchToken, LocalCancellation } from './local-cancellation.js' +import { markClientAdapter } from './recovery-scope.js' import { validateSchema } from './standard-schema.js' import { WaitManager } from './wait-manager.js' import { type ClaimedBatch, WorkerDiscovery } from './worker-discovery.js' @@ -261,12 +262,10 @@ export interface BaseOptionsInput { * Stuck jobs are jobs that were marked as active but the process that owned them * is no longer running (e.g., after a crash or restart). * These jobs will be reset to 'created' status so they can be picked up again. - * The first successful recovery after start (this one, or the first periodic recovery when - * disabled) also rescues jobs a previous process with this Client's id left active. - * With this option false and `recoverJobsInterval` 0, Duron runs no recovery: such jobs are - * never rescued automatically, and the first successful direct `database.recoverJobs()` - * call after start includes this Client's id and can requeue its running jobs. Call it - * before claiming, or keep startup recovery on. + * Every recovery Duron runs for this Client (this one and periodic ones) also rescues jobs + * with this Client's id that it does not hold locally, such as jobs a previous process with + * this id left active. With this option false and `recoverJobsInterval` 0, Duron runs no + * recovery, and a direct `database.recoverJobs()` call skips this Client's own id. * * @default true */ @@ -295,13 +294,13 @@ export interface BaseOptionsInput { * Recovery checks for expired or stuck jobs and handles them appropriately. * Set to `0` to disable periodic recovery (only runs on startup). * Runs inside worker discovery once strictly more than this many monotonic milliseconds - * have elapsed since startup recovery success or the last attempt's settlement. Until one - * recovery has succeeded, every discovery turn recovers first and claims only after success. - * It runs while this Client's jobs are running and does not pause claiming: it rescues - * other workers' abandoned jobs and never touches this Client's own running jobs. That - * guarantee covers Duron's own startup and periodic recovery, not a first direct - * `database.recoverJobs()` call (see `recoverJobsOnStart`) or a direct call that overlaps - * the first recovery. + * have elapsed since startup recovery success or the last attempt's settlement (without one, + * the first discovery turn recovers). A failed attempt skips that turn's claim only. + * It runs while this Client's jobs are running and does not pause claiming. It rescues other + * workers' abandoned jobs and this Client's own active jobs that it no longer holds (for + * example after a rejected cancel or final write), and never touches a job this Client holds + * locally (claimed, queued, running or finalizing). A direct `database.recoverJobs()` call + * cannot see the held jobs, so it skips this Client's own id. * * @default 60000 */ @@ -418,6 +417,8 @@ export class Client< #discovery: WorkerDiscovery | null = null #cancellation: LocalCancellation #actionManagers = new Map>>() + /** Job ids held locally from dispatch until actual local settlement (see `#hold`). */ + #held = new Map() #mockInputSchemas = new Map() #waits: WaitManager #jobStatusListenerSetup = false @@ -447,6 +448,7 @@ export class Client< this.#variables = options?.variables ?? {} this.#logger = this.#normalizeLogger(options?.logger) this.#database.setId(this.#id) + markClientAdapter(this.#database) this.#database.setLogger(this.#logger) this.#cancellation = new LocalCancellation(this) if (this.#actions) { @@ -463,6 +465,7 @@ export class Client< this.#database.recoverJobs({ checksums: Object.values(actions).map((action) => action.checksum), staleTimeoutMs: this.#options.heartbeatTimeout, + heldJobIds: this.#heldJobIds(), }), claim: (batch) => this.#claim(batch), }) @@ -777,7 +780,9 @@ export class Client< * * A job this Client has claimed but not started (claim reply pending, or queued behind * `actionConcurrencyLimit`) never starts its handler once such a call is admitted, even if the - * write is rejected; nothing retries or replays it, and the job can later be recovered. Jobs + * write is rejected; nothing retries or replays it. A job a rejected write left active is + * rescued by this Client's next startup or periodic recovery once it is no longer held + * locally: requeued, or archived as failed if expired (see `recoverJobsInterval`). Jobs * running on another Client keep running until their next write finds the job inactive. * * @param jobId - The ID of the job to cancel @@ -1121,6 +1126,7 @@ export class Client< await this.#database.recoverJobs({ checksums: Object.values(this.#actions).map((action) => action.checksum), staleTimeoutMs: this.#options.heartbeatTimeout, + heldJobIds: this.#heldJobIds(), }) if (!this.#lifecycle.accepting) return false this.#discovery?.anchorRecovery() @@ -1279,11 +1285,40 @@ export class Client< } return { jobs, - dispatch: (job) => this.#executeJob(job, token), + dispatch: (job) => this.#hold(job.id, () => this.#executeJob(job, token)), release: () => this.#cancellation.releaseFetch(token), } } + /** Count `jobId` as held locally from dispatch until its actual local settlement. */ + #hold(jobId: string, dispatch: () => Promise): Promise { + this.#held.set(jobId, (this.#held.get(jobId) ?? 0) + 1) + const release = () => { + const count = (this.#held.get(jobId) ?? 1) - 1 + if (count > 0) this.#held.set(jobId, count) + else this.#held.delete(jobId) + } + let settlement: Promise + try { + settlement = dispatch() + } catch (error) { + release() + throw error + } + return settlement.finally(release) + } + + /** + * The job ids recovery must leave alone: every job this Client holds locally (claimed, + * queued, running or finalizing, including a timed-out handler that still runs). Recovery + * rescues this Client's other own active jobs. `null` (skip the own id entirely) while a + * Client claim's reply is pending, because its jobs are not dispatched yet. Worker discovery + * runs recovery and claims one after the other, so its recoveries always get the list. + */ + #heldJobIds(): string[] | null { + return this.#cancellation.claimPending ? null : [...this.#held.keys()] + } + /** * Schedule the next heartbeat. Uses recursive setTimeout (not setInterval) * to avoid overlapping calls if a heartbeat is slow. diff --git a/packages/duron/src/local-cancellation.ts b/packages/duron/src/local-cancellation.ts index 0dc4f57..8018819 100644 --- a/packages/duron/src/local-cancellation.ts +++ b/packages/duron/src/local-cancellation.ts @@ -84,6 +84,11 @@ export class LocalCancellation { return token } + /** True while an issued Client fetch has not been released (its reply is pending). */ + get claimPending(): boolean { + return this.#issued.size > 0 + } + /** Call once the fetch rejected, or after every returned job was dispatched or dropped. */ releaseFetch(token: FetchToken): void { this.#issued.delete(token) diff --git a/packages/duron/src/recovery-scope.ts b/packages/duron/src/recovery-scope.ts new file mode 100644 index 0000000..8081b96 --- /dev/null +++ b/packages/duron/src/recovery-scope.ts @@ -0,0 +1,18 @@ +/** + * Internal recovery scope registry: not exported by the package. + * + * Adapters used by a Client. A direct `recoverJobs()` call on such an adapter cannot know + * which of the adapter's own jobs the Client holds locally (claimed, queued, running or + * finalizing), so it skips the adapter's own id. The Client passes its held job ids itself. + */ +const clientAdapters = new WeakSet() + +/** Mark `adapter` as used by a Client. */ +export function markClientAdapter(adapter: object): void { + clientAdapters.add(adapter) +} + +/** True when a Client uses `adapter`. */ +export function usedByClient(adapter: object): boolean { + return clientAdapters.has(adapter) +} diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index 13161f5..c7d5c33 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -83,11 +83,13 @@ const notAccepting = () => new Error('Lifecycle is not accepting work') * - Automatic claims use only the room left under a Client-wide ceiling of B outstanding * local claims (claimed, queued, running and finalizing work, plus reservations). Manual * calls keep their own batch and returned jobs and may exceed B. - * - Due recovery runs in the next chain even while local jobs are running (the adapter never - * requeues this worker's own jobs after its first successful recovery), then that chain - * claims as usual. Its interval is measured monotonically from startup recovery success or - * any attempt's settlement. Until one recovery has succeeded (startup or periodic), every - * chain recovers first, so nothing is claimed while the adapter still includes its own id. + * - Due recovery runs in the next chain even while local jobs are running, then that chain + * claims as usual. Recovery skips every job the Client holds locally (the `recover` + * callback passes them) and rescues the Client's other own active jobs; no claim of this + * coordinator is in flight during it. Its interval is measured monotonically from startup + * recovery success or any attempt's settlement; without one, the first chain recovers. A + * failed recovery costs that chain's claim and one cooldown, but does not block later + * claims until the next recovery is due. * - Any chain failure applies one effective pullInterval cooldown to all triggers. * - Direct Adapter calls (including via client.database) are outside this coordinator. */ @@ -102,7 +104,6 @@ export class WorkerDiscovery { #stopped = false #cooldownUntil = -Infinity #recoveredAt = -Infinity - #recoverySucceeded = false #reserved = 0 #local = new Set>() #tick: ReturnType | null = null @@ -117,7 +118,6 @@ export class WorkerDiscovery { /** Successful startup recovery anchors the next periodic recovery interval. */ anchorRecovery(): void { this.#recoveredAt = monotonicMs() - this.#recoverySucceeded = true } /** Admit discovery after the Client is running: one immediate pass, then periodic safety. */ @@ -194,7 +194,7 @@ export class WorkerDiscovery { #recoveryDue(now: number): boolean { const interval = this.#options.recoverJobsInterval - return interval > 0 && (!this.#recoverySucceeded || now - this.#recoveredAt > interval) + return interval > 0 && now - this.#recoveredAt > interval } #pump(): void { @@ -243,7 +243,6 @@ export class WorkerDiscovery { if (recover) { try { await this.#options.recover() - this.#recoverySucceeded = true } finally { this.#recoveredAt = monotonicMs() } diff --git a/packages/duron/test/heartbeat-clock.test.ts b/packages/duron/test/heartbeat-clock.test.ts index f5fdbeb..1b57cce 100644 --- a/packages/duron/test/heartbeat-clock.test.ts +++ b/packages/duron/test/heartbeat-clock.test.ts @@ -203,15 +203,14 @@ for (const factory of [ { client_id: 'clock-minus', delta: '-1' }, { client_id: 'clock-plus', delta: '1' }, ]) - // Only the first successful recovery after start includes the own id, - // regardless of its liveness; later passes leave own jobs active. - const ownIncluded = timeout === undefined + // An adapter without a Client includes its own id in every pass, regardless + // of its liveness (it holds no jobs locally). expect( await adapter.recoverJobs({ checksums: ['clock-boundary'], staleTimeoutMs: timeout, }), - ).toBe(ownIncluded ? 4 : 3) + ).toBe(4) const states = await rows<{ id: string; status: string }>( tx, sql` @@ -224,7 +223,7 @@ for (const factory of [ 'created', 'active', 'created', - ownIncluded ? 'created' : 'active', + 'created', 'active', ]) } finally { diff --git a/packages/duron/test/local-cancellation.test.ts b/packages/duron/test/local-cancellation.test.ts index 00e2d40..216e9c4 100644 --- a/packages/duron/test/local-cancellation.test.ts +++ b/packages/duron/test/local-cancellation.test.ts @@ -248,6 +248,7 @@ interface HarnessOptions { pullInterval?: number batchSize?: number actionConcurrencyLimit?: number + recoverJobsOnStart?: boolean recoverJobsInterval?: number logger?: pino.Logger } @@ -332,7 +333,7 @@ async function harness(factory: AdapterFactory, options: HarnessOptions = {}): P pullInterval: options.pullInterval ?? 60_000, batchSize: options.batchSize ?? 10, actionConcurrencyLimit: options.actionConcurrencyLimit ?? 100, - recoverJobsOnStart: false, + recoverJobsOnStart: options.recoverJobsOnStart ?? false, recoverJobsInterval: options.recoverJobsInterval ?? 0, logger: options.logger ?? 'silent', }) @@ -591,9 +592,11 @@ for (const factory of factories) { // ------------------------------------------------------------------------ it( - 'E5: a rejected write suppresses without replay; recovery later requeues the unexpired job (fault-injected, direct recovery)', + 'E5: a rejected write suppresses without replay; periodic recovery later requeues the unexpired job (fault-injected, default recoverJobsOnStart)', async () => { - const h = await harness(factory) + // Startup recovery on (the default): the own id stays in every later recovery. + const h = await harness(factory, { recoverJobsOnStart: true, recoverJobsInterval: 500 }) + const startedAt = performance.now() try { let target: string | null = null const reply = holdReplyFor(h.adapter, () => target) @@ -617,13 +620,16 @@ for (const factory of factories) { expect(cancels.for(target)).toHaveLength(1) expect(fails).not.toContain(target) - // Direct: this Client's own recovery requeues its remaining unexpired active job. + // A direct call cannot see this Client's held jobs, so it skips the own id. await h.adapter.recoverJobs({ checksums: [h.client.getConfig().actions!['work'].checksum], staleTimeoutMs: 15_000, }) - expect(await status(h.adapter, target)).toBe('created') - // A later claim is not suppressed: the job may run again. + expect(await status(h.adapter, target)).toBe('active') + + // The next due periodic recovery requeues this Client's own unheld active job, and + // the same discovery turn claims it again: the claim is not suppressed. + await Bun.sleep(Math.max(0, startedAt + 600 - performance.now())) expect((await h.client.fetch()).map((job) => job.id)).toEqual([target]) await eventually( async () => (await status(h.adapter, target!)) === 'completed', @@ -668,9 +674,10 @@ for (const factory of factories) { ) it( - 'E5: after a rejected write an expired job is archived failed by recovery (fault-injected, direct recovery)', + 'E5: after a rejected write an expired job is archived failed by periodic recovery (fault-injected, default recoverJobsOnStart)', async () => { - const h = await harness(factory) + const h = await harness(factory, { recoverJobsOnStart: true, recoverJobsInterval: 500 }) + const startedAt = performance.now() try { let target: string | null = null const reply = holdReplyFor(h.adapter, () => target) @@ -684,11 +691,10 @@ for (const factory of factories) { await fetching await h.sentinel() expect(h.starts).not.toContain(target) - await Bun.sleep(400) - await h.adapter.recoverJobs({ - checksums: [h.client.getConfig().actions!['short'].checksum], - staleTimeoutMs: 15_000, - }) + // Past the job's 300 ms expiry and the 500 ms recovery interval: the discovery turn + // of this fetch archives the expired own job before it claims. + await Bun.sleep(Math.max(400, startedAt + 600 - performance.now())) + expect(await h.client.fetch()).toEqual([]) expect(await status(h.adapter, target)).toBe('failed') expect(cancels.for(target)).toHaveLength(1) } finally { diff --git a/packages/duron/test/recover-own-jobs.test.ts b/packages/duron/test/recover-own-jobs.test.ts index 6b45fa2..6686d80 100644 --- a/packages/duron/test/recover-own-jobs.test.ts +++ b/packages/duron/test/recover-own-jobs.test.ts @@ -3,16 +3,19 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { defineAction } from '../src/action.js' import type { Adapter } from '../src/adapters/adapter.js' import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' import { getPostgresConnection } from './docker.js' -// Own-id recovery scope (adapter level). The adapter's own id is an unresponsive owner -// only until one recovery call succeeds after start; later calls rescue only other owners -// whose liveness is missing or stale. Controls: public Adapter calls and reads; setId to -// claim as another owner (no liveness row); one fault-injected recovery transaction. +// Own-id recovery scope (adapter level). Recovery rescues owners whose liveness is missing +// or stale and, unless told to skip it, this adapter's own id too, except the job ids its +// Client holds locally (internal `heldJobIds` option). An adapter used by a Client skips its +// own id in direct calls. Controls: public Adapter calls and reads; setId to claim as another +// owner (no liveness row); one fault-injected recovery transaction. const TEST_MS = 30_000 const OWN = 'own-worker' @@ -117,7 +120,7 @@ for (const engine of engines) { describe(`Own-id recovery scope with ${engine.name}`, () => { it( - 'the first recovery after start requeues own running jobs and archives own expired jobs', + 'every recovery of an adapter without a Client requeues own running jobs and archives own expired jobs', () => withStore(async (start) => { const adapter = await start() @@ -128,64 +131,96 @@ for (const engine of engines) { expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(2) expect(await job(adapter, running)).toMatchObject({ status: 'created', startedAt: null }) expect(await job(adapter, expired)).toMatchObject({ status: 'failed', clientId: OWN }) + + // Not only the first call: claimed again and left active, it is rescued again. + expect((await adapter.fetch({ batch: 1 })).map((value) => value.id)).toEqual([running]) + expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(1) + expect(await job(adapter, running)).toMatchObject({ status: 'created', startedAt: null }) }), TEST_MS, ) it( - 'later recoveries leave own jobs untouched and still rescue owners without liveness', + 'held own jobs stay untouched while other own jobs and owners without liveness are rescued', () => withStore(async (start) => { const adapter = await start() - expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) - + const heldRunning = await claimAs(adapter, OWN) + const heldExpired = await claimAs(adapter, OWN, 300) const ownRunning = await claimAs(adapter, OWN) const ownExpired = await claimAs(adapter, OWN, 300) const deadRunning = await claimAs(adapter, DEAD) const deadExpired = await claimAs(adapter, DEAD, 300) - const before = await job(adapter, ownRunning) + // A held id of another owner does not protect that owner's job. + const deadHeld = await claimAs(adapter, DEAD) + const before = await job(adapter, heldRunning) await Bun.sleep(400) - expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(2) - expect(await job(adapter, ownRunning)).toEqual({ ...before, status: 'active' }) - expect(await job(adapter, ownExpired)).toMatchObject({ status: 'active', clientId: OWN }) - expect(await job(adapter, deadRunning)).toMatchObject({ - status: 'created', - clientId: DEAD, - }) - expect(await job(adapter, deadExpired)).toMatchObject({ - status: 'failed', - clientId: DEAD, + const heldJobIds = [heldRunning, heldExpired, deadHeld] + expect(await adapter.recoverJobs({ checksums: [CHECKSUM], heldJobIds })).toBe(5) + expect(await job(adapter, heldRunning)).toEqual({ ...before, status: 'active' }) + expect(await job(adapter, heldExpired)).toMatchObject({ status: 'active', clientId: OWN }) + expect(await job(adapter, ownRunning)).toMatchObject({ status: 'created' }) + expect(await job(adapter, ownExpired)).toMatchObject({ status: 'failed', clientId: OWN }) + expect(await job(adapter, deadRunning)).toMatchObject({ status: 'created' }) + expect(await job(adapter, deadExpired)).toMatchObject({ status: 'failed' }) + expect(await job(adapter, deadHeld)).toMatchObject({ status: 'created' }) + // With only held jobs left, a later recovery has nothing to rescue. + expect(await adapter.recoverJobs({ checksums: [CHECKSUM], heldJobIds })).toBe(0) + expect(await job(adapter, heldRunning)).toEqual({ ...before, status: 'active' }) + }), + TEST_MS, + ) + + it( + 'heldJobIds null skips the own id, and so does a direct call on an adapter used by a Client', + () => + withStore(async (start) => { + const adapter = await start() + const own = await claimAs(adapter, OWN) + const dead = await claimAs(adapter, DEAD) + expect(await adapter.recoverJobs({ checksums: [CHECKSUM], heldJobIds: null })).toBe(1) + expect(await job(adapter, own)).toMatchObject({ status: 'active', clientId: OWN }) + expect(await job(adapter, dead)).toMatchObject({ status: 'created' }) + + // A Client uses this adapter (its id becomes the own id). Without the Client's held + // ids, a direct call cannot tell which own jobs are running, so it skips them all. + const action = defineAction()({ name: 'own-recovery', handler: async () => ({}) }) + new Client({ + id: OWN, + database: adapter, + actions: { action }, + syncPattern: false, + logger: 'silent', }) - // With only own jobs left, a later recovery has nothing to rescue. expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) - expect(await job(adapter, ownRunning)).toEqual({ ...before, status: 'active' }) + expect(await job(adapter, own)).toMatchObject({ status: 'active', clientId: OWN }) }), TEST_MS, ) it( - 'a restarted adapter with the same id rescues its own leftovers once again', + 'a restarted adapter with the same id rescues its own leftovers', () => withStore(async (start) => { const first = await start() - expect(await first.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) const leftover = await claimAs(first, OWN) expect(await first.stop()).toBe(true) const restarted = await start() - expect(await restarted.recoverJobs({ checksums: [CHECKSUM] })).toBe(1) + expect(await restarted.recoverJobs({ checksums: [CHECKSUM], heldJobIds: [] })).toBe(1) expect(await job(restarted, leftover)).toMatchObject({ status: 'created' }) expect((await restarted.fetch({ batch: 1 })).map((value) => value.id)).toEqual([leftover]) - expect(await restarted.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) + const heldJobIds = [leftover] + expect(await restarted.recoverJobs({ checksums: [CHECKSUM], heldJobIds })).toBe(0) expect(await job(restarted, leftover)).toMatchObject({ status: 'active', clientId: OWN }) }), TEST_MS, ) it( - 'a failed first recovery still includes own jobs in the next attempt', + 'a failed recovery leaves own jobs active and the next attempt rescues them', () => withStore(async (start) => { const adapter = await start() @@ -197,10 +232,6 @@ for (const engine of engines) { expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(1) expect(await job(adapter, leftover)).toMatchObject({ status: 'created' }) - - expect((await adapter.fetch({ batch: 1 })).map((value) => value.id)).toEqual([leftover]) - expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) - expect(await job(adapter, leftover)).toMatchObject({ status: 'active', clientId: OWN }) }), TEST_MS, ) diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index 7e223cd..fc7cd3c 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -1115,7 +1115,7 @@ for (const factory of factories) { ) it( - 'skips the claim after a background recovery failure and recovers again before the first claim (fault-injected)', + 'skips the claim after a background recovery failure, then claims without waiting for a recovery success (fault-injected)', async () => { const instance = await factory.create() let client: Client | null = null @@ -1149,13 +1149,13 @@ for (const factory of factories) { await eventually(() => recoveries === 1, 'unanchored first turn recovers') await Bun.sleep(50) expect(calls).toHaveLength(0) - // Until a recovery succeeds, every turn recovers first; only then does it claim. + // After the cooldown a later turn claims; the failed attempt anchors the interval, + // so no recovery runs before it (recovery no longer gates claiming). await eventually(() => calls.length >= 1, 'a later turn claims') - expect(firstClaim.recoveries).toBe(2) - // After that success the normal cadence applies: later turns do not recover. + expect(firstClaim.recoveries).toBe(1) await Bun.sleep(250) expect(calls.length).toBeGreaterThan(1) - expect(recoveries).toBe(2) + expect(recoveries).toBe(1) const failures = logs.discovery() expect(failures).toHaveLength(1) expect(failures[0]!['stage']).toBe('recovery') diff --git a/packages/duron/test/worker-recovery.test.ts b/packages/duron/test/worker-recovery.test.ts index 0b0d271..c99ca95 100644 --- a/packages/duron/test/worker-recovery.test.ts +++ b/packages/duron/test/worker-recovery.test.ts @@ -261,7 +261,7 @@ for (const factory of factories) { ) it( - 'without startup recovery no job is claimed until a recovery succeeds; a live job is never requeued (fault-injected)', + 'a failing recovery does not block claiming; a live job is never requeued (fault-injected)', async () => { const instance = await factory.create() let client: Client | null = null @@ -290,28 +290,17 @@ for (const factory of factories) { const trace = traceCalls(instance.adapter, events) const injected = new Error('injected recovery failure') trace.failRecovery(injected) - const claims = () => events.filter((event) => event === 'fetch:start').length expect(await client.start()).toBe(true) const jobId = await client.runAction('gated', {}) - // Every chain retries recovery after the cooldown and claims nothing. - await eventually(() => trace.recoveries() >= 3, 'failed recovery is retried', SHORT_MS) - await expect(client.fetch()).rejects.toBe(injected) - expect(claims()).toBe(0) - expect(runs).toBe(0) - expect(await status(instance.adapter, jobId)).toBe('created') - - // Once one recovery succeeds, claiming proceeds. - trace.failRecovery(null) - await eventually( - () => runs === 1, - 'the job is claimed after a successful recovery', - SHORT_MS, - ) + // The failed recovery costs one cooldown; later turns claim before the next is due. + await eventually(() => runs === 1, 'the job is claimed despite failed recovery', SHORT_MS) + expect(trace.recoveries()).toBeGreaterThanOrEqual(1) const claimed = await instance.adapter.getJobById(jobId) expect(claimed).toMatchObject({ status: 'active', clientId: 'gated-worker' }) - // Normal cadence: periodic recovery runs while the job is live and leaves it alone. + // Periodic recovery succeeds while the job is live and leaves it alone. + trace.failRecovery(null) const recoveriesWhileLive = trace.recoveries() await eventually( () => trace.recoveries() > recoveriesWhileLive + 1, @@ -338,6 +327,173 @@ for (const factory of factories) { TEST_MS, ) + it( + 'periodic recovery requeues an own job whose final writes were rejected; it runs again (fault-injected)', + async () => { + const instance = await factory.create() + let client: Client | null = null + try { + let runs = 0 + const action = defineAction()({ + name: 'lost-completion', + handler: async () => { + runs++ + return {} + }, + }) + client = new Client({ + id: 'lost-completion-worker', + database: instance.adapter, + actions: { 'lost-completion': action }, + syncPattern: 'pull', + pullInterval: 20, + // Defaults: startup recovery on. A short interval for the periodic rescue. + recoverJobsInterval: 150, + logger: 'silent', + }) + // The first completion write rejects, and so does the failure write that follows it. + const complete = instance.adapter.completeJob.bind(instance.adapter) + const fail = instance.adapter.failJob.bind(instance.adapter) + let rejected = 0 + instance.adapter.completeJob = async (options) => { + if (rejected++ === 0) throw new Error('injected completion write failure') + return complete(options) + } + let failRejected = 0 + instance.adapter.failJob = async (options) => { + if (failRejected++ === 0) throw new Error('injected failure write failure') + return fail(options) + } + expect(await client.start()).toBe(true) + const jobId = await client.runAction('lost-completion', {}) + await eventually(() => runs === 1 && failRejected === 1, 'both final writes rejected') + expect(await status(instance.adapter, jobId)).toBe('active') + await eventually( + async () => (await status(instance.adapter, jobId)) === 'completed', + 'periodic recovery requeues the job and it runs again', + ) + expect(runs).toBe(2) + } finally { + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + + it( + 'keeps a timed-out handler that still runs locally out of recovery until it settles (fault-injected)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const lingering = Promise.withResolvers() + const events: Event[] = [] + try { + let runs = 0 + const action = defineAction()({ + name: 'lingering', + expire: 100, + // Ignores abort: its raw promise outlives the timeout and the failure write. + handler: async () => { + runs++ + await lingering.promise + return {} + }, + }) + client = new Client({ + id: 'lingering-worker', + database: instance.adapter, + actions: { lingering: action }, + syncPattern: 'pull', + pullInterval: 20, + recoverJobsInterval: 50, + logger: 'silent', + }) + const trace = traceCalls(instance.adapter, events) + const fail = instance.adapter.failJob.bind(instance.adapter) + let rejected = 0 + instance.adapter.failJob = async (options) => { + rejected++ + if (rejected === 1) throw new Error('injected failure write failure') + return fail(options) + } + expect(await client.start()).toBe(true) + const jobId = await client.runAction('lingering', {}) + await eventually(() => rejected === 1, 'the timeout failure write rejected') + // Expired and left active by the rejected write, but its handler still runs here. + const recoveries = trace.recoveries() + await eventually( + () => trace.recoveries() > recoveries + 2, + 'several recoveries while the handler lingers', + ) + expect(await status(instance.adapter, jobId)).toBe('active') + expect(runs).toBe(1) + lingering.resolve() + await eventually( + async () => (await status(instance.adapter, jobId)) === 'failed', + 'once settled, recovery archives the expired job as failed', + ) + expect(runs).toBe(1) + } finally { + lingering.resolve() + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + + it( + 'frequent recovery during a burst never requeues a job this Client holds (public-only)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const events: Event[] = [] + try { + const runs = new Map() + const action = defineAction()({ + name: 'burst-recovery', + handler: async (ctx) => { + runs.set(ctx.jobId, (runs.get(ctx.jobId) ?? 0) + 1) + await Bun.sleep(15) + return {} + }, + }) + client = new Client({ + id: 'burst-recovery-worker', + database: instance.adapter, + actions: { 'burst-recovery': action }, + syncPattern: 'hybrid', + pullInterval: 60_000, + batchSize: 5, + recoverJobsInterval: 1, + logger: 'silent', + }) + const trace = traceCalls(instance.adapter, events) + expect(await client.start()).toBe(true) + const before = trace.recoveries() + const ids = await Promise.all( + Array.from({ length: 40 }, () => client!.runAction('burst-recovery', {})), + ) + await eventually( + async () => + (await Promise.all(ids.map((id) => status(instance.adapter, id)))).every( + (value) => value === 'completed', + ), + 'the whole burst completes', + ) + // A recovery ran before nearly every claim, while held jobs were queued or running. + expect(trace.recoveries() - before).toBeGreaterThan(5) + expect(ids.every((id) => runs.get(id) === 1)).toBe(true) + expect(trace.overlap).toBe(0) + } finally { + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + describe('monotonic recovery cadence (controlled clock)', () => { let restore: Array<() => void> = [] afterEach(() => { From 6eed6cecd00d82a08d8a2605ba5392352062c139 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 03:03:11 -0300 Subject: [PATCH 066/100] fix: one Client per adapter; address G2 review advisories A4: Clients sharing one adapter share its client id (setId is last-write- wins), liveness row and lifecycle: on 64a866c two Clients on one adapter store each other's claims under the last id, and stopping one stops the other. With own-id recovery each one's recovery would also requeue the other's running jobs. The Client constructor now throws a TypeError when another Client already uses the adapter (checked before any side effect; a constructor that throws later does not bind the adapter). Tests that built a second Client on a shared adapter now use their own adapter. Advisories: remove stale own-id comments (A1), fix the no-new lint warning (A2), document that jobs claimed by a direct client.database.fetch() are not held and get requeued (A3) and that a running job whose cancellation write rejects is requeued and runs again (A5), document one Client per adapter, and widen the E5 recovery interval to 1500 ms (A6). --- packages/docs/content/docs/client-api.mdx | 4 +- packages/docs/content/docs/multi-worker.mdx | 4 +- packages/duron/src/adapters/postgres/base.ts | 1 - packages/duron/src/client.ts | 13 +++- packages/duron/src/recovery-scope.ts | 3 +- .../duron/test/client-adapter-binding.test.ts | 64 +++++++++++++++++++ packages/duron/test/client.test.ts | 36 +++++++---- .../duron/test/local-cancellation.test.ts | 10 +-- packages/duron/test/recover-own-jobs.test.ts | 10 ++- packages/duron/test/recover-snapshot.test.ts | 4 +- packages/duron/test/wait-options.test.ts | 30 ++++++--- 11 files changed, 140 insertions(+), 39 deletions(-) create mode 100644 packages/duron/test/client-adapter-binding.test.ts diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 0eeb1e6..6b7475f 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -29,7 +29,7 @@ const client = duron({ ### `database` -**Required.** The database adapter to use. +**Required.** The database adapter to use. Use one adapter instance per Client: the Client sets the adapter's client ID and owns its lifecycle (stopping the Client stops the adapter). Creating a second Client with an adapter that a Client already uses throws a `TypeError`. ```ts { @@ -184,7 +184,7 @@ Startup recovery, like every recovery Duron runs for this Client, also rescues j Periodic recovery is part of worker discovery, not a separate timer: when a discovery turn runs and more than this interval has elapsed, recovery runs first. Elapsed time is measured with a process-local monotonic clock (`performance.now()`, whole milliseconds), so changes to the system clock do not affect it. A successful startup recovery starts the interval; after that, each recovery attempt starts it again when that attempt finishes, whether it succeeded or failed. Exactly reaching the interval is not enough; it must be exceeded. Without startup recovery, the first discovery turn recovers. If a recovery attempt fails, that turn claims nothing and the `pullInterval` cooldown applies; later turns claim as usual until the next recovery is due. -Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. It rescues other workers' abandoned jobs and this Client's own active jobs that it no longer holds locally, and it never touches a job this Client holds: claimed, queued behind `actionConcurrencyLimit`, running or writing its result, including a timed-out handler that still runs. So an own job that a rejected write left active (a failed `cancelJob` before the handler started, or a failed final `completeJob`/`failJob` write) is requeued and runs again, or is archived as `failed` if it expired, by the next recovery. This covers Duron's own startup and periodic recovery. A direct `client.database.recoverJobs()` call cannot see which jobs this Client holds, so it skips this Client's own `id` entirely and rescues only other owners. One recovery call can affect any number of jobs and has no time limit. +Recovery runs while this Client's jobs are running and does not pause claiming: after the recovery, the same discovery turn claims as usual. It rescues other workers' abandoned jobs and this Client's own active jobs that it no longer holds locally, and it never touches a job this Client holds: claimed, queued behind `actionConcurrencyLimit`, running or writing its result, including a timed-out handler that still runs. So an own job that a rejected write left active is requeued and runs again, or is archived as `failed` if it expired, by the next recovery: a failed `cancelJob` before the handler started, a failed final `completeJob`/`failJob` write, or a failed cancellation write of a running job after its abort. A job claimed by a direct `client.database.fetch()` is not held either, so recovery requeues it too. This covers Duron's own startup and periodic recovery. A direct `client.database.recoverJobs()` call cannot see which jobs this Client holds, so it skips this Client's own `id` entirely and rescues only other owners. One recovery call can affect any number of jobs and has no time limit. Recovery checks for: diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 6d1ad8d..ac16302 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -252,7 +252,7 @@ Each Client with actions coordinates its own job discovery: - **Recovery does not pause claiming.** When periodic recovery is due, it runs in the next discovery turn, also while this Client's jobs are running or the automatic claim ceiling is full, and that turn then claims as usual. Recovery and a claim never run at the same time in one Client. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs (see [Job Recovery](#job-recovery)). - **Failures.** After a failed discovery or recovery attempt, all discovery waits one `pullInterval`. Failed claims are never replayed. -This coordination is local to one Client. Other Clients, and direct calls such as `client.database.fetch()` or `client.database.recoverJobs()`, are not coordinated with it. Cross-worker group limits rely on the claim admission described above, not on this local coordination. +This coordination is local to one Client. Other Clients, and direct calls such as `client.database.fetch()` or `client.database.recoverJobs()`, are not coordinated with it. A job claimed by a direct `client.database.fetch()` carries this Client's ID but is not held by the Client, so this Client's next startup or periodic recovery requeues it (or archives it as `failed` if it expired); see [Job Recovery](#job-recovery). Cross-worker group limits rely on the claim admission described above, not on this local coordination. ## Cancellation and Stored Steps @@ -285,7 +285,7 @@ Duron uses heartbeat-based liveness detection for crashed-instance recovery: 2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). Without startup recovery, the first discovery turn recovers. A failed recovery skips that turn's claim and applies the `pullInterval` cooldown; later turns claim as usual. There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. 3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. 4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery does not newly include null owners. - - **Own jobs**: Every startup and periodic recovery also includes the current client ID, regardless of its heartbeat, except for the jobs this Client holds locally: claimed, queued, running or writing their result (including a timed-out handler that still runs). Discovery runs recovery and claims one after the other, so no claim of this Client is in flight during it. This rescues jobs that a previous process with the same ID left active, and this process's own jobs that a rejected write left active (a failed `cancelJob` before the handler started, or a failed final `completeJob`/`failJob` write), while a job this worker is running is never requeued. + - **Own jobs**: Every startup and periodic recovery also includes the current client ID, regardless of its heartbeat, except for the jobs this Client holds locally: claimed, queued, running or writing their result (including a timed-out handler that still runs). Discovery runs recovery and claims one after the other, so no claim of this Client is in flight during it. This rescues jobs that a previous process with the same ID left active, and this process's own jobs that a rejected write left active: a failed `cancelJob` before the handler started, a failed final `completeJob`/`failJob` write, or a failed cancellation write of a running job that was aborted (that job is requeued and runs again). A job this worker holds is never requeued; a job claimed by a direct `client.database.fetch()` is not held, so it can be. Use one adapter instance per Client; a second Client constructor on an adapter that a Client already uses throws a `TypeError`. - **Direct calls**: A direct `client.database.recoverJobs()` call cannot see which jobs the Client holds, so it skips this worker's own ID and rescues only other owners. With `recoverJobsOnStart: false` and `recoverJobsInterval: 0`, Duron runs no recovery, so this worker's own leftovers stay active until this worker stops and its heartbeat goes stale; then other workers' recovery rescues them. 5. **Recovery behavior**: - **Expired jobs** (exceeded timeout): Archived as failed with error information diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index d48ed22..d0d286d 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -141,7 +141,6 @@ export abstract class PostgresBaseAdapter< private pruneConfig: PruneSchedulerConfig | null = null private lastPrunedAt: Date | null = null private initialized = false - // Set by the first successful recovery after start; later recoveries skip own jobs. protected ownedClosed = false private listenerObligations: Array<{ done: boolean }> = [] private readonly waitReadContext = new AsyncLocalStorage<{ diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index dcc7824..71e1e3c 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -26,7 +26,7 @@ import type { JobStatusResult, JobStepStatusResult } from './adapters/schemas.js import { JOB_STATUS_CANCELLED, JOB_STATUS_FAILED, type JobStatus } from './constants.js' import { type Lifecycle, lifecycleFor } from './lifecycle.js' import { type FetchToken, LocalCancellation } from './local-cancellation.js' -import { markClientAdapter } from './recovery-scope.js' +import { markClientAdapter, usedByClient } from './recovery-scope.js' import { validateSchema } from './standard-schema.js' import { WaitManager } from './wait-manager.js' import { type ClaimedBatch, WorkerDiscovery } from './worker-discovery.js' @@ -435,9 +435,20 @@ export class Client< /** * Create a new Duron Client instance. * + * Use one adapter instance per Client: Clients on one adapter would share its client id, + * its liveness row and its lifecycle, and each one's recovery would requeue the other's + * running jobs. + * * @param options - Configuration options for the client + * @throws {TypeError} When another Client already uses `options.database`. */ constructor(options: ClientOptions) { + if (usedByClient(options.database)) { + throw new TypeError( + 'This adapter is already used by another Client. Create one adapter instance per ' + + 'Client: Clients on one adapter share its client id and lifecycle.', + ) + } const telemetry = assertTelemetryOptions(options.telemetry) this.#options = BaseOptionsSchema.parse(options) this.#id = options.id ?? globalThis.crypto.randomUUID() diff --git a/packages/duron/src/recovery-scope.ts b/packages/duron/src/recovery-scope.ts index 8081b96..e40ebf2 100644 --- a/packages/duron/src/recovery-scope.ts +++ b/packages/duron/src/recovery-scope.ts @@ -1,7 +1,8 @@ /** * Internal recovery scope registry: not exported by the package. * - * Adapters used by a Client. A direct `recoverJobs()` call on such an adapter cannot know + * Adapters used by a Client (at most one Client per adapter; a second Client constructor on + * a marked adapter throws). A direct `recoverJobs()` call on such an adapter cannot know * which of the adapter's own jobs the Client holds locally (claimed, queued, running or * finalizing), so it skips the adapter's own id. The Client passes its held job ids itself. */ diff --git a/packages/duron/test/client-adapter-binding.test.ts b/packages/duron/test/client-adapter-binding.test.ts new file mode 100644 index 0000000..7a85122 --- /dev/null +++ b/packages/duron/test/client-adapter-binding.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'bun:test' + +import { defineAction } from '../src/action.js' +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' +import { Client } from '../src/client.js' + +// One Client per adapter: Clients on one adapter would share its client id (setId is +// last-write-wins), its liveness row and its lifecycle (stopping one stops the other), and +// each Client's recovery would treat the other's running jobs as its own unheld jobs. + +describe('Client adapter binding', () => { + it('rejects a second Client on an adapter that a Client already uses, without side effects', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + const action = defineAction()({ name: 'bound', handler: async () => ({}) }) + const first = new Client({ + id: 'first', + database: adapter, + actions: { action }, + syncPattern: false, + logger: 'silent', + }) + try { + expect( + () => + new Client({ + id: 'second', + database: adapter, + actions: { action }, + syncPattern: false, + logger: 'silent', + }), + ).toThrow(TypeError) + expect(() => new Client({ id: 'second', database: adapter, logger: 'silent' })).toThrow( + 'This adapter is already used by another Client', + ) + // The rejected constructor did not take over the adapter's client id. + expect(adapter.id).toBe('first') + expect(await first.start()).toBe(true) + const jobId = await first.runAction('action', {}) + expect((await first.fetch()).map((job) => job.id)).toEqual([jobId]) + } finally { + await first.stop() + } + }) + + it('accepts one Client per adapter instance on the same database', async () => { + const action = defineAction()({ name: 'separate', handler: async () => ({}) }) + const clients = ['one', 'two'].map( + (id) => + new Client({ + id, + database: new PGLiteAdapter({ connection: ':memory:' }), + actions: { action }, + syncPattern: false, + logger: 'silent', + }), + ) + try { + for (const client of clients) expect(await client.start()).toBe(true) + } finally { + for (const client of clients) await client.stop() + } + }) +}) diff --git a/packages/duron/test/client.test.ts b/packages/duron/test/client.test.ts index 0db3530..7d43706 100644 --- a/packages/duron/test/client.test.ts +++ b/packages/duron/test/client.test.ts @@ -140,6 +140,15 @@ function runClientTests(adapterFactory: AdapterFactory) { }, ) + // One Client per adapter: a test that needs another Client gets its own adapter (and + // database), deleted after the test. + const extraDbs: Array<() => Promise> = [] + async function freshDatabase(): Promise { + const instance = await adapterFactory.create({}) + extraDbs.push(instance.deleteDb) + return instance.adapter + } + afterEach(async () => { if (client) { await client.stop() @@ -147,6 +156,7 @@ function runClientTests(adapterFactory: AdapterFactory) { if (deleteDb) { await deleteDb() } + for (const drop of extraDbs.splice(0)) await drop() }) describe('Lifecycle', () => { @@ -261,7 +271,7 @@ function runClientTests(adapterFactory: AdapterFactory) { }) const testClient = new Client({ - database, + database: await freshDatabase(), actions: { noInputAction: actionWithoutInput, }, @@ -347,7 +357,7 @@ function runClientTests(adapterFactory: AdapterFactory) { describe('Sync Patterns', () => { it('should use pull pattern to fetch jobs periodically', async () => { const pullClient = new Client({ - database, + database: await freshDatabase(), actions: { testAction, }, @@ -374,7 +384,7 @@ function runClientTests(adapterFactory: AdapterFactory) { it('should use push pattern to fetch jobs on notification', async () => { const pushClient = new Client({ - database, + database: await freshDatabase(), actions: { testAction, }, @@ -400,7 +410,7 @@ function runClientTests(adapterFactory: AdapterFactory) { it('should use hybrid pattern to fetch jobs', async () => { const hybridClient = new Client({ - database, + database: await freshDatabase(), actions: { testAction, }, @@ -806,7 +816,7 @@ function runClientTests(adapterFactory: AdapterFactory) { it('should run an action and wait for completion', async () => { // Use a client with auto-fetch enabled const autoClient = new Client({ - database, + database: await freshDatabase(), actions: { testAction, failingAction, @@ -838,7 +848,7 @@ function runClientTests(adapterFactory: AdapterFactory) { it('should return typed input and output', async () => { // Use a client with auto-fetch enabled const autoClient = new Client({ - database, + database: await freshDatabase(), actions: { testAction, failingAction, @@ -872,7 +882,7 @@ function runClientTests(adapterFactory: AdapterFactory) { it('should throw when action fails', async () => { // Use a client with auto-fetch enabled const autoClient = new Client({ - database, + database: await freshDatabase(), actions: { testAction, failingAction, @@ -960,7 +970,7 @@ function runClientTests(adapterFactory: AdapterFactory) { it('should cancel the job when aborted', async () => { // Use a client with auto-fetch enabled so the job starts processing const autoClient = new Client({ - database, + database: await freshDatabase(), actions: { testAction, failingAction, @@ -1167,7 +1177,7 @@ function runClientTests(adapterFactory: AdapterFactory) { }) const varsClient = new Client({ - database, + database: await freshDatabase(), actions: { varsAction: actionWithVars, }, @@ -1208,7 +1218,7 @@ function runClientTests(adapterFactory: AdapterFactory) { }) const descClient = new Client({ - database, + database: await freshDatabase(), actions: { describedAction: actionWithDescription, }, @@ -1237,7 +1247,7 @@ function runClientTests(adapterFactory: AdapterFactory) { }) const noDescClient = new Client({ - database, + database: await freshDatabase(), actions: { noDescAction: actionWithoutDescription, }, @@ -1267,7 +1277,7 @@ function runClientTests(adapterFactory: AdapterFactory) { }) const waitClient = new Client({ - database, + database: await freshDatabase(), actions: { waitDescAction: actionWithDesc, }, @@ -1299,7 +1309,7 @@ function runClientTests(adapterFactory: AdapterFactory) { }) const filterClient = new Client({ - database, + database: await freshDatabase(), actions: { filterDescAction: actionWithDesc, }, diff --git a/packages/duron/test/local-cancellation.test.ts b/packages/duron/test/local-cancellation.test.ts index 216e9c4..4ceb976 100644 --- a/packages/duron/test/local-cancellation.test.ts +++ b/packages/duron/test/local-cancellation.test.ts @@ -595,7 +595,7 @@ for (const factory of factories) { 'E5: a rejected write suppresses without replay; periodic recovery later requeues the unexpired job (fault-injected, default recoverJobsOnStart)', async () => { // Startup recovery on (the default): the own id stays in every later recovery. - const h = await harness(factory, { recoverJobsOnStart: true, recoverJobsInterval: 500 }) + const h = await harness(factory, { recoverJobsOnStart: true, recoverJobsInterval: 1_500 }) const startedAt = performance.now() try { let target: string | null = null @@ -629,7 +629,7 @@ for (const factory of factories) { // The next due periodic recovery requeues this Client's own unheld active job, and // the same discovery turn claims it again: the claim is not suppressed. - await Bun.sleep(Math.max(0, startedAt + 600 - performance.now())) + await Bun.sleep(Math.max(0, startedAt + 1_600 - performance.now())) expect((await h.client.fetch()).map((job) => job.id)).toEqual([target]) await eventually( async () => (await status(h.adapter, target!)) === 'completed', @@ -676,7 +676,7 @@ for (const factory of factories) { it( 'E5: after a rejected write an expired job is archived failed by periodic recovery (fault-injected, default recoverJobsOnStart)', async () => { - const h = await harness(factory, { recoverJobsOnStart: true, recoverJobsInterval: 500 }) + const h = await harness(factory, { recoverJobsOnStart: true, recoverJobsInterval: 1_500 }) const startedAt = performance.now() try { let target: string | null = null @@ -691,9 +691,9 @@ for (const factory of factories) { await fetching await h.sentinel() expect(h.starts).not.toContain(target) - // Past the job's 300 ms expiry and the 500 ms recovery interval: the discovery turn + // Past the job's 300 ms expiry and the 1500 ms recovery interval: the discovery turn // of this fetch archives the expired own job before it claims. - await Bun.sleep(Math.max(400, startedAt + 600 - performance.now())) + await Bun.sleep(Math.max(400, startedAt + 1_600 - performance.now())) expect(await h.client.fetch()).toEqual([]) expect(await status(h.adapter, target)).toBe('failed') expect(cancels.for(target)).toHaveLength(1) diff --git a/packages/duron/test/recover-own-jobs.test.ts b/packages/duron/test/recover-own-jobs.test.ts index 6686d80..323b668 100644 --- a/packages/duron/test/recover-own-jobs.test.ts +++ b/packages/duron/test/recover-own-jobs.test.ts @@ -185,14 +185,18 @@ for (const engine of engines) { // A Client uses this adapter (its id becomes the own id). Without the Client's held // ids, a direct call cannot tell which own jobs are running, so it skips them all. - const action = defineAction()({ name: 'own-recovery', handler: async () => ({}) }) - new Client({ + const actions = { + action: defineAction()({ name: 'own-recovery', handler: async () => ({}) }), + } + const client = new Client({ id: OWN, database: adapter, - actions: { action }, + actions, syncPattern: false, logger: 'silent', }) + expect(client.getConfig().actions).toBe(actions) + expect(adapter.id).toBe(OWN) expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) expect(await job(adapter, own)).toMatchObject({ status: 'active', clientId: OWN }) }), diff --git a/packages/duron/test/recover-snapshot.test.ts b/packages/duron/test/recover-snapshot.test.ts index 5d8eec6..fdda0cd 100644 --- a/packages/duron/test/recover-snapshot.test.ts +++ b/packages/duron/test/recover-snapshot.test.ts @@ -1196,8 +1196,8 @@ for (const factory of engines) { expect(statement.sql).not.toContain('ANY(') } - // The first successful recovery above was this adapter's only own-id pass, so the - // jobs below are claimed by a dead owner (no liveness row). + // The jobs below are claimed by a dead owner (no liveness row); the adapter then + // recovers as 'r', which owns no job. // One requeued job. const one = await claimAs(adapter, 'dead', 60_000, OLD_CHECKSUM) adapter.setId('r') diff --git a/packages/duron/test/wait-options.test.ts b/packages/duron/test/wait-options.test.ts index 9be234f..496f889 100644 --- a/packages/duron/test/wait-options.test.ts +++ b/packages/duron/test/wait-options.test.ts @@ -1,23 +1,35 @@ import { expect, it } from 'bun:test' +import type { Adapter } from '../src/adapters/adapter.js' import { Client } from '../src/client.js' import { pgliteFactory } from './adapters.js' it('rejects invalid waitReadTimeout values without coercion or a disable value', async () => { - const { adapter } = await pgliteFactory.create() - adapter.setId('wait-options') + // One Client per adapter: each constructed Client gets its own adapter. + const adapters: Adapter[] = [] + const database = async () => { + const { adapter } = await pgliteFactory.create() + adapter.setId('wait-options') + adapters.push(adapter) + return adapter + } try { - expect(new Client({ database: adapter }).getConfig().waitReadTimeout).toBe(5000) + expect(new Client({ database: await database() }).getConfig().waitReadTimeout).toBe(5000) for (const waitReadTimeout of [1, 5000, 2_147_483_647]) { - expect(new Client({ database: adapter, waitReadTimeout }).getConfig().waitReadTimeout).toBe( - waitReadTimeout, - ) + expect( + new Client({ database: await database(), waitReadTimeout }).getConfig().waitReadTimeout, + ).toBe(waitReadTimeout) } + // A rejected constructor does not bind its adapter, so these can share one. + const rejected = await database() for (const waitReadTimeout of [0, -1, 0.5, 2_147_483_648, NaN, Infinity, '5000', null, false]) { - expect(() => new Client({ database: adapter, waitReadTimeout } as never)).toThrow() + expect(() => new Client({ database: rejected, waitReadTimeout } as never)).toThrow( + /waitReadTimeout|Invalid|expected/i, + ) } + expect(new Client({ database: rejected }).getConfig().waitReadTimeout).toBe(5000) } finally { - await adapter.stop() + for (const adapter of adapters) await adapter.stop() } -}) +}, 20_000) From f38b9a3ad8e85d10e9bb6000ca27e2a7791acce7 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 03:31:03 -0300 Subject: [PATCH 067/100] fix: no Client constructor side effects before its fallible steps R1: the constructor registered a quiesce hook (and, after an invalid logger level, left it on the adapter's lifecycle) and bound the adapter before creating the logger and the tracer. An invalid logger string then made a later Client's stop() reject, and a throwing getTracer left the adapter bound with the rejected id. All fallible steps (telemetry and option checks, id, logger, tracer) now run before the first side effect. Also: docs say an adapter whose Client stopped cannot be reused (A7); the client.test.ts extra databases stop their adapter before the drop and all drops run even if one fails (A8); client.test.ts runs PGlite always and native PostgreSQL only with POSTGRES_TEST (A9). --- packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/src/client.ts | 22 ++++---- .../duron/test/client-adapter-binding.test.ts | 50 +++++++++++++++++++ packages/duron/test/client.test.ts | 17 +++++-- 5 files changed, 78 insertions(+), 15 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 6b7475f..fee67a9 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -29,7 +29,7 @@ const client = duron({ ### `database` -**Required.** The database adapter to use. Use one adapter instance per Client: the Client sets the adapter's client ID and owns its lifecycle (stopping the Client stops the adapter). Creating a second Client with an adapter that a Client already uses throws a `TypeError`. +**Required.** The database adapter to use. Use one adapter instance per Client: the Client sets the adapter's client ID and owns its lifecycle (stopping the Client stops the adapter). Creating a second Client with an adapter that a Client already uses throws a `TypeError`. This includes an adapter whose Client was stopped: a stopped adapter cannot start again, so create a new adapter instance for a new Client. ```ts { diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index ac16302..afcbeec 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -285,7 +285,7 @@ Duron uses heartbeat-based liveness detection for crashed-instance recovery: 2. **Periodic recovery**: A worker with configured actions runs recovery during a discovery turn once more than `recoverJobsInterval` has elapsed (default: 60 seconds), measured with a monotonic process clock from the end of the previous attempt (or from a successful startup recovery). Without startup recovery, the first discovery turn recovers. A failed recovery skips that turn's claim and applies the `pullInterval` cooldown; later turns claim as usual. There is no separate recovery timer: automatic workers check at every `pullInterval`, and with `syncPattern: false` only `client.fetch()` calls run discovery turns. Recovery does not wait for this Client's running jobs and does not pause claiming (see [Worker Discovery](#worker-discovery)). Setting `recoverJobsInterval` to `0` disables periodic recovery. 3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. 4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery does not newly include null owners. - - **Own jobs**: Every startup and periodic recovery also includes the current client ID, regardless of its heartbeat, except for the jobs this Client holds locally: claimed, queued, running or writing their result (including a timed-out handler that still runs). Discovery runs recovery and claims one after the other, so no claim of this Client is in flight during it. This rescues jobs that a previous process with the same ID left active, and this process's own jobs that a rejected write left active: a failed `cancelJob` before the handler started, a failed final `completeJob`/`failJob` write, or a failed cancellation write of a running job that was aborted (that job is requeued and runs again). A job this worker holds is never requeued; a job claimed by a direct `client.database.fetch()` is not held, so it can be. Use one adapter instance per Client; a second Client constructor on an adapter that a Client already uses throws a `TypeError`. + - **Own jobs**: Every startup and periodic recovery also includes the current client ID, regardless of its heartbeat, except for the jobs this Client holds locally: claimed, queued, running or writing their result (including a timed-out handler that still runs). Discovery runs recovery and claims one after the other, so no claim of this Client is in flight during it. This rescues jobs that a previous process with the same ID left active, and this process's own jobs that a rejected write left active: a failed `cancelJob` before the handler started, a failed final `completeJob`/`failJob` write, or a failed cancellation write of a running job that was aborted (that job is requeued and runs again). A job this worker holds is never requeued; a job claimed by a direct `client.database.fetch()` is not held, so it can be. Use one adapter instance per Client; a second Client constructor on an adapter that a Client already uses throws a `TypeError`, also when that Client was stopped (a stopped adapter cannot start again). - **Direct calls**: A direct `client.database.recoverJobs()` call cannot see which jobs the Client holds, so it skips this worker's own ID and rescues only other owners. With `recoverJobsOnStart: false` and `recoverJobsInterval: 0`, Duron runs no recovery, so this worker's own leftovers stay active until this worker stops and its heartbeat goes stale; then other workers' recovery rescues them. 5. **Recovery behavior**: - **Expired jobs** (exceeded timeout): Archived as failed with error information diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 71e1e3c..63d40a4 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -449,15 +449,25 @@ export class Client< 'Client: Clients on one adapter share its client id and lifecycle.', ) } + // Every fallible step (option checks, logger and tracer creation, which can run + // application code) comes before the first side effect on the adapter, so a constructor + // that throws leaves the adapter unbound, with its id, logger and lifecycle unchanged. const telemetry = assertTelemetryOptions(options.telemetry) this.#options = BaseOptionsSchema.parse(options) this.#id = options.id ?? globalThis.crypto.randomUUID() - this.#database = options.database - this.#lifecycle = lifecycleFor(this.#database) - this.#lifecycle.onQuiesce(() => this.#quiesce()) this.#actions = options.actions ?? null this.#variables = options?.variables ?? {} this.#logger = this.#normalizeLogger(options?.logger) + // Telemetry is scoped to this client: the tracer comes from the provider the + // application passed in. Without one, a ProxyTracerProvider with no delegate + // gives a no-op tracer. It never reads the global tracer provider. + const tracerProvider = telemetry?.tracerProvider ?? new ProxyTracerProvider() + this.#tracer = tracerProvider.getTracer(TRACER_NAME) + + // Side effects from here on. + this.#database = options.database + this.#lifecycle = lifecycleFor(this.#database) + this.#lifecycle.onQuiesce(() => this.#quiesce()) this.#database.setId(this.#id) markClientAdapter(this.#database) this.#database.setLogger(this.#logger) @@ -494,12 +504,6 @@ export class Client< this.getJobById === Client.prototype.getJobById && this.start === Client.prototype.start, ) - - // Telemetry is scoped to this client: the tracer comes from the provider the - // application passed in. Without one, a ProxyTracerProvider with no delegate - // gives a no-op tracer. It never reads the global tracer provider. - const tracerProvider = telemetry?.tracerProvider ?? new ProxyTracerProvider() - this.#tracer = tracerProvider.getTracer(TRACER_NAME) } #normalizeLogger( diff --git a/packages/duron/test/client-adapter-binding.test.ts b/packages/duron/test/client-adapter-binding.test.ts index 7a85122..8355a6a 100644 --- a/packages/duron/test/client-adapter-binding.test.ts +++ b/packages/duron/test/client-adapter-binding.test.ts @@ -43,6 +43,56 @@ describe('Client adapter binding', () => { } }) + // A constructor that throws after its option checks must not touch the adapter either. + for (const [name, bad] of [ + ['an invalid logger level', { logger: 'bogus' }], + [ + 'a tracer provider whose getTracer throws', + { + telemetry: { + tracerProvider: { + getTracer: () => { + throw new Error('injected getTracer failure') + }, + }, + }, + }, + ], + ] as const) { + it(`leaves the adapter unbound and unchanged when the constructor throws on ${name}`, async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + adapter.setId('before') + const action = defineAction()({ name: 'unbound', handler: async () => ({}) }) + expect( + () => + new Client({ + id: 'rejected', + database: adapter, + actions: { action }, + syncPattern: false, + ...bad, + } as never), + ).toThrow() + expect(adapter.id).toBe('before') + // A later valid Client binds the adapter and starts and stops cleanly. + const client = new Client({ + id: 'valid', + database: adapter, + actions: { action }, + syncPattern: false, + logger: 'silent', + }) + expect(adapter.id).toBe('valid') + try { + expect(await client.start()).toBe(true) + const jobId = await client.runAction('action', {}) + expect((await client.fetch()).map((job) => job.id)).toEqual([jobId]) + } finally { + expect(await client.stop()).toBe(true) + } + }) + } + it('accepts one Client per adapter instance on the same database', async () => { const action = defineAction()({ name: 'separate', handler: async () => ({}) }) const clients = ['one', 'two'].map( diff --git a/packages/duron/test/client.test.ts b/packages/duron/test/client.test.ts index 7d43706..6146f13 100644 --- a/packages/duron/test/client.test.ts +++ b/packages/duron/test/client.test.ts @@ -145,7 +145,12 @@ function runClientTests(adapterFactory: AdapterFactory) { const extraDbs: Array<() => Promise> = [] async function freshDatabase(): Promise { const instance = await adapterFactory.create({}) - extraDbs.push(instance.deleteDb) + // Stop the adapter first: a test that failed before stopping its Client leaves it open, + // and dropping a database with open connections fails. + extraDbs.push(async () => { + await instance.adapter.stop().catch(() => undefined) + await instance.deleteDb() + }) return instance.adapter } @@ -156,7 +161,10 @@ function runClientTests(adapterFactory: AdapterFactory) { if (deleteDb) { await deleteDb() } - for (const drop of extraDbs.splice(0)) await drop() + // Drop every extra database even if one drop fails; report the first failure. + const drops = await Promise.allSettled(extraDbs.splice(0).map((drop) => drop())) + const failed = drops.find((drop) => drop.status === 'rejected') + if (failed) throw failed.reason }) describe('Lifecycle', () => { @@ -1337,8 +1345,9 @@ function runClientTests(adapterFactory: AdapterFactory) { }) } -runClientTests(postgresFactory) +// PGlite always; native PostgreSQL only with POSTGRES_TEST, like the other suites. +runClientTests(pgliteFactory) // oxlint-disable-next-line useLiteralKeys if (process.env['POSTGRES_TEST'] === 'true') { - runClientTests(pgliteFactory) + runClientTests(postgresFactory) } From b5390b49ea5451a958ffc5cc0f70c62b62a0706a Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 04:48:58 -0300 Subject: [PATCH 068/100] chore: native CI matrix, install docs and review nits (PR #9 review R4 + nits) CI (.github/workflows/test.yml): - Pin Bun 1.4.5 (first stable with `bun check`), `bun install --frozen-lockfile`, add a build step (tsc dist, dashboard, docs). - New `native` job: POSTGRES_TEST=true bun test on postgres:16-alpine and postgres:19-alpine (DURON_TEST_POSTGRES_IMAGE), provisioned by test/docker.ts on the runner's Docker; covers client.test.ts's PostgreSQL path. R4: install docs pin drizzle-orm@1.0.0-rc.6 (the peer range does not accept later RCs). package.json engines: node ^20.19.0 || >=22.12.0. PGlite 0.5.17 suite run manually (documented). Nits: - getJobs: an empty sort array uses the default sort (startedAt desc). - Liveness-table absence before migration: SQLSTATE 42P01 plus a to_regclass probe instead of the locale-dependent message text. - Remove the redundant length check in _recoverJobs. - Client.fetch rejects when start() resolved false instead of hanging. - waitForJob docs: pending waits resolve null on stop, calls after stop reject. - Report quiesce hook failures once, in the stop attempt that observed them. G1 recheck advisories: - A5: stop wakes pending claim-retry delays at once. - A6: a claim failure surfaced by a normal stop is logged at debug level (Adapter.fetch and WorkerDiscovery), not as two errors. - A7: the natural-conflict test allows up to 100 rounds; docs say the 310 ms bound counts only the waits. --- .github/workflows/test.yml | 46 +++++- AGENTS.md | 5 +- README.md | 10 +- packages/docs/content/docs/client-api.mdx | 10 +- .../docs/content/docs/getting-started.mdx | 12 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/README.md | 10 +- packages/duron/package.json | 3 + packages/duron/src/adapters/adapter.ts | 5 +- packages/duron/src/adapters/postgres/base.ts | 147 +++++++++++------- packages/duron/src/client.ts | 11 +- packages/duron/src/lifecycle.ts | 4 +- packages/duron/src/worker-discovery.ts | 4 +- packages/duron/test/adapter.test.ts | 14 +- packages/duron/test/claim-isolation.test.ts | 6 +- packages/duron/test/claim-pglite.test.ts | 95 ++++++++++- .../duron/test/client-adapter-binding.test.ts | 32 ++++ packages/duron/test/lifecycle-errors.test.ts | 17 ++ packages/duron/test/liveness-absence.test.ts | 49 ++++++ packages/duron/test/wait-lifecycle.test.ts | 29 ++++ 20 files changed, 416 insertions(+), 95 deletions(-) create mode 100644 packages/duron/test/liveness-absence.test.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 36ced2a..2654ad0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -4,6 +4,12 @@ on: branches: [main] pull_request: branches: [main] + +# Bun 1.4.5 is the first stable release used here with `bun check` (the typecheck script). +# Keep it pinned so a new Bun release cannot change CI results on its own. +env: + BUN_VERSION: 1.4.5 + jobs: test: timeout-minutes: 60 @@ -11,13 +17,51 @@ jobs: steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 + with: + bun-version: ${{ env.BUN_VERSION }} - name: Install dependencies - run: bun install + run: bun install --frozen-lockfile - name: Run typecheck run: bun run typecheck - name: Run lint run: bun run lint - name: Run format check run: bun run fmt:check + # typecheck uses `bun check`; the published `dist` is emitted by tsc, so build it too. + - name: Build + run: bun run build - name: Run tests run: bun test + + # The native PostgreSQL suite (POSTGRES_TEST=true) on every supported server major. + # test/docker.ts provisions the server itself: it runs DURON_TEST_POSTGRES_IMAGE as the + # container duron-postgres-test- on port 5440 and creates one database per test + # with `docker exec` (createdb/psql/dropdb). The runner's Docker daemon is enough, so no + # `services:` container is used (docker.ts would refuse one that holds port 5440). + native: + timeout-minutes: 60 + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + image: [postgres:16-alpine, postgres:19-alpine] + name: native (${{ matrix.image }}) + env: + POSTGRES_TEST: 'true' + DURON_TEST_POSTGRES_IMAGE: ${{ matrix.image }} + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: ${{ env.BUN_VERSION }} + - name: Install dependencies + run: bun install --frozen-lockfile + # Pull before the tests, so the first test's timeout does not include the download. + - name: Pull PostgreSQL image + run: docker pull "$DURON_TEST_POSTGRES_IMAGE" + # Includes the PostgreSQL path of client.test.ts, which runs only with POSTGRES_TEST. + - name: Run native tests + run: bun test + - name: PostgreSQL container logs + if: failure() + run: docker logs "duron-postgres-test-${DURON_TEST_POSTGRES_IMAGE//[^a-zA-Z0-9_.-]/-}" 2>&1 | tail -200 diff --git a/AGENTS.md b/AGENTS.md index 9c14de1..4ddc787 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,7 +107,10 @@ bun run build:docs # docs only ## CI -Workflow `.github/workflows/test.yml` runs: `bun install` → `typecheck` → `lint` → `test`. +Workflow `.github/workflows/test.yml` (Bun pinned with `BUN_VERSION`, currently 1.4.5) has two jobs: + +- `test`: `bun install --frozen-lockfile` → `typecheck` → `lint` → `fmt:check` → `build` → `bun test` (mostly PGlite; a few suites also run PostgreSQL through `test/docker.ts` without `POSTGRES_TEST`). +- `native`: matrix over `postgres:16-alpine` and `postgres:19-alpine` (`DURON_TEST_POSTGRES_IMAGE`), `POSTGRES_TEST=true bun test`. `test/docker.ts` starts the container on the runner's Docker. ## Branch Workflow diff --git a/README.md b/README.md index 17303e3..397f5a2 100644 --- a/README.md +++ b/README.md @@ -42,16 +42,16 @@ The complete documentation includes detailed guides on actions, adapters, client ### Installation ```bash -bun add duron postgres drizzle-orm@rc @opentelemetry/api +bun add duron postgres drizzle-orm@1.0.0-rc.6 @opentelemetry/api # or -npm install duron postgres drizzle-orm@rc @opentelemetry/api +npm install duron postgres drizzle-orm@1.0.0-rc.6 @opentelemetry/api # or -pnpm add duron postgres drizzle-orm@rc @opentelemetry/api +pnpm add duron postgres drizzle-orm@1.0.0-rc.6 @opentelemetry/api # or -yarn add duron postgres drizzle-orm@rc @opentelemetry/api +yarn add duron postgres drizzle-orm@1.0.0-rc.6 @opentelemetry/api ``` -Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0, on PostgreSQL 16 and 19, and with PGlite 0.6.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0, on PostgreSQL 16 and 19, and with PGlite 0.6.1. Install that exact `drizzle-orm` version: Duron's peer range is `1.0.0-rc.6 || ^1.0.0`, and a later release candidate (such as `drizzle-orm@rc` once rc.7 ships) does not satisfy it. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. `@opentelemetry/api` (`^1.9.0`) is a peer dependency: Duron uses only the OpenTelemetry API, and your application chooses the SDK. See [Telemetry](https://duron-docs.pages.dev/docs/telemetry). diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index fee67a9..6f89b94 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -298,7 +298,7 @@ const jobId = await client.runAction('sendEmail', { Manually fetch and process jobs from the database. -Each call keeps its own batch and returns the jobs it actually claimed, after its claim (not after the handlers finish). Calls are served one at a time together with automatic discovery, in arrival order, so a call can wait behind a running discovery, a due recovery (see `recoverJobsInterval`) or a failure cooldown. A failed call rejects with the original error and is not retried. Calls still waiting when `stop()` begins reject; a call whose claim was already issued returns its jobs, but no handler starts after `stop()`. Direct `client.database.fetch()` calls are outside this coordination. +Each call keeps its own batch and returns the jobs it actually claimed, after its claim (not after the handlers finish). Calls are served one at a time together with automatic discovery, in arrival order, so a call can wait behind a running discovery, a due recovery (see `recoverJobsInterval`) or a failure cooldown. A failed call rejects with the original error and is not retried. Calls still waiting when `stop()` begins reject; a call whose claim was already issued returns its jobs, but no handler starts after `stop()`. If the Client did not start (`start()` resolved `false`, for example because a custom adapter's `start()` declined), the call rejects instead of waiting. Direct `client.database.fetch()` calls are outside this coordination. ```ts const jobs = await client.fetch({ @@ -488,9 +488,9 @@ Job records include input, output, and error, but not steps. A terminal job rest active storage remains visible under its status filter. SQL adapters apply every requested sort key in order, then break ties by job ID in the -direction of the last sort key (ID descending when that key is descending). An empty -sort array uses only ID ascending. The order is total, so while the jobs do not change, -every job appears on exactly one page. The default is `startedAt` descending. Nulls +direction of the last sort key (ID descending when that key is descending). The order +is total, so while the jobs do not change, every job appears on exactly one page. The +default, also for an empty sort array, is `startedAt` descending. Nulls sort last ascending and first descending. Text (`status`, `actionName`, `description`) uses byte order (Unicode code point order in a UTF-8 database): it does not depend on the database locale and, unlike JavaScript UTF-16 order, sorts characters above U+FFFF @@ -644,7 +644,7 @@ const job = await client.waitForJob(jobId) - `options.timeout` - Optional caller waiting timeout in milliseconds. Expiry resolves this waiter to `null`; omission means no caller timeout. This is separate from the Client's `waitReadTimeout`. - `options.signal` - Optional AbortSignal to cancel waiting. If aborted, the promise resolves to `null`. -**Returns:** A terminal result containing `id`, `actionName`, `status`, `groupKey`, `description`, `input`, `output`, and `error`. Returns `null` on caller timeout/abort, stop, initial-check failure/expiry, or missing detail after a terminal status/hint. `null` does not mean the job failed. +**Returns:** A terminal result containing `id`, `actionName`, `status`, `groupKey`, `description`, `input`, `output`, and `error`. Returns `null` on caller timeout/abort, initial-check failure/expiry, missing detail after a terminal status/hint, or when `stop()` begins while the wait is pending. A call made after `stop()` began rejects with `Lifecycle is not accepting work` instead. `null` does not mean the job failed. **Example:** diff --git a/packages/docs/content/docs/getting-started.mdx b/packages/docs/content/docs/getting-started.mdx index d4e00c6..d1fcf23 100644 --- a/packages/docs/content/docs/getting-started.mdx +++ b/packages/docs/content/docs/getting-started.mdx @@ -12,19 +12,19 @@ Install Duron using your preferred package manager: ```bash # Using npm -npm install duron drizzle-orm@rc @opentelemetry/api +npm install duron drizzle-orm@1.0.0-rc.6 @opentelemetry/api # Using pnpm -pnpm add duron drizzle-orm@rc @opentelemetry/api +pnpm add duron drizzle-orm@1.0.0-rc.6 @opentelemetry/api # Using yarn -yarn add duron drizzle-orm@rc @opentelemetry/api +yarn add duron drizzle-orm@1.0.0-rc.6 @opentelemetry/api # Using bun -bun add duron drizzle-orm@rc @opentelemetry/api +bun add duron drizzle-orm@1.0.0-rc.6 @opentelemetry/api ``` -Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0. Install that exact `drizzle-orm` version: Duron's peer range is `1.0.0-rc.6 || ^1.0.0`, and a later release candidate (such as `drizzle-orm@rc` once rc.7 ships) does not satisfy it. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. `@opentelemetry/api` (`^1.9.0`) is a peer dependency: Duron uses only the OpenTelemetry API, and your application chooses the SDK. See [Telemetry](/docs/telemetry). @@ -62,7 +62,7 @@ yarn add @electric-sql/pglite@0.6 bun add @electric-sql/pglite@0.6 ``` -Duron is tested with PGlite 0.6.1 (PostgreSQL 19). PGlite 0.5.17 or later 0.5.x (PostgreSQL 18) is also supported. A persistent PGlite data directory only opens with the PostgreSQL major version that created it: PGlite 0.6 cannot open a directory created by PGlite 0.5, so keep 0.5 for an existing directory or dump and restore its data. +Duron is tested with PGlite 0.6.1 (PostgreSQL 19). PGlite 0.5.17 or later 0.5.x (PostgreSQL 18) is also supported: the PGlite test suite passes with 0.5.17, run manually (CI runs 0.6.1 only). A persistent PGlite data directory only opens with the PostgreSQL major version that created it: PGlite 0.6 cannot open a directory created by PGlite 0.5, so keep 0.5 for an existing directory or dump and restore its data. ## Schema Library diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index afcbeec..964def0 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -226,7 +226,7 @@ The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` t When concurrent claims from different workers would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so conflicts between unrelated groups are possible, for example when every worker claims at the same time after a notification. -The fetch retries a claim rejected with `40001` up to 5 times. Each retry is a new transaction, so it sees the claims that committed in the meantime. It starts after a random delay that grows with each retry (exponential backoff with full jitter): up to 10, 20, 40, 80 and then 160 ms, so the retries add at most about 310 ms to a claim. Retried conflicts are logged at debug level. Only when the last retry also fails does the fetch reject with the original error: a manual `client.fetch()` or `adapter.fetch()` call rejects, and automatic discovery logs the failure once, waits one `pullInterval`, and then makes a new claim; notifications and queued `client.fetch()` calls also wait for that cooldown. Other claim errors are not retried. Handle the rejection of a `fetch()` you start without awaiting. +The fetch retries a claim rejected with `40001` up to 5 times. Each retry is a new transaction, so it sees the claims that committed in the meantime. It starts after a random delay that grows with each retry (exponential backoff with full jitter): up to 10, 20, 40, 80 and then 160 ms, so the waits add at most 310 ms to a claim, plus the time of the retried transactions themselves. Retried conflicts are logged at debug level. Only when the last retry also fails does the fetch reject with the original error: a manual `client.fetch()` or `adapter.fetch()` call rejects, and automatic discovery logs the failure once, waits one `pullInterval`, and then makes a new claim; notifications and queued `client.fetch()` calls also wait for that cooldown. Once `stop()` has begun, no new retry starts and a pending wait ends at once: the claim rejects with its conflict, and that shutdown failure is logged at debug level instead of error. Other claim errors are not retried. Handle the rejection of a `fetch()` you start without awaiting. Limits of this protection: diff --git a/packages/duron/README.md b/packages/duron/README.md index 90f7bf7..0c96532 100644 --- a/packages/duron/README.md +++ b/packages/duron/README.md @@ -6,19 +6,19 @@ A powerful, type-safe job queue system for Node.js and Bun.js. Duron provides a ```bash # Using bun -bun add duron postgres drizzle-orm@rc @opentelemetry/api +bun add duron postgres drizzle-orm@1.0.0-rc.6 @opentelemetry/api # Using npm -npm install duron postgres drizzle-orm@rc @opentelemetry/api +npm install duron postgres drizzle-orm@1.0.0-rc.6 @opentelemetry/api # Using pnpm -pnpm add duron postgres drizzle-orm@rc @opentelemetry/api +pnpm add duron postgres drizzle-orm@1.0.0-rc.6 @opentelemetry/api # Using yarn -yarn add duron postgres drizzle-orm@rc @opentelemetry/api +yarn add duron postgres drizzle-orm@1.0.0-rc.6 @opentelemetry/api ``` -Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0, on PostgreSQL 16 and 19, and with PGlite 0.6.1. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. +Duron is tested with `drizzle-orm` 1.0.0-rc.6 and `postgres` 4.2.0, on PostgreSQL 16 and 19, and with PGlite 0.6.1. Install that exact `drizzle-orm` version: Duron's peer range is `1.0.0-rc.6 || ^1.0.0`, and a later release candidate (such as `drizzle-orm@rc` once rc.7 ships) does not satisfy it. `drizzle-orm` 1.0 is ESM-only, so on Node.js use version `^20.19.0` or `>=22.12.0`. `@opentelemetry/api` (`^1.9.0`) is a peer dependency: Duron uses only the OpenTelemetry API, and your application chooses the SDK. See [Telemetry](https://duron.dev/docs/telemetry). diff --git a/packages/duron/package.json b/packages/duron/package.json index 41fc2ed..73e80c1 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -115,5 +115,8 @@ "postgres": { "optional": true } + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" } } diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index 7e73f7f..38e2633 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -454,7 +454,10 @@ export abstract class Adapter extends EventEmitter { const result = await this._fetch(parsedOptions) return JobsArrayResultSchema.parse(result) } catch (error) { - this.#logger?.error(error, 'Error in Adapter.fetch()') + // A claim that fails once stop began (for example a conflict it no longer retries) + // is part of a normal shutdown: report it at debug level. + if (this.#lifecycle.accepting) this.#logger?.error(error, 'Error in Adapter.fetch()') + else this.#logger?.debug(error, 'Error in Adapter.fetch()') throw error } }) diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index d0d286d..f76444a 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -52,6 +52,7 @@ import { type GetJobsOptions, type GetJobsResult, type Job, + type JobSort, type JobStatusResult, type JobStep, type JobStepStatusResult, @@ -142,6 +143,7 @@ export abstract class PostgresBaseAdapter< private lastPrunedAt: Date | null = null private initialized = false protected ownedClosed = false + private readonly claimRetryWakers = new Set<() => void>() private listenerObligations: Array<{ done: boolean }> = [] private readonly waitReadContext = new AsyncLocalStorage<{ db: DrizzleDatabase @@ -172,7 +174,12 @@ export abstract class PostgresBaseAdapter< this._initDb() this._guardTransactions() registerWaitReadExecutor(this, (budget, work) => this._executeWaitRead(budget, work)) - lifecycleFor(this).onQuiesce(() => this._stopScheduler()) + lifecycleFor(this).onQuiesce(() => { + this._stopScheduler() + // Stop ends pending claim-retry delays at once; their claims then surface the conflict. + // Each waker deletes itself; deleting the current entry is safe during Set iteration. + for (const wake of this.claimRetryWakers) wake() + }) } /** @@ -267,7 +274,7 @@ export abstract class PostgresBaseAdapter< WHERE last_seen_at < now() - interval '24 hours' `) } catch (error) { - if (!this._isUninitializedLivenessAbsence(error)) throw error + if (!(await this._isUninitializedLivenessAbsence(error))) throw error } if (!lifecycleFor(this).accepting) return @@ -377,26 +384,31 @@ export abstract class PostgresBaseAdapter< .delete(this.tables.clientsTable) .where(eq(this.tables.clientsTable.client_id, this.id)) } catch (error) { - if (!this._isUninitializedLivenessAbsence(error)) throw error + if (!(await this._isUninitializedLivenessAbsence(error))) throw error } } - private _isUninitializedLivenessAbsence(error: unknown): boolean { + // Before migration, a liveness statement fails with SQLSTATE 42P01 (undefined_table). + // The SQLSTATE plus a to_regclass probe of the clients table identify that case, not the + // message text, which follows the server's lc_messages locale. Any other missing relation + // (the probe finds the clients table) is rethrown. + private async _isUninitializedLivenessAbsence(error: unknown): Promise { if (this.initialized) return false let cause = error const seen = new Set() + let undefinedTable = false while (cause instanceof Error && !seen.has(cause)) { seen.add(cause) - if ( - 'code' in cause && - cause.code === '42P01' && - cause.message === `relation "${this.schema}.clients" does not exist` - ) { - return true - } + if ('code' in cause && cause.code === '42P01') undefinedTable = true cause = cause.cause } - return false + if (!undefinedTable) return false + const [row] = this._map( + await this.db.execute<{ missing: boolean }>( + sql`SELECT to_regclass(format('%I.%I', ${this.schema}::text, 'clients')) IS NULL AS missing`, + ), + ) + return row?.missing === true } /** @@ -1220,13 +1232,29 @@ export abstract class PostgresBaseAdapter< { err: conflict, attempt, retries: CLAIM_CONFLICT_RETRIES, delay }, 'Retrying claim conflict (SQLSTATE 40001)', ) - await new Promise((resolve) => setTimeout(resolve, delay)) - // Stop began during the delay: surface the conflict instead of claiming again. + await this._claimRetryDelay(delay) + // Stop began during the delay (which it ends early): surface the conflict instead + // of claiming again. if (!lifecycle.accepting) throw error } } } + /** Wait `delay` ms, or less when stop begins (quiesce wakes the waiter). */ + private _claimRetryDelay(delay: number): Promise { + return new Promise((resolve) => { + // Stop may have begun since the pre-delay check (for example from the retry log). + if (!lifecycleFor(this).accepting) return resolve() + const wake = () => { + clearTimeout(timer) + this.claimRetryWakers.delete(wake) + resolve() + } + const timer = setTimeout(wake, delay) + this.claimRetryWakers.add(wake) + }) + } + /** One claim attempt in its own SERIALIZABLE transaction. */ private async _claim(batch: number): Promise { let claim: Promise | undefined @@ -1451,51 +1479,50 @@ export abstract class PostgresBaseAdapter< `, ) - if (unresponsiveClientIds.length > 0) { - recoveredCount += await this._recoverLockedJobs( - sql` - SELECT j.id - FROM ${this.tables.jobsActiveTable} j - WHERE j.status = ${JOB_STATUS_ACTIVE} - AND j.client_id IN ${unresponsiveClientIds} - AND (j.expires_at IS NULL OR j.expires_at > now()) - ${notHeld} - FOR UPDATE OF j SKIP LOCKED - `, - (lockedIds) => sql` - WITH locked_jobs AS ( - SELECT j.id - FROM ${this.tables.jobsActiveTable} j - WHERE j.status = ${JOB_STATUS_ACTIVE} - AND j.client_id IN ${unresponsiveClientIds} - AND (j.expires_at IS NULL OR j.expires_at > now()) - AND j.id = ANY(${lockedIds}) - FOR UPDATE OF j SKIP LOCKED - ), - updated_jobs AS ( - UPDATE ${this.tables.jobsActiveTable} j - SET status = ${JOB_STATUS_CREATED}, - started_at = NULL, - expires_at = NULL, - finished_at = NULL, - output = NULL, - error = NULL, - updated_at = now() - WHERE EXISTS (SELECT 1 FROM locked_jobs lj WHERE lj.id = j.id) - RETURNING id, checksum - ), - deleted_steps AS ( - DELETE FROM ${this.tables.jobStepsActiveTable} s - WHERE EXISTS ( - SELECT 1 FROM updated_jobs uj - WHERE uj.id = s.job_id - AND uj.checksum NOT IN ${checksums} - ) - ) - SELECT id FROM updated_jobs + // Requeue unexpired active jobs from unresponsive clients + recoveredCount += await this._recoverLockedJobs( + sql` + SELECT j.id + FROM ${this.tables.jobsActiveTable} j + WHERE j.status = ${JOB_STATUS_ACTIVE} + AND j.client_id IN ${unresponsiveClientIds} + AND (j.expires_at IS NULL OR j.expires_at > now()) + ${notHeld} + FOR UPDATE OF j SKIP LOCKED `, + (lockedIds) => sql` + WITH locked_jobs AS ( + SELECT j.id + FROM ${this.tables.jobsActiveTable} j + WHERE j.status = ${JOB_STATUS_ACTIVE} + AND j.client_id IN ${unresponsiveClientIds} + AND (j.expires_at IS NULL OR j.expires_at > now()) + AND j.id = ANY(${lockedIds}) + FOR UPDATE OF j SKIP LOCKED + ), + updated_jobs AS ( + UPDATE ${this.tables.jobsActiveTable} j + SET status = ${JOB_STATUS_CREATED}, + started_at = NULL, + expires_at = NULL, + finished_at = NULL, + output = NULL, + error = NULL, + updated_at = now() + WHERE EXISTS (SELECT 1 FROM locked_jobs lj WHERE lj.id = j.id) + RETURNING id, checksum + ), + deleted_steps AS ( + DELETE FROM ${this.tables.jobStepsActiveTable} s + WHERE EXISTS ( + SELECT 1 FROM updated_jobs uj + WHERE uj.id = s.job_id + AND uj.checksum NOT IN ${checksums} + ) ) - } + SELECT id FROM updated_jobs + `, + ) return recoveredCount } @@ -2195,8 +2222,10 @@ export abstract class PostgresBaseAdapter< const [count] = await this.db .select({ total: sql`count(*)`.mapWith(Number) }) .from(matchingIds) - const sortInput = options?.sort ?? { field: 'startedAt', order: 'desc' } - const sorts = Array.isArray(sortInput) ? sortInput : [sortInput] + // No sort, or an empty sort array, uses the default sort (as the server does). + const sortInput = options?.sort ?? [] + const sorts: JobSort[] = Array.isArray(sortInput) ? [...sortInput] : [sortInput] + if (sorts.length === 0) sorts.push({ field: 'startedAt', order: 'desc' }) // Sort keys are the stored columns so the per-table (column, id) indexes can serve them // (Merge Append over index scans of jobs_active and jobs_archive): // - timestamps sort by their stored (microsecond) precision; diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 63d40a4..1dd264a 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -769,17 +769,22 @@ export class Client< * Calls are served one at a time with automatic discovery; a call may wait behind an * admitted chain (including a due recovery) or a failure cooldown. It returns after its claim, * not after the claimed handlers finish. Without actions it returns [] without claiming. + * Rejects when the Client did not start (`start()` resolved `false`), instead of waiting + * for a discovery that never runs. * * @param [options.batchSize] - Maximum number of jobs to fetch in this batch (defaults to `batchSize` from client options) * @returns Promise resolving to the array of fetched jobs */ async fetch(options: FetchOptions = {}) { return this.#lifecycle.run(async () => { - await this.start() + const started = await this.start() if (!this.#discovery) { return [] } + if (!started) { + throw new Error('Client is not started: start() resolved false') + } return this.#discovery.fetch(options.batchSize ?? this.#options.batchSize) }) @@ -988,7 +993,9 @@ export class Client< * * @param jobId - The ID of the job to wait for * @param options - Optional configuration including timeout - * @returns Terminal result, or null on timeout/abort/stop, initial read failure/expiry, or missing detail + * @returns Terminal result, or null on timeout/abort, initial read failure/expiry, missing + * detail, or when `stop()` begins while the wait is pending. A call made after `stop()` + * began rejects (`Lifecycle is not accepting work`) instead of returning null. */ async waitForJob( jobId: string, diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index 8dc4b8e..839ffd6 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -328,8 +328,10 @@ export class Lifecycle { await this.#settlePhase('startup settlement', this.#startupWork, failures) this.#drained = await this.#settlePhase('admitted-work drain', this.#work, failures) this.#ordinaryOpen = false + // Report quiesce failures once, in the attempt that observed them; a repeated stop + // then returns true when nothing else failed. failures.push( - ...this.#quiesceFailures.map((error): LifecycleFailure => ({ + ...this.#quiesceFailures.splice(0).map((error): LifecycleFailure => ({ error, phase: 'admitted-work drain', })), diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index c7d5c33..f26d9de 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -292,7 +292,9 @@ export class WorkerDiscovery { if (request.kind === 'manual') { request.reject(error) } else { - this.#options.logger.error( + // After stop began, a failed chain is part of a normal shutdown: debug, not error. + const stopping = this.#stopped || !this.#options.lifecycle.accepting + this.#options.logger[stopping ? 'debug' : 'error']( { error, stage, triggers: [...request.triggers] }, `[Duron] [WorkerDiscovery] Background ${stage} failed`, ) diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index 8987d43..880ffa6 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -708,7 +708,8 @@ function runAdapterTests(adapterFactory: AdapterFactory) { expect(secondary.jobs.map((job) => job.id)).toEqual([ids[1]!, ids[3]!, ids[2]!, ids[0]!]) expect(secondary.total).toBe(4) for (const [sort, expected] of [ - [[], ids], + // An empty sort is the default (startedAt desc): all unstarted, so id desc. + [[], ids.toReversed()], [[{ field: 'description', order: 'asc' }], ids], [[{ field: 'description', order: 'desc' }], ids.toReversed()], [ @@ -1037,9 +1038,10 @@ function runAdapterTests(adapterFactory: AdapterFactory) { } } try { + // `sort: []` uses the default sort (startedAt desc): all unstarted, so id desc. for (const [page, expected] of [ - [1, [ids[0]!, ids[1]!]], - [2, [ids[2]!, ids[3]!]], + [1, [ids[5]!, ids[4]!]], + [2, [ids[3]!, ids[2]!]], [9, []], ] as const) { payloadBatches.length = 0 @@ -1168,9 +1170,13 @@ function runAdapterTests(adapterFactory: AdapterFactory) { cases.push([{ [field]: new Date('2026-01-01T00:00:01Z') }, [1, 2]]) } for (const [filters, expected] of cases) { + // `sort: []` uses the default sort: startedAt desc, seeded in rank order. const result = await adapter.getJobs({ filters, sort: [], pageSize: 2 }) expect(result.jobs.map((job) => job.id)).toEqual( - expected.slice(0, 2).map((rank) => ids[rank]!), + expected + .toReversed() + .slice(0, 2) + .map((rank) => ids[rank]!), ) expect(result.total).toBe(expected.length) const empty = await adapter.getJobs({ filters, sort: [], page: 9, pageSize: 2 }) diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 63d5f68..2cffdd2 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -914,7 +914,9 @@ suite('Native PostgreSQL claim admission', () => { // A round has a natural conflict only sometimes, so rounds repeat (bounded) until // at least one conflict was retried. let active = 0 - for (let round = 0; round < 40 && conflicts().length === 0; round++) { + // 100 rounds (measured: at most 14 needed) leave margin for quiet or slow CI runners; + // a round takes tens of milliseconds. + for (let round = 0; round < 100 && conflicts().length === 0; round++) { const ids = await createJobs(claimers[0]!.adapter, 30, 10_000) const claimed: string[] = [] // Every claimer claims in a tight loop until a claim comes back empty. @@ -948,5 +950,5 @@ suite('Native PostgreSQL claim admission', () => { } finally { await db.cleanup() } - }, 30_000) + }, 60_000) }) diff --git a/packages/duron/test/claim-pglite.test.ts b/packages/duron/test/claim-pglite.test.ts index 4c5e80b..c9b581f 100644 --- a/packages/duron/test/claim-pglite.test.ts +++ b/packages/duron/test/claim-pglite.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'bun:test' +import { describe, expect, it, spyOn } from 'bun:test' import type { PGlite } from '@electric-sql/pglite' import pino from 'pino' @@ -273,6 +273,99 @@ describe('PGLite claim transaction', () => { }) } + // Serial: it pins the global Math.random so the last backoff is its full 160 ms. + it.serial('stop ends a pending claim-retry delay at once', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + adapter.setId('claim-pglite') + const random = spyOn(Math, 'random').mockReturnValue(0.999) + let stopping: Promise | undefined + let stopAt = 0 + adapter.setLogger( + pino( + { level: 'debug' }, + { + write: (line: string) => { + const entry = JSON.parse(line) + // Stop 20 ms into the 160 ms delay before the 5th retry. + if (/claim conflict/.test(entry['msg']) && entry['attempt'] === 5) { + expect(entry['delay']).toBe(160) + setTimeout(() => { + stopAt = performance.now() + stopping ??= adapter.stop() + }, 20) + } + }, + }, + ), + ) + try { + await adapter.start() + await injectSerializationFailures(engineOf(adapter), null) + await createJobs(adapter, 1, 1) + const failed = await adapter.fetch({ batch: 1 }).then( + () => null, + (error: unknown) => error, + ) + const surfacedAfter = performance.now() - stopAt + expect(sqlState(failed)).toBe('40001') + expect(stopAt).toBeGreaterThan(0) + // The delay ended with the stop, well before its 160 ms. + expect(surfacedAfter).toBeLessThan(100) + expect(await stopping).toBe(true) + } finally { + random.mockRestore() + await adapter.stop() + } + }) + + it('logs a claim conflict surfaced by a normal stop at debug level, not as errors', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + const entries: Array> = [] + let client: Client | null = null + let stopRequested = false + const stopped = Promise.withResolvers() + const logger = pino( + { level: 'debug' }, + { + write: (line: string) => { + const entry = JSON.parse(line) + entries.push(entry) + // The first retried conflict of the startup claim: stop the Client now. + if (/claim conflict/.test(entry['msg']) && !stopRequested) { + stopRequested = true + client!.stop().then(stopped.resolve, stopped.reject) + } + }, + }, + ) + const action = defineAction()({ + name: 'claim-stop', + input: z.object({}), + output: z.object({}), + handler: async () => ({}), + }) + // The job exists before start, so the startup claim conflicts (persistent fault). + client = new Client({ + database: adapter, + actions: { claimStop: action }, + syncPattern: 'pull', + pullInterval: 60_000, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger, + }) + adapter.setId('claim-stop') + expect(await adapter.start()).toBe(true) + await injectSerializationFailures(engineOf(adapter), null) + await createJobs(adapter, 1, 1) + expect(await client.start()).toBe(true) + expect(await Promise.race([stopped.promise, Bun.sleep(5_000).then(() => 'no stop')])).toBe(true) + // The surfaced conflict is reported at debug level by the adapter and by discovery. + expect(entries.filter((entry) => entry['level'] >= 50)).toEqual([]) + expect(entries.some((entry) => entry['msg'] === 'Error in Adapter.fetch()')).toBe(true) + expect(entries.some((entry) => /Background claim failed/.test(entry['msg']))).toBe(true) + }) + it('does not pause Client discovery for a single claim conflict', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) const logs = captureLogs() diff --git a/packages/duron/test/client-adapter-binding.test.ts b/packages/duron/test/client-adapter-binding.test.ts index 8355a6a..e361680 100644 --- a/packages/duron/test/client-adapter-binding.test.ts +++ b/packages/duron/test/client-adapter-binding.test.ts @@ -112,3 +112,35 @@ describe('Client adapter binding', () => { } }) }) + +describe('Client.fetch without a started Client', () => { + it('rejects instead of hanging when start() resolves false while the lifecycle accepts work', async () => { + // A public Adapter.start override that declines to start. + class DecliningAdapter extends PGLiteAdapter { + override async start() { + return false + } + } + const adapter = new DecliningAdapter({ connection: ':memory:' }) + const action = defineAction()({ name: 'declined', handler: async () => ({}) }) + const client = new Client({ + database: adapter, + actions: { action }, + syncPattern: false, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(false) + const outcome = await Promise.race([ + client.fetch().then( + () => 'fulfilled', + (error: Error) => error.message, + ), + Bun.sleep(2_000).then(() => 'hung'), + ]) + expect(outcome).toBe('Client is not started: start() resolved false') + } finally { + await client.stop() + } + }) +}) diff --git a/packages/duron/test/lifecycle-errors.test.ts b/packages/duron/test/lifecycle-errors.test.ts index bcb9015..7a205b3 100644 --- a/packages/duron/test/lifecycle-errors.test.ts +++ b/packages/duron/test/lifecycle-errors.test.ts @@ -4,6 +4,7 @@ import { type SQL, sql } from 'drizzle-orm' import postgres from 'postgres' import { Client } from '../src/client.js' +import { lifecycleFor } from '../src/lifecycle.js' import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' @@ -26,6 +27,22 @@ for (const factory of [ ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), ]) { describe(`Lifecycle errors with ${factory.name}`, () => { + it('reports a quiesce hook failure in the stop attempt that observed it, not in later ones', async () => { + const instance = await factory.create() + const adapter = instance.adapter + adapter.setId('quiesce-failure') + try { + expect(await adapter.start()).toBe(true) + lifecycleFor(adapter).onQuiesce(() => Promise.reject(new Error('injected quiesce failure'))) + await expect(adapter.stop()).rejects.toThrow('injected quiesce failure') + // The failure was reported once; a repeated stop has nothing left to report. + expect(await adapter.stop()).toBe(true) + } finally { + await adapter.stop().catch(() => undefined) + await instance.deleteDb() + } + }) + it('does not suppress an expected-relation absence after successful initialization', async () => { const instance = await factory.create() const adapter = instance.adapter as ErrorProbe diff --git a/packages/duron/test/liveness-absence.test.ts b/packages/duron/test/liveness-absence.test.ts new file mode 100644 index 0000000..8464998 --- /dev/null +++ b/packages/duron/test/liveness-absence.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'bun:test' + +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' + +// Before migration (migrateOnStart: false, no tables yet), start skips the missing liveness +// table. The check uses SQLSTATE 42P01, not the server's message text, which +// depends on lc_messages. Fault-injected: the real 42P01 error is rethrown with a localized +// message, as a non-English server would report it. + +function localizeUndefinedTable(adapter: PGLiteAdapter) { + const db = (adapter as unknown as { db: { execute: (...args: unknown[]) => Promise } }) + .db + const execute = db.execute.bind(db) + let localized = 0 + db.execute = async (...args: unknown[]) => { + try { + return await execute(...args) + } catch (error) { + const code = (error as { code?: string; cause?: { code?: string } }).code + const causeCode = (error as { cause?: { code?: string } }).cause?.code + if (code !== '42P01' && causeCode !== '42P01') throw error + localized++ + throw Object.assign(new Error('Failed query'), { + cause: Object.assign(new Error('la relation « duron.clients » n’existe pas'), { + code: '42P01', + }), + }) + } + } + return () => localized +} + +describe('Liveness table absence before migration', () => { + it('start skips a missing clients table whatever the server message language', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:', migrateOnStart: false }) + adapter.setId('unmigrated') + const localized = localizeUndefinedTable(adapter) + expect(await adapter.start()).toBe(true) + expect(localized()).toBe(1) + // A started adapter releases its liveness row on stop; give it a table to delete from. + const engine = ( + adapter as unknown as { db: { $client: { exec: (q: string) => Promise } } } + ).db.$client + await engine.exec( + 'CREATE SCHEMA IF NOT EXISTS duron; CREATE TABLE duron.clients (client_id text PRIMARY KEY)', + ) + expect(await adapter.stop()).toBe(true) + }) +}) diff --git a/packages/duron/test/wait-lifecycle.test.ts b/packages/duron/test/wait-lifecycle.test.ts index 6ce8346..24a1f44 100644 --- a/packages/duron/test/wait-lifecycle.test.ts +++ b/packages/duron/test/wait-lifecycle.test.ts @@ -9,6 +9,35 @@ for (const factory of [ ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), ]) { describe(`Wait lifecycle with ${factory.name}`, () => { + it('resolves a pending wait with null on stop; a wait started after stop rejects', async () => { + const instance = await factory.create() + const client = new Client({ + database: instance.adapter, + syncPattern: false, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + const jobId = await instance.adapter.createJob({ + queue: 'wait-stop', + groupKey: '@default', + input: {}, + timeoutMs: 60_000, + checksum: 'wait-stop', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + const pending = client.waitForJob(jobId!) + await Bun.sleep(50) + expect(await client.stop()).toBe(true) + expect(await pending).toBeNull() + await expect(client.waitForJob(jobId!)).rejects.toThrow('Lifecycle is not accepting work') + } finally { + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }) + for (const waitReadTimeout of [40, 15_000]) { it(`retains the shared five-second drain with a ${waitReadTimeout}ms read budget`, async () => { const instance = await factory.create() From ca825e989887937f8ab2f10434773c5fa2469186 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 05:10:29 -0300 Subject: [PATCH 069/100] fix: CI build on a clean checkout; narrower shutdown log demotion (G3 review) R1: duron-dashboard's build:get-html (tsconfig.node.json types: ["node"]) needs @types/node, which resolved only from a node_modules directory outside the repo. Add it as a dashboard devDependency (bun.lock: one line). Verified from a git archive in /tmp with Bun 1.4.5: frozen install, typecheck, lint, fmt:check, build and bun test pass; the archive of b5390b4 fails with TS2688. A1: after stop began, only failures that stopping causes (stop-gate refusals, a claim 40001 no longer retried) are logged at debug; other claim errors stay at error level (new internal isStopFailure). A2: a failing to_regclass probe is logged and the original 42P01 is rethrown. A3: Client.fetch racing stop rejects with the stop-gate refusal. --- bun.lock | 1 + packages/duron-dashboard/package.json | 1 + packages/duron/src/adapters/adapter.ts | 13 +++--- packages/duron/src/adapters/postgres/base.ts | 21 +++++++--- packages/duron/src/client.ts | 2 + packages/duron/src/lifecycle.ts | 26 ++++++++++++ packages/duron/src/worker-discovery.ts | 7 ++-- packages/duron/test/claim-pglite.test.ts | 42 +++++++++++++++++++ .../duron/test/client-adapter-binding.test.ts | 18 ++++++++ packages/duron/test/liveness-absence.test.ts | 39 +++++++++++++++++ 10 files changed, 156 insertions(+), 14 deletions(-) diff --git a/bun.lock b/bun.lock index c17688b..31c1545 100644 --- a/bun.lock +++ b/bun.lock @@ -117,6 +117,7 @@ }, "devDependencies": { "@types/bun": "latest", + "@types/node": "^26.6.11", "@types/react": "^19.3.3", "@types/react-dom": "^19.3.0", "tailwindcss": "^4.3.5", diff --git a/packages/duron-dashboard/package.json b/packages/duron-dashboard/package.json index 3c8e24c..d6db742 100644 --- a/packages/duron-dashboard/package.json +++ b/packages/duron-dashboard/package.json @@ -73,6 +73,7 @@ }, "devDependencies": { "@types/bun": "latest", + "@types/node": "^26.6.11", "@types/react": "^19.3.3", "@types/react-dom": "^19.3.0", "tailwindcss": "^4.3.5", diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index 38e2633..c205621 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -9,7 +9,7 @@ import { JOB_STATUS_FAILED, type JobStatus, } from '../constants.js' -import { lifecycleFor } from '../lifecycle.js' +import { isStopFailure, lifecycleFor } from '../lifecycle.js' import { usedByClient } from '../recovery-scope.js' import { @@ -454,10 +454,13 @@ export abstract class Adapter extends EventEmitter { const result = await this._fetch(parsedOptions) return JobsArrayResultSchema.parse(result) } catch (error) { - // A claim that fails once stop began (for example a conflict it no longer retries) - // is part of a normal shutdown: report it at debug level. - if (this.#lifecycle.accepting) this.#logger?.error(error, 'Error in Adapter.fetch()') - else this.#logger?.debug(error, 'Error in Adapter.fetch()') + // A claim that stopping made fail (a conflict it no longer retries, a stop-gate + // refusal) is part of a normal shutdown: debug level. Other errors stay errors. + if (!this.#lifecycle.accepting && isStopFailure(error)) { + this.#logger?.debug(error, 'Error in Adapter.fetch()') + } else { + this.#logger?.error(error, 'Error in Adapter.fetch()') + } throw error } }) diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index f76444a..c739c9b 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -403,12 +403,21 @@ export abstract class PostgresBaseAdapter< cause = cause.cause } if (!undefinedTable) return false - const [row] = this._map( - await this.db.execute<{ missing: boolean }>( - sql`SELECT to_regclass(format('%I.%I', ${this.schema}::text, 'clients')) IS NULL AS missing`, - ), - ) - return row?.missing === true + try { + const [row] = this._map( + await this.db.execute<{ missing: boolean }>( + sql`SELECT to_regclass(format('%I.%I', ${this.schema}::text, 'clients')) IS NULL AS missing`, + ), + ) + return row?.missing === true + } catch (probeError) { + // The caller rethrows the original 42P01; the probe's own failure is only logged. + this.logger?.error( + { err: probeError, original: error }, + 'Liveness table probe failed; rethrowing the original error', + ) + return false + } } /** diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 1dd264a..21d9af4 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -783,6 +783,8 @@ export class Client< return [] } if (!started) { + // Stop began (start() declines then): the usual stop-gate refusal. + if (!this.#lifecycle.accepting) throw new Error('Lifecycle is not accepting work') throw new Error('Client is not started: start() resolved false') } diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index 839ffd6..aa024d1 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -15,6 +15,32 @@ export function lifecycleFor(adapter: object): Lifecycle { return lifecycle } +// Refusals of the stop gate (lifecycle and adapter admission, SQL continuation). +const STOP_GATE_MESSAGES = new Set([ + 'Lifecycle is not accepting work', + 'Lifecycle ordinary work has drained', + 'Lifecycle SQL resources are unavailable', + 'Adapter is not accepting work', +]) + +/** + * Internal: true when `error`, or one of its causes, is a failure that stopping causes or + * explains: a stop-gate refusal, or a claim serialization failure (SQLSTATE 40001) that is + * no longer retried once stop began. Callers log these at debug level after stop began; + * every other error keeps its error level. + */ +export function isStopFailure(error: unknown): boolean { + const seen = new Set() + let cause = error + while (cause instanceof Error && !seen.has(cause)) { + seen.add(cause) + if (STOP_GATE_MESSAGES.has(cause.message)) return true + if ('code' in cause && cause.code === '40001') return true + cause = cause.cause + } + return false +} + // A deadline bounds observation, not execution. The losing promise remains observed. class ShutdownBudget { readonly #deadline = performance.now() + 5_000 diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index f26d9de..9c2ffc4 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -1,7 +1,7 @@ import type { Logger } from 'pino' import type { Job } from './adapters/adapter.js' -import type { Lifecycle } from './lifecycle.js' +import { type Lifecycle, isStopFailure } from './lifecycle.js' export type DiscoveryTrigger = 'startup' | 'periodic' | 'hint' @@ -292,9 +292,10 @@ export class WorkerDiscovery { if (request.kind === 'manual') { request.reject(error) } else { - // After stop began, a failed chain is part of a normal shutdown: debug, not error. + // After stop began, a chain that stopping made fail is part of a normal shutdown: + // debug, not error. Other failures stay errors. const stopping = this.#stopped || !this.#options.lifecycle.accepting - this.#options.logger[stopping ? 'debug' : 'error']( + this.#options.logger[stopping && isStopFailure(error) ? 'debug' : 'error']( { error, stage, triggers: [...request.triggers] }, `[Duron] [WorkerDiscovery] Background ${stage} failed`, ) diff --git a/packages/duron/test/claim-pglite.test.ts b/packages/duron/test/claim-pglite.test.ts index c9b581f..ee0e2f1 100644 --- a/packages/duron/test/claim-pglite.test.ts +++ b/packages/duron/test/claim-pglite.test.ts @@ -366,6 +366,48 @@ describe('PGLite claim transaction', () => { expect(entries.some((entry) => /Background claim failed/.test(entry['msg']))).toBe(true) }) + it('keeps a claim failure that stopping did not cause at error level during stop', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + const entries: Array> = [] + const logger = pino( + { level: 'debug' }, + { write: (line: string) => entries.push(JSON.parse(line)) }, + ) + const action = defineAction()({ + name: 'claim-broken', + input: z.object({}), + output: z.object({}), + handler: async () => ({}), + }) + const client = new Client({ + database: adapter, + actions: { claimBroken: action }, + syncPattern: 'pull', + pullInterval: 60_000, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger, + }) + // Fault-injected: the startup claim begins, stop begins while it is in flight, then the + // claim fails with an error unrelated to stopping (as a broken schema would). + let stopRequested = false + const stopped = Promise.withResolvers() + const target = adapter as unknown as { _fetch: (options: FetchOptions) => Promise } + target._fetch = async () => { + if (!stopRequested) { + stopRequested = true + client.stop().then(stopped.resolve, stopped.reject) + } + await Bun.sleep(10) + throw new Error('injected unrelated claim failure') + } + expect(await client.start()).toBe(true) + expect(await Promise.race([stopped.promise, Bun.sleep(5_000).then(() => 'no stop')])).toBe(true) + const errors = entries.filter((entry) => entry['level'] >= 50).map((entry) => entry['msg']) + expect(errors).toContain('Error in Adapter.fetch()') + expect(errors.some((msg) => /Background claim failed/.test(msg))).toBe(true) + }) + it('does not pause Client discovery for a single claim conflict', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) const logs = captureLogs() diff --git a/packages/duron/test/client-adapter-binding.test.ts b/packages/duron/test/client-adapter-binding.test.ts index e361680..7008c43 100644 --- a/packages/duron/test/client-adapter-binding.test.ts +++ b/packages/duron/test/client-adapter-binding.test.ts @@ -144,3 +144,21 @@ describe('Client.fetch without a started Client', () => { } }) }) + +describe('Client.fetch racing stop', () => { + it('rejects with the stop-gate refusal when stop begins before the Client started', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + const action = defineAction()({ name: 'raced', handler: async () => ({}) }) + const client = new Client({ + database: adapter, + actions: { action }, + syncPattern: false, + logger: 'silent', + }) + // fetch() is admitted synchronously; stop() begins before its start() runs. + const fetching = client.fetch() + const stopping = client.stop() + await expect(fetching).rejects.toThrow('Lifecycle is not accepting work') + expect(await stopping).toBe(true) + }) +}) diff --git a/packages/duron/test/liveness-absence.test.ts b/packages/duron/test/liveness-absence.test.ts index 8464998..2efa102 100644 --- a/packages/duron/test/liveness-absence.test.ts +++ b/packages/duron/test/liveness-absence.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'bun:test' +import { type SQL } from 'drizzle-orm' +import { PgDialect } from 'drizzle-orm/pg-core' +import pino from 'pino' + import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' // Before migration (migrateOnStart: false, no tables yet), start skips the missing liveness @@ -47,3 +51,38 @@ describe('Liveness table absence before migration', () => { expect(await adapter.stop()).toBe(true) }) }) + +describe('Liveness table probe failure', () => { + it('rethrows the original 42P01 and logs the probe failure', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:', migrateOnStart: false }) + adapter.setId('unmigrated-probe') + const entries: Array> = [] + adapter.setLogger( + pino({ level: 'error' }, { write: (line: string) => entries.push(JSON.parse(line)) }), + ) + // Fault-injected: the to_regclass probe fails (as a broken connection would). + const db = (adapter as unknown as { db: { execute: (query: SQL) => Promise } }).db + const execute = db.execute.bind(db) + db.execute = async (query: SQL) => { + const text = new PgDialect().sqlToQuery(query).sql + if (text.includes('to_regclass')) throw new Error('injected probe failure') + return execute(query) + } + const failure = await adapter.start().then( + () => null, + (error: unknown) => error, + ) + // Startup fails, and so does its automatic cleanup (its liveness delete hits the same + // missing table and failing probe): both report the original 42P01, not the probe error. + const reported = failure instanceof AggregateError ? failure.errors : [failure] + const codes: unknown[] = [] + for (const error of reported) { + for (let cause = error as any; cause; cause = cause.cause) codes.push(cause.code) + } + expect(codes).toContain('42P01') + expect(reported.some((error) => String(error).includes('injected probe failure'))).toBe(false) + const probe = entries.find((entry) => /Liveness table probe failed/.test(entry['msg'])) + expect(probe?.['err']?.['message']).toBe('injected probe failure') + await adapter.stop().catch(() => undefined) + }) +}) From a67ce916593ca92dd11b22981dd7e8af812699f2 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 06:35:10 -0300 Subject: [PATCH 070/100] fix: pre-existing bugs from the PR #9 review (time travel, prune lock, wait reads, stop in handler) 1. Time travel returning false no longer strands the job: the restore from the archive rolls back with the failed validation (private sentinel thrown inside the transaction), and the archived row is locked FOR UPDATE first so a concurrent prune cannot split the job and step copies. Pinned tests updated; the elapsed-shift "active" fixture seeds the legacy stranded state with SQL. 2. A lost prune-lock session no longer disables scheduled pruning until restart: the timer keeps ticking while retired (each skipped tick logs a warning), and once the old isolated client is confirmed closed and no pass runs, the next tick builds a new lock client. Only the loss of an established session qualifies; bootstrap failures, uncertain/malformed results, false unlock and PGLite stay retired. Key 42 keeps one owner (the server released the old lock). 3. runActionAndWait: an initial wait read that expires rejects with WaitReadTimeoutError, one that fails with WaitReadFailedError (cause = read error), instead of "Job not found". Both exported. waitForJob still resolves null. 4. await client.stop() inside a handler or step no longer deadlocks: the drain stops waiting for the caller's own user-code runs (handler/step callbacks, also when another stop is already in progress); the calling job is still aborted and writes its cancellation, and liveness is released. G3 recheck N2: the probe-failure log carries originalCode/originalMessage. --- packages/docs/content/docs/adapters.mdx | 4 +- packages/docs/content/docs/client-api.mdx | 11 +- packages/docs/content/docs/multi-worker.mdx | 4 +- packages/duron/src/action-job.ts | 21 ++-- packages/duron/src/adapters/postgres/base.ts | 85 +++++++++++++-- .../duron/src/adapters/postgres/postgres.ts | 9 ++ .../duron/src/adapters/postgres/prune-lock.ts | 14 +++ packages/duron/src/client.ts | 33 +++++- packages/duron/src/errors.ts | 28 +++++ packages/duron/src/index.ts | 7 +- packages/duron/src/lifecycle.ts | 86 +++++++++++++-- packages/duron/src/step-manager.ts | 21 ++-- packages/duron/src/wait-manager.ts | 52 +++++++-- packages/duron/test/adapter.test.ts | 51 +++++++++ .../duron/test/cancel-storage-shared.test.ts | 8 +- packages/duron/test/liveness-absence.test.ts | 3 + packages/duron/test/prune-reestablish.test.ts | 100 ++++++++++++++++++ packages/duron/test/stop-in-handler.test.ts | 98 +++++++++++++++++ packages/duron/test/time-travel.test.ts | 31 +++++- packages/duron/test/wait-read-errors.test.ts | 64 +++++++++++ 20 files changed, 666 insertions(+), 64 deletions(-) create mode 100644 packages/duron/test/prune-reestablish.test.ts create mode 100644 packages/duron/test/stop-in-handler.test.ts create mode 100644 packages/duron/test/wait-read-errors.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index e9a878d..45e8792 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -86,11 +86,11 @@ The scheduler attempts a pass immediately during startup, then at the configured ### PostgreSQL ownership and scope -An opted-in adapter owns one additional, max-one postgres.js client for coordination. It first performs an ordinary read-only backend-identity query, then reserves that same ready backend once for the scheduler lifetime. Initial driver setup attempts are permitted only while that first bootstrap is pending. After bootstrap succeeds, coordination never reconnects or replaces the session. Each pass acquires session-level advisory key `42` and must receive a true unlock; the reservation is not returned between passes. +An opted-in adapter owns one additional, max-one postgres.js client for coordination. It first performs an ordinary read-only backend-identity query, then reserves that same ready backend once for the scheduler lifetime. Initial driver setup attempts are permitted only while that first bootstrap is pending. After bootstrap succeeds, coordination never reconnects that session; only a lost session is replaced by a new client (see below). Each pass acquires session-level advisory key `42` and must receive a true unlock; the reservation is not returned between passes. Key `42` coordinates **across schemas in the same database**, not just one Duron schema. Separate databases do not contend. Avoid using this advisory key for unrelated application locks. DELETEs still run on the adapter's original query pool, including when that pool has `max: 1`. Custom `_pruneArchive` overrides remain in the dispatch path and can delegate to `super._pruneArchive`. -Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replace the client, replay pruning or close the normal query/listener resources. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. +Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, `idle_session_timeout`, a pooler or load-balancer idle timeout, `pg_terminate_backend`), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so key `42` keeps a single owner. A bootstrap failure, an uncertain or malformed coordination result, a false or rejected unlock, or a failed close keeps scheduling retired until the adapter restarts. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. ### Manual pruning and failure limits diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 6f89b94..930ae85 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -273,6 +273,8 @@ Stop the Duron instance. Stops worker discovery, aborts all running jobs, waits await client.stop() ``` +`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. Like every running job, the calling job is aborted and ends `cancelled`. Code that runs in it after `stop()` resolves cannot issue database calls. + ## Job Methods ### `runAction(actionName, input?)` @@ -373,6 +375,8 @@ console.log(result.output) // Typed based on action's output schema On abort or timeout the promise rejects immediately and `cancelJob(jobId)` runs in the background (its errors are logged), with the behavior described under [`cancelJob`](#canceljobjobid). `waitForJob` is different: its timeout or abort settles only that waiter and never cancels the job. +If the first read of the job's status does not finish within [`waitReadTimeout`](#waitreadtimeout), the promise rejects with `WaitReadTimeoutError`; if that read fails, it rejects with `WaitReadFailedError` (the read error is its `cause`). Both are exported from `duron`. The job may exist and keep running: only the read gave up, and the job is not cancelled. A job that has no readable detail rejects with `Job not found`. + **Returns:** Promise resolving to the job result with typed input and output **Example:** @@ -416,6 +420,8 @@ const success = await client.timeTravelJob(jobId, stepId) **Returns:** Promise resolving to `true` if time travel succeeded, `false` otherwise +A `false` result (the job is not terminal, or the step does not belong to it) changes nothing: the job and its steps stay where they were, so an archived job can still be retried, time-traveled to an existing step or pruned. + Which steps are kept: - The target step and its ancestor steps are reset to active and run again. @@ -484,8 +490,9 @@ const job = await client.getJobById(jobId) ### `getJobs(options?)` Get matching jobs from active and archive storage with global sorting and pagination. -Job records include input, output, and error, but not steps. A terminal job restored to -active storage remains visible under its status filter. +Job records include input, output, and error, but not steps. A terminal job that an older +version left in active storage after a failed time travel remains visible under its status +filter. SQL adapters apply every requested sort key in order, then break ties by job ID in the direction of the last sort key (ID descending when that key is descending). The order diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 964def0..fd13419 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -270,7 +270,7 @@ If the late call locks the job first, it wins and recovery skips the job. These Limits: - The guarantees hold when the effective transaction isolation is `READ COMMITTED` (the PostgreSQL default) and only for the built-in writers. Duron does not set the isolation level. Under a different `default_transaction_isolation`, these locks can raise serialization errors earlier, and behavior has not been analyzed. Workers on an older Duron version, custom adapter overrides and direct SQL do not participate. -- They describe the stored result as of the cancellation's commit, until a later time travel, prune or reset changes the job. False time travel restores the job and its steps as they were archived, and each step method keeps its existing guard, so `cancelJobStep` still accepts an active step under a restored `cancelled` job. +- They describe the stored result as of the cancellation's commit, until a later time travel, prune or reset changes the job. A time travel that returns `false` (for example for an unknown step) rolls back completely: the job and its steps stay archived as they were, so the job can still be retried, time-traveled to an existing step or pruned. - A call that waited checks expiry against its transaction's start time, not the time it acquired the lock. Archived `finishedAt` and `updatedAt` are the application time taken before any wait. - Lock waits have no deadline. A cancellation can wait for in-flight step creations, other terminators, recovery and claims (including claims holding candidate rows they did not select). `completeJob` and `failJob` can wait for step creations, cancellation and recovery. A step creation can wait for terminators and recovery. Step creations can keep overtaking a waiting cancellation, completion or failure, so a busy job can delay them. `client.stop()` observes such waits within its shutdown budgets but does not cut them short; an unfinished wait is reported as an incomplete drain. - Recovery's own step handling, including steps created while recovery runs, is described in [Recovery and concurrent steps](#recovery-and-concurrent-steps). @@ -343,7 +343,7 @@ Client and Adapter share four internal shutdown budgets. Each budget applies to Empty phases are skipped. Later cleanup phases still receive their opportunity after an earlier failure or timeout. The planned asynchronous wait is approximately twenty seconds when all phases are needed, not a hard elapsed-time or natural-process-exit guarantee. -After the drain boundary, no new ordinary SQL may begin. Already-issued SQL is not assumed cancelled. A successful mutation that reaches notification submission too late keeps its successful result; the forbidden hint is omitted and logged as delivery unconfirmed. User JavaScript and external side effects are not forcibly terminated or fenced by these in-process gates. +After the drain boundary, no new ordinary SQL may begin. Already-issued SQL is not assumed cancelled. A successful mutation that reaches notification submission too late keeps its successful result; the forbidden hint is omitted and logged as delivery unconfirmed. User JavaScript and external side effects are not forcibly terminated or fenced by these in-process gates. A handler or step that calls `stop()` itself is not waited for by the drain (it waits for `stop()`); the rest of its job, including the abort and cancellation write, still is. A timeout or cleanup failure rejects `stop()`. A sole error is preserved; multiple failures use `AggregateError`. Log and inspect the rejection rather than treating it as proof that resources closed or work stopped. Concurrent stop callers share cleanup. A later stop joins pending resource operations or retries only safe unfinished cleanup; it does not replay completed application work or allocate a replacement connection. Failed or withheld liveness deletion cannot be repaired after SQL has closed. A failed explicit unsubscribe remains an error for that attempt even if owned close subsequently releases its resources. diff --git a/packages/duron/src/action-job.ts b/packages/duron/src/action-job.ts index 4a570d8..1519424 100644 --- a/packages/duron/src/action-job.ts +++ b/packages/duron/src/action-job.ts @@ -153,15 +153,18 @@ export class ActionJob> { const spanContext = trace.setSpan(context.active(), this.#jobSpan) // Keep the raw handler promise: an abort/timeout can settle the race first. - const handler = lifecycleFor(this.#database).run(() => - context.with(spanContext, () => { - // The tracked invocation is deferred. Stop can win after preparation. - if (!lifecycleFor(this.#database).accepting) { - throw new ActionCancelError(this.#action.name, this.#job.id) - } - this.#abortController.signal.throwIfAborted() - return this.#action.handler(ctx) - }), + const handler = lifecycleFor(this.#database).run( + () => + context.with(spanContext, () => { + // The tracked invocation is deferred. Stop can win after preparation. + if (!lifecycleFor(this.#database).accepting) { + throw new ActionCancelError(this.#action.name, this.#job.id) + } + this.#abortController.signal.throwIfAborted() + return this.#action.handler(ctx) + }), + // User code: a stop() it awaits is excluded from the drain (see Lifecycle.stop). + { userCode: true }, ) this.#handler = handler await Promise.race([ diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index c739c9b..3464efe 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -138,6 +138,8 @@ export abstract class PostgresBaseAdapter< private pruneRetired = false private pruneCoordinationErrors: unknown[] = [] private pruneFaultClose: Promise | undefined + /** Set once the isolated lock client of a retirement closed successfully. */ + private pruneFaultClosed = false private readonly scheduledPrune = new AsyncLocalStorage() private pruneConfig: PruneSchedulerConfig | null = null private lastPrunedAt: Date | null = null @@ -396,10 +398,10 @@ export abstract class PostgresBaseAdapter< if (this.initialized) return false let cause = error const seen = new Set() - let undefinedTable = false + let undefinedTable: Error | undefined while (cause instanceof Error && !seen.has(cause)) { seen.add(cause) - if ('code' in cause && cause.code === '42P01') undefinedTable = true + if ('code' in cause && cause.code === '42P01') undefinedTable ??= cause cause = cause.cause } if (!undefinedTable) return false @@ -412,8 +414,9 @@ export abstract class PostgresBaseAdapter< return row?.missing === true } catch (probeError) { // The caller rethrows the original 42P01; the probe's own failure is only logged. + // Plain fields: pino serializes only `err` as an Error. this.logger?.error( - { err: probeError, original: error }, + { err: probeError, originalCode: '42P01', originalMessage: undefinedTable.message }, 'Liveness table probe failed; rethrowing the original error', ) return false @@ -458,12 +461,13 @@ export abstract class PostgresBaseAdapter< protected _retirePruning(error: unknown): void { this.pruneCoordinationErrors.push(error) this.pruneRetired = true - this._stopScheduler() + // The timer keeps ticking: a later tick re-establishes coordination once the isolated + // lock client is confirmed closed (see `_reestablishPruning`), or reports the retired state. if (!lifecycleFor(this).accepting) return // The hook uses the other query pool and may remain pending indefinitely. // Start isolated cleanup now; retain this observer's outcome for the pass's // ordered error report instead of replacing it with a later cached success. - const closing = (this.pruneFaultClose ??= this._closePruneLock()) + const closing = (this.pruneFaultClose ??= this._observePruneLockClose()) if (this.pruneRunning) { void closing.catch(() => undefined) } else { @@ -485,6 +489,44 @@ export abstract class PostgresBaseAdapter< // PGLite has no isolated resource: its engine stays available until normal stop. } + /** The retirement's isolated close; records its success for re-establishment. */ + private _observePruneLockClose(): Promise { + return this._closePruneLock().then(() => { + this.pruneFaultClosed = true + }) + } + + /** + * Whether coordination can start again with a new isolated lock after a retirement whose + * lock client closed successfully. Only the loss of an established isolated lock session + * qualifies: the server released that session's advisory lock when it ended. Bootstrap + * failures and uncertain or malformed coordination results keep the scheduler retired, and + * so does PGLite, which coordinates on its shared engine. + */ + protected _canReplacePruneLock(): boolean { + return false + } + + /** Drop the closed isolated lock so the next acquisition builds a new one. */ + protected _resetPruneLock(): void {} + + /** + * Called by a tick while retired and no pass runs. Re-establishes coordination when the + * old lock client is confirmed closed; otherwise reports that the tick is skipped. + */ + private _reestablishPruning(): boolean { + if (this.pruneFaultClosed && this._canReplacePruneLock()) { + this._resetPruneLock() + this.pruneRetired = false + this.pruneFaultClose = undefined + this.pruneFaultClosed = false + this.logger?.info('Scheduled prune coordination re-established on a new lock session') + return true + } + this.logger?.warn('Scheduled prune skipped: coordination is retired') + return false + } + /** * Start the archive prune scheduler. */ @@ -494,7 +536,8 @@ export abstract class PostgresBaseAdapter< if (!config || !lifecycle.accepting) return const run = () => { - if (!lifecycle.accepting || this.pruneRetired || this.pruneRunning) return Promise.resolve() + if (!lifecycle.accepting || this.pruneRunning) return Promise.resolve() + if (this.pruneRetired && !this._reestablishPruning()) return Promise.resolve() this.pruneRunning = true return lifecycle .run(async () => { @@ -535,7 +578,7 @@ export abstract class PostgresBaseAdapter< // adapter. Positive resource release does not erase its earlier error. if (this.pruneFaultClose || (this.pruneRetired && lifecycle.accepting)) { try { - await (this.pruneFaultClose ??= this._closePruneLock()) + await (this.pruneFaultClose ??= this._observePruneLockClose()) } catch (error) { closeErrors.push(error) } @@ -940,7 +983,28 @@ export abstract class PostgresBaseAdapter< * @returns Promise resolving to `true` if time travel succeeded, `false` otherwise */ protected async _timeTravelJob({ jobId, stepId }: TimeTravelJobOptions): Promise { + // A failed validation rolls the whole transaction back, including the restore from the + // archive, so a `false` result never leaves a terminal job stranded in active storage. + const rejected = Symbol('time travel rejected') + try { + return await this._timeTravelJobInTransaction(jobId, stepId, rejected) + } catch (error) { + if (error === rejected) return false + throw error + } + } + + private _timeTravelJobInTransaction( + jobId: string, + stepId: string, + rejected: symbol, + ): Promise { return this.db.transaction(async (tx) => { + // Lock the archived job first (a no-op when it is not archived): a concurrent prune + // cannot delete it between the job copy and the step copy below. + await tx.execute(sql` + SELECT 1 FROM ${this.tables.jobsArchiveTable} WHERE id = ${jobId} FOR UPDATE + `) // If the job is archived, restore it and its steps to the active tables. The copy is // SQL-native so timestamps keep their microseconds: the "created before the target" rule // below compares created_at, and a millisecond round trip through Date would tie steps @@ -1150,7 +1214,9 @@ export abstract class PostgresBaseAdapter< `), ) - return result.length > 0 && result[0]!.success === true + if (result.length > 0 && result[0]!.success === true) return true + // Roll back: the restore above must not outlive a rejected time travel. + throw rejected }) } @@ -2177,7 +2243,8 @@ export abstract class PostgresBaseAdapter< const queryArchive = statuses.length === 0 || statuses.some((s) => (archiveStatuses as string[]).includes(s)) - // Active storage can contain every status after a false time-travel restoration. + // Active storage can still hold terminal jobs that an older version stranded after a + // false time-travel restoration (a false result now rolls back), so query it for every status. const activeTable = this.tables.jobsActiveTable const archiveTable = this.tables.jobsArchiveTable const activeWhere = this._buildJobsWhereClause(filters) diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index f2dee23..0ae2db3 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -89,6 +89,15 @@ export class PostgresAdapter extends PostgresBaseAdapter | string, @@ -42,6 +44,8 @@ export class PostgresPruneLock { this.#confirmClosed() if (this.#closing) return this.#uncertain = true + // The server ended a session that was working: its advisory lock is released with it. + this.#lostAfterEstablished = this.#established this.retire(new Error('Scheduled prune coordination session was lost')) }, } @@ -87,6 +91,7 @@ export class PostgresPruneLock { if (identity.length !== 1 || identity[0]?.pid !== this.#pid) { throw new Error('Scheduled prune reservation changed backend identity') } + this.#established = true return true } catch (error) { // A failed transition cannot establish safe reservation ownership, even @@ -128,6 +133,15 @@ export class PostgresPruneLock { this.#lock = 'none' } + /** + * True when an established reserved session was lost (server restart, idle timeout, + * terminated backend). Once this client's close is confirmed, a new lock may replace it. + * Bootstrap failures and uncertain or malformed coordination results never qualify. + */ + get lostAfterEstablished(): boolean { + return this.#lostAfterEstablished + } + faultClose(): Promise { return this.#obligation.observeEarlyClose() } diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 21d9af4..8310e62 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -24,11 +24,12 @@ import type { } from './adapters/adapter.js' import type { JobStatusResult, JobStepStatusResult } from './adapters/schemas.js' import { JOB_STATUS_CANCELLED, JOB_STATUS_FAILED, type JobStatus } from './constants.js' +import { WaitReadFailedError, WaitReadTimeoutError } from './errors.js' import { type Lifecycle, lifecycleFor } from './lifecycle.js' import { type FetchToken, LocalCancellation } from './local-cancellation.js' import { markClientAdapter, usedByClient } from './recovery-scope.js' import { validateSchema } from './standard-schema.js' -import { WaitManager } from './wait-manager.js' +import { WaitManager, type WaitOutcome } from './wait-manager.js' import { type ClaimedBatch, WorkerDiscovery } from './worker-discovery.js' /** @@ -643,6 +644,8 @@ export class Client< * @param options - Options including abort signal and timeout * @returns Promise resolving to the job result with typed input and output * @throws Error if action is not found, job creation fails, job is cancelled, or operation is aborted + * @throws WaitReadTimeoutError if the first wait read exceeds `waitReadTimeout`, or + * WaitReadFailedError if it fails; the job may exist and is not cancelled */ async runActionAndWait( actionName: TActionName, @@ -706,7 +709,8 @@ export class Client< } // Wait for the job to complete - const job = await this.waitForJob(jobId, { signal: waitSignal }) + const outcome = await this.#waitOutcome(jobId, { signal: waitSignal }) + const job = outcome.result // Clean up if (timeoutId) { @@ -724,6 +728,13 @@ export class Client< if (timeoutAbortController?.signal.aborted) { throw new Error('Operation timed out') } + // The first read gave up or failed: the job may exist, so do not report it missing. + if (outcome.reason === 'read-expired') { + throw new WaitReadTimeoutError(jobId, this.#options.waitReadTimeout) + } + if (outcome.reason === 'read-failed') { + throw new WaitReadFailedError(jobId, { cause: outcome.error }) + } throw new Error('Job not found') } @@ -1013,16 +1024,24 @@ export class Client< signal?: AbortSignal }, ): Promise { + return (await this.#waitOutcome(jobId, options)).result + } + + /** `waitForJob` with the reason the wait settled (internal; used by runActionAndWait). */ + #waitOutcome( + jobId: string, + options?: { timeout?: number; signal?: AbortSignal }, + ): Promise { return this.#lifecycle.run(async () => { await this.start() this.#lifecycle.assertContinuation() - if (!this.#lifecycle.accepting) return null + if (!this.#lifecycle.accepting) return { reason: 'stop', result: null } // Set up the shared event listener if not already set up this.#setupJobStatusListener() // Listener and waiter registration precede the first admitted read. - return this.#waits.wait(jobId, options) + return this.#waits.waitOutcome(jobId, options) }) } @@ -1171,7 +1190,11 @@ export class Client< /** Quiesce synchronously, then preserve public Adapter.stop override dispatch. */ async stop(): Promise { - if (this.#stopping) return this.#stopping + if (this.#stopping) { + // Awaited inside a handler or step: the drain must not wait for that caller. + this.#lifecycle.excludeCallerFromDrain() + return this.#stopping + } this.#stopping = Promise.resolve() .then(() => this.#database.stop()) .finally(() => { diff --git a/packages/duron/src/errors.ts b/packages/duron/src/errors.ts index 62d4a9b..130f754 100644 --- a/packages/duron/src/errors.ts +++ b/packages/duron/src/errors.ts @@ -7,6 +7,8 @@ export const ERROR_CODES = { STEP_TIMEOUT: 'STEP_TIMEOUT', ACTION_CANCEL: 'ACTION_CANCEL', UNHANDLED_CHILD_STEPS: 'UNHANDLED_CHILD_STEPS', + WAIT_READ_TIMEOUT: 'WAIT_READ_TIMEOUT', + WAIT_READ_FAILED: 'WAIT_READ_FAILED', } as const export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES] @@ -263,6 +265,32 @@ export class UnhandledChildStepsError extends NonRetriableError { } } +/** + * Thrown by `runActionAndWait` when its first wait read did not finish within + * `waitReadTimeout`. The job may exist and keep running; only the caller's read gave up. + */ +export class WaitReadTimeoutError extends DuronError { + public override readonly code = ERROR_CODES.WAIT_READ_TIMEOUT + + constructor(jobId: string, timeoutMs: number) { + super(`Wait read for job "${jobId}" did not finish within ${timeoutMs}ms (waitReadTimeout)`, { + metadata: { jobId }, + }) + } +} + +/** + * Thrown by `runActionAndWait` when its first wait read failed (its `cause` is the read + * error). The job may exist and keep running; only the caller's read failed. + */ +export class WaitReadFailedError extends DuronError { + public override readonly code = ERROR_CODES.WAIT_READ_FAILED + + constructor(jobId: string, options: { cause: unknown }) { + super(`Wait read for job "${jobId}" failed`, { cause: options.cause, metadata: { jobId } }) + } +} + /** * Checks if an error is a DuronError instance. */ diff --git a/packages/duron/src/index.ts b/packages/duron/src/index.ts index 8dd3e61..8c9cabb 100644 --- a/packages/duron/src/index.ts +++ b/packages/duron/src/index.ts @@ -11,7 +11,12 @@ export { } from './action.js' export * from './client.js' export * from './constants.js' -export { NonRetriableError, UnhandledChildStepsError } from './errors.js' +export { + NonRetriableError, + UnhandledChildStepsError, + WaitReadFailedError, + WaitReadTimeoutError, +} from './errors.js' export * from './server.js' export { validateSchema, isStandardSchema } from './standard-schema.js' export type { TelemetryContext } from './step-manager.js' diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index aa024d1..5630292 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -1,7 +1,16 @@ import { AsyncLocalStorage } from 'node:async_hooks' type Phase = 'startup settlement' | 'admitted-work drain' | 'database cleanup' | 'owned close' -type Context = { lifecycle: Lifecycle; kind: 'startup' | 'operation' | 'cleanup'; active: boolean } +type Context = { + lifecycle: Lifecycle + kind: 'startup' | 'operation' | 'cleanup' + active: boolean + /** The enclosing context of this lifecycle when this run was admitted. */ + parent?: Context + /** A raw handler or step callback run: user code that can await `stop()`. */ + userCode?: boolean + promise?: Promise +} const context = new AsyncLocalStorage() const lifecycles = new WeakMap() @@ -41,6 +50,15 @@ export function isStopFailure(error: unknown): boolean { return false } +// Local deferred instead of Promise.withResolvers, which needs Node.js 22. +function signal(): { promise: Promise; resolve: () => void } { + let resolve!: () => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} + // A deadline bounds observation, not execution. The losing promise remains observed. class ShutdownBudget { readonly #deadline = performance.now() + 5_000 @@ -178,6 +196,9 @@ export class Lifecycle { #work = new Set>() #quiesce = new Set<() => void | Promise>() #quiesceFailures: unknown[] = [] + /** Runs the admitted-work drain no longer waits for (see excludeCallerFromDrain). */ + #drainExcluded = new Set>() + #drainExclusionChanged = signal() #obligations = new Set() #stopping: StopAttempt | null = null #lastStop: StopAttempt | null = null @@ -278,7 +299,32 @@ export class Lifecycle { return caller?.lifecycle === this && caller.active ? start.raw : start.outcome } - run(work: () => Promise): Promise { + /** + * Called by stop(): a caller inside this lifecycle's user code (a handler or step that + * awaits stop) cannot settle before stop does, so the admitted-work drain stops waiting + * for those runs. Framework work around them (the job's abort and cancellation write) + * is still drained. + */ + excludeCallerFromDrain(): void { + let token = context.getStore() + let added = false + while (token) { + if (token.lifecycle === this && token.active && token.userCode && token.promise) { + if (!this.#drainExcluded.has(token.promise)) { + this.#drainExcluded.add(token.promise) + added = true + } + } + token = token.parent + } + if (added) { + const changed = this.#drainExclusionChanged + this.#drainExclusionChanged = signal() + changed.resolve() + } + } + + run(work: () => Promise, options?: { userCode?: boolean }): Promise { const caller = context.getStore() if ( !this.#ordinaryOpen || @@ -287,7 +333,7 @@ export class Lifecycle { ) { return Promise.reject(new Error('Lifecycle is not accepting work')) } - const promise = this.#inContext('operation', work) + const promise = this.#inContext('operation', work, options?.userCode) this.#observe(promise, this.#work) return promise } @@ -328,6 +374,8 @@ export class Lifecycle { } stop(): Promise { + // A stop() awaited inside a handler or step must not wait for that handler or step. + this.excludeCallerFromDrain() if (this.#stopping) return this.#stopping.promise // Install before invoking quiesce hooks, which may reenter public lifecycle calls. const attempt: StopAttempt = { promise: Promise.resolve(false), failures: [] } @@ -352,7 +400,12 @@ export class Lifecycle { async #cleanup(attempt: StopAttempt): Promise { const failures: LifecycleFailure[] = [] await this.#settlePhase('startup settlement', this.#startupWork, failures) - this.#drained = await this.#settlePhase('admitted-work drain', this.#work, failures) + this.#drained = await this.#settlePhase( + 'admitted-work drain', + this.#work, + failures, + this.#drainExcluded, + ) this.#ordinaryOpen = false // Report quiesce failures once, in the attempt that observed them; a repeated stop // then returns true when nothing else failed. @@ -392,11 +445,17 @@ export class Lifecycle { phase: Phase, pending: Set>, failures: LifecycleFailure[], + excluded?: Set>, ): Promise { - if (!pending.size) return true + const waited = () => [...pending].filter((work) => !excluded?.has(work)) + if (!waited().length) return true this.#phase = phase const settle = async () => { - while (pending.size) await Promise.allSettled(pending) + // A caller can be excluded while this phase waits (stop() awaited inside a handler + // after another caller began stopping), so also wake on exclusion changes. + for (let remaining = waited(); remaining.length; remaining = waited()) { + await Promise.race([Promise.allSettled(remaining), this.#drainExclusionChanged.promise]) + } } try { await new ShutdownBudget(phase).observe(settle()) @@ -415,12 +474,21 @@ export class Lifecycle { ) } - #inContext(kind: Context['kind'], work: () => Promise): Promise { - const token: Context = { lifecycle: this, kind, active: true } - return Promise.resolve() + #inContext(kind: Context['kind'], work: () => Promise, userCode = false): Promise { + const enclosing = context.getStore() + const token: Context = { + lifecycle: this, + kind, + active: true, + userCode, + parent: enclosing?.lifecycle === this ? enclosing : undefined, + } + const promise = Promise.resolve() .then(() => context.run(token, work)) .finally(() => { token.active = false }) + token.promise = promise + return promise } } diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index b592075..31eba36 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -688,15 +688,18 @@ export class StepManager { throw new ActionCancelError(this.#actionName, this.#jobId) } stepSignal.throwIfAborted() - const callbackPromise = this.#lifecycle.run(() => - context.with(spanContext, () => { - // Recheck at actual invocation, after the ledger's queued continuation. - if (!this.#lifecycle.accepting) { - throw new ActionCancelError(this.#actionName, this.#jobId) - } - stepSignal.throwIfAborted() - return cb(stepContext) - }), + const callbackPromise = this.#lifecycle.run( + () => + context.with(spanContext, () => { + // Recheck at actual invocation, after the ledger's queued continuation. + if (!this.#lifecycle.accepting) { + throw new ActionCancelError(this.#actionName, this.#jobId) + } + stepSignal.throwIfAborted() + return cb(stepContext) + }), + // User code: a stop() it awaits is excluded from the drain (see Lifecycle.stop). + { userCode: true }, ) let result: any = null diff --git a/packages/duron/src/wait-manager.ts b/packages/duron/src/wait-manager.ts index 5e9a415..911ce1a 100644 --- a/packages/duron/src/wait-manager.ts +++ b/packages/duron/src/wait-manager.ts @@ -5,9 +5,18 @@ import type { JobResult } from './client.js' import type { Lifecycle } from './lifecycle.js' import { WaitReadBudget, WaitReadExpired, WaitReadStopped, executeWaitRead } from './wait-read.js' +/** + * Why a wait settled. `read-expired`/`read-failed`: the waiter's initial read gave up + * (waitReadTimeout) or failed; the job may exist. `missing`: no readable job detail. + */ +export type WaitOutcome = + | { reason: 'result'; result: JobResult } + | { reason: 'missing' | 'timeout' | 'abort' | 'stop' | 'read-expired'; result: null } + | { reason: 'read-failed'; result: null; error: unknown } + type Waiter = { initial: boolean - resolve: (result: JobResult | null) => void + resolve: (outcome: WaitOutcome) => void timer?: ReturnType signal?: AbortSignal abort?: () => void @@ -50,7 +59,16 @@ export class WaitManager { id: string, options?: { timeout?: number; signal?: AbortSignal }, ): Promise { - if (!this.lifecycle.accepting || options?.signal?.aborted) return Promise.resolve(null) + return this.waitOutcome(id, options).then((outcome) => outcome.result) + } + + /** Like `wait`, with the reason it settled. */ + waitOutcome( + id: string, + options?: { timeout?: number; signal?: AbortSignal }, + ): Promise { + if (!this.lifecycle.accepting) return Promise.resolve({ reason: 'stop', result: null }) + if (options?.signal?.aborted) return Promise.resolve({ reason: 'abort', result: null }) let cohort = this.#cohorts.get(id) if (!cohort) { cohort = { id, waiters: new Set(), cooldown: 0 } @@ -61,10 +79,13 @@ export class WaitManager { const waiter: Waiter = { initial: true, resolve, signal: options?.signal } captured.waiters.add(waiter) if (options?.timeout) { - waiter.timer = setTimeout(() => this.#settle(captured, waiter, null), options.timeout) + waiter.timer = setTimeout( + () => this.#settle(captured, waiter, { reason: 'timeout', result: null }), + options.timeout, + ) } if (options?.signal) { - waiter.abort = () => this.#settle(captured, waiter, null) + waiter.abort = () => this.#settle(captured, waiter, { reason: 'abort', result: null }) options.signal.addEventListener('abort', waiter.abort) } this.#request(captured, false) @@ -79,7 +100,9 @@ export class WaitManager { stop(): void { for (const cohort of this.#cohorts.values()) { - for (const waiter of cohort.waiters) this.#settle(cohort, waiter, null) + for (const waiter of cohort.waiters) { + this.#settle(cohort, waiter, { reason: 'stop', result: null }) + } } this.#idle() } @@ -88,11 +111,11 @@ export class WaitManager { return this.#cohorts.get(cohort.id) === cohort && cohort.waiters.size > 0 } - #settle(cohort: Cohort, waiter: Waiter, result: JobResult | null): void { + #settle(cohort: Cohort, waiter: Waiter, outcome: WaitOutcome): void { if (!this.#current(cohort) || !cohort.waiters.delete(waiter)) return if (waiter.timer !== undefined) clearTimeout(waiter.timer) if (waiter.signal && waiter.abort) waiter.signal.removeEventListener('abort', waiter.abort) - waiter.resolve(result) + waiter.resolve(outcome) if (!cohort.waiters.size) { this.#cohorts.delete(cohort.id) this.#queue.delete(cohort) @@ -182,7 +205,9 @@ export class WaitManager { }, '[Duron] Wait read expired', ) - for (const waiter of initial) this.#settle(cohort, waiter, null) + for (const waiter of initial) { + this.#settle(cohort, waiter, { reason: 'read-expired', result: null }) + } }) let failed = false const read = async (): Promise => { @@ -228,7 +253,10 @@ export class WaitManager { error: job.error, } : null - for (const waiter of eligible) this.#settle(cohort, waiter, result) + const outcome: WaitOutcome = result + ? { reason: 'result', result } + : { reason: 'missing', result: null } + for (const waiter of eligible) this.#settle(cohort, waiter, outcome) }, (error: unknown) => { budget.finish() @@ -245,7 +273,11 @@ export class WaitManager { }, '[Duron] Wait read failed', ) - if (!budget.expired) for (const waiter of initial) this.#settle(cohort, waiter, null) + if (!budget.expired) { + for (const waiter of initial) { + this.#settle(cohort, waiter, { reason: 'read-failed', result: null, error }) + } + } }, ) .finally(() => { diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index 880ffa6..bb3b620 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -19,6 +19,12 @@ import { serializeError } from '../src/errors.js' import { type Adapter, type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' import { expectToBeDefined } from './asserts.js' +// Rows of a db.execute result (postgres.js returns the array, PGlite a { rows } object). +function rowsOf(result: unknown): Array> { + return Array.isArray(result) + ? [...result] + : (result as { rows: Array> }).rows +} function runAdapterTests(adapterFactory: AdapterFactory) { describe(`Adapter Tests with ${adapterFactory.name}`, () => { let adapter: Adapter @@ -1275,6 +1281,51 @@ function runAdapterTests(adapterFactory: AdapterFactory) { }) } + it('should leave a terminal job archived, retryable and prunable after a false time travel', async () => { + const jobId = await adapter.createJob({ + queue: 'false-time-travel', + groupKey: 'test-group', + input: {}, + timeoutMs: 60_000, + checksum: 'abc123', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expectToBeDefined(jobId) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + const step = await adapter.createOrRecoverJobStep({ + jobId, + name: 'kept', + timeoutMs: 60_000, + retriesLimit: 0, + }) + expectToBeDefined(step) + expect(await adapter.completeJobStep({ stepId: step.id, output: 1 })).toBe(true) + expect(await adapter.completeJob({ jobId, output: { ok: 1 } })).toBe(true) + + // An unknown step makes the time travel return false and roll back its restore. + expect(await adapter.timeTravelJob({ jobId, stepId: crypto.randomUUID() })).toBe(false) + const { db } = adapter as unknown as { + db: { execute: (query: SQL) => Promise } + } + const rows = async (table: string, column: string) => + rowsOf( + await db.execute( + sql`SELECT status FROM duron.${sql.identifier(table)} WHERE ${sql.identifier(column)} = ${jobId}`, + ), + ) + expect(await rows('jobs_active', 'id')).toEqual([]) + expect(await rows('jobs_archive', 'id')).toEqual([{ status: 'completed' }]) + expect(await rows('job_steps_archive', 'job_id')).toEqual([{ status: 'completed' }]) + expect(await adapter.getArchiveStats()).toMatchObject({ jobsCount: 1 }) + + // Still archived: it can be time-traveled to a real step, retried and pruned. + const retried = await adapter.retryJob({ jobId }) + expectToBeDefined(retried) + expect(await adapter.pruneArchive({ olderThan: new Date(Date.now() + 86_400_000) })).toBe(1) + expect(await rows('jobs_archive', 'id')).toEqual([]) + }) + it('should get jobs with pagination', async () => { // Create multiple jobs for (let i = 0; i < 5; i++) { diff --git a/packages/duron/test/cancel-storage-shared.test.ts b/packages/duron/test/cancel-storage-shared.test.ts index 09df988..4b34f84 100644 --- a/packages/duron/test/cancel-storage-shared.test.ts +++ b/packages/duron/test/cancel-storage-shared.test.ts @@ -118,7 +118,7 @@ function runCancelStorageTests(factory: AdapterFactory) { }) }) - it('TT-false: a false time travel restoring a cancelled job keeps cancelJobStep for a legacy active step', async () => { + it('TT-false: a false time travel rolls back and leaves the cancelled job and its legacy active step archived', async () => { await withAdapter(async (adapter) => { const jobId = await createClaimedJob(adapter) const s1 = (await createStep(adapter, jobId, 's1'))! @@ -132,11 +132,15 @@ function runCancelStorageTests(factory: AdapterFactory) { expect(await adapter.timeTravelJob({ jobId, stepId: crypto.randomUUID() })).toBe(false) + // Nothing was restored: the job and its step stay archived and read-only. expect((await adapter.getJobById(jobId))?.status).toBe('cancelled') expect(await stepStatuses(adapter, jobId)).toEqual({ [s1.id]: 'active' }) expect(await createStep(adapter, jobId, 's2')).toBeNull() expect(await adapter.completeJobStep({ stepId: s1.id, output: 1 })).toBe(false) - expect(await adapter.cancelJobStep({ stepId: s1.id })).toBe(true) + expect(await adapter.cancelJobStep({ stepId: s1.id })).toBe(false) + // A time travel to an existing step still restores it. + expect(await adapter.timeTravelJob({ jobId, stepId: s1.id })).toBe(true) + expect((await adapter.getJobById(jobId))?.status).toBe('created') }) }) }) diff --git a/packages/duron/test/liveness-absence.test.ts b/packages/duron/test/liveness-absence.test.ts index 2efa102..1f190e9 100644 --- a/packages/duron/test/liveness-absence.test.ts +++ b/packages/duron/test/liveness-absence.test.ts @@ -83,6 +83,9 @@ describe('Liveness table probe failure', () => { expect(reported.some((error) => String(error).includes('injected probe failure'))).toBe(false) const probe = entries.find((entry) => /Liveness table probe failed/.test(entry['msg'])) expect(probe?.['err']?.['message']).toBe('injected probe failure') + // The log also identifies the original error (pino serializes only `err` as an Error). + expect(probe?.['originalCode']).toBe('42P01') + expect(probe?.['originalMessage']).toContain('clients') await adapter.stop().catch(() => undefined) }) }) diff --git a/packages/duron/test/prune-reestablish.test.ts b/packages/duron/test/prune-reestablish.test.ts new file mode 100644 index 0000000..bd954a4 --- /dev/null +++ b/packages/duron/test/prune-reestablish.test.ts @@ -0,0 +1,100 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' +import postgres from 'postgres' + +import type { PruneArchiveOptions } from '../src/adapters/adapter.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +// A lost coordination session (server restart, idle_session_timeout, pg_terminate_backend) +// retires the scheduler only until the old session is confirmed closed: a later tick builds +// a new lock session and pruning continues. Key 42 keeps one owner: the server released the +// old session's lock when it ended, and no pass overlaps the re-establishment. + +async function eventually(check: () => Promise, timeout = 10_000): Promise { + const deadline = performance.now() + timeout + for (;;) { + try { + await check() + return + } catch (error) { + if (performance.now() >= deadline) throw error + await Bun.sleep(20) + } + } +} + +if (process.env['POSTGRES_TEST'] === 'true') { + it('re-establishes scheduled pruning on a new lock session after the old one was lost', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() + let hooks = 0 + class CountingPrune extends PostgresAdapter { + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + hooks++ + return super._pruneArchive(options) + } + } + const application = `reestablish-${crypto.randomUUID()}` + const url = new URL(CONNECTION_URL) + const adapter = new CountingPrune({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + connection: { application_name: application }, + }, + pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: 50 }, + }) + adapter.setId(application) + const entries: Array<{ level: string; msg: string }> = [] + const logger = pino({ level: 'silent' }) + for (const level of ['error', 'warn', 'info'] as const) { + logger[level] = ((value: unknown, message?: string) => { + entries.push({ + level, + msg: message ?? (value instanceof Error ? value.message : String(value)), + }) + }) as never + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + // The lock session is the backend whose last statement used advisory key 42. + const lockSessions = () => observer<{ pid: number }[]>` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND application_name = ${application} + AND query LIKE '%advisory%lock(42)%' + ` + try { + expect(await adapter.start()).toBe(true) + let lost = 0 + await eventually(async () => { + const sessions = await lockSessions() + expect(sessions).toHaveLength(1) + lost = sessions[0]!.pid + }) + await eventually(async () => expect(hooks).toBeGreaterThan(0)) + await observer`SELECT pg_terminate_backend(${lost})` + await eventually(async () => + expect(entries.some((entry) => entry.level === 'error')).toBe(true), + ) + const hooksAtLoss = hooks + // A new lock session (another backend) serves later passes. + await eventually(async () => { + const sessions = await lockSessions() + expect(sessions).toHaveLength(1) + expect(sessions[0]!.pid).not.toBe(lost) + expect(hooks).toBeGreaterThan(hooksAtLoss) + }) + expect(entries.some((entry) => /re-established/.test(entry.msg))).toBe(true) + expect(await adapter.stop()).toBe(true) + } finally { + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 30_000) +} diff --git a/packages/duron/test/stop-in-handler.test.ts b/packages/duron/test/stop-in-handler.test.ts new file mode 100644 index 0000000..822ec54 --- /dev/null +++ b/packages/duron/test/stop-in-handler.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'bun:test' + +import { sql } from 'drizzle-orm' + +import { defineAction } from '../src/action.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +// `await client.stop()` inside a handler or step: the drain must not wait for the caller's own +// handler/step (which waits for stop), so stop completes promptly and releases liveness. The +// calling job is aborted like every running job and writes its cancellation. + +async function livenessRows(adapter: Adapter, id: string): Promise { + const db = (adapter as unknown as { db: { execute: (query: unknown) => Promise } }).db + const result = await db.execute( + sql`SELECT count(*)::int AS count FROM duron.clients WHERE client_id = ${id}`, + ) + const rows = Array.isArray(result) ? result : (result as { rows: unknown[] }).rows + return (rows[0] as { count: number }).count +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`stop() awaited inside admitted work with ${factory.name}`, () => { + for (const where of ['handler', 'step', 'handler after an external stop'] as const) { + it(`completes promptly when awaited inside a ${where}`, async () => { + const instance = await factory.create() + const id = `stop-inside-${crypto.randomUUID()}` + let client: Client | null = null + type Outcome = { result?: unknown; error?: unknown; ms: number } + const stopped = Promise.withResolvers() + const external = Promise.withResolvers() + const stopHere = async () => { + const start = performance.now() + try { + stopped.resolve({ result: await client!.stop(), ms: performance.now() - start }) + } catch (error) { + stopped.resolve({ error, ms: performance.now() - start }) + } + } + const action = defineAction()({ + name: 'shutdown', + handler: async (ctx) => { + if (where === 'step') await ctx.step('stop', stopHere) + else if (where === 'handler') await stopHere() + else { + // Another caller began stopping first; this handler then awaits stop() too. + void client!.stop().then(external.resolve, external.reject) + await stopHere() + } + return {} + }, + }) + client = new Client({ + id, + database: instance.adapter, + actions: { action }, + syncPattern: false, + recoverJobsOnStart: false, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + const jobId = await client.runAction('action', {}) + await client.fetch() + const outcome = await Promise.race([ + stopped.promise, + Bun.sleep(4_000).then((): Outcome => ({ error: 'stop() did not settle', ms: 4_000 })), + ]) + expect(outcome.error).toBeUndefined() + expect(outcome.result).toBe(true) + expect(outcome.ms).toBeLessThan(3_000) + if (where === 'handler after an external stop') { + expect(await external.promise).toBe(true) + } + if (factory.name === 'postgres') { + // The calling job was aborted and wrote its cancellation; liveness was released. + const reader = new PostgresAdapter({ connection: instance.connectionUrl }) + reader.setId('stop-inside-reader') + try { + expect((await reader.getJobById(jobId))?.status).toBe('cancelled') + expect(await livenessRows(reader, id)).toBe(0) + } finally { + await reader.stop() + } + } + } finally { + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 15_000) + } + }) +} diff --git a/packages/duron/test/time-travel.test.ts b/packages/duron/test/time-travel.test.ts index f10435c..4128841 100644 --- a/packages/duron/test/time-travel.test.ts +++ b/packages/duron/test/time-travel.test.ts @@ -848,7 +848,7 @@ function runIsolationTests(factory: AdapterFactory) { ) it.each([JOB_STATUS_COMPLETED, JOB_STATUS_FAILED, JOB_STATUS_CANCELLED])( - 'restores an archived %s job before returning false for a missing target', + 'keeps an archived %s job archived when time travel returns false for a missing target', async (status) => { const { adapter, deleteDb } = await factory.create({ logger: 'silent' }) try { @@ -872,7 +872,8 @@ function runIsolationTests(factory: AdapterFactory) { expect(await adapter.timeTravelJob({ jobId, stepId: missingStepId })).toBe(false) expect(await adapter.getJobById(jobId)).toEqual(jobBefore) expect(await adapter.getJobStepById(stepId)).toEqual(stepBefore) - expect(await getJobStorage(adapter, jobId)).toEqual({ active: true, archived: false }) + // The false result rolled the restore back: the job and step stay archived. + expect(await getJobStorage(adapter, jobId)).toEqual({ active: false, archived: true }) } finally { await adapter.stop() await deleteDb() @@ -905,6 +906,27 @@ async function createElapsedFixture(factory: AdapterFactory): Promise { + const jobColumns = sql.raw(`id, action_name, group_key, description, status, checksum, input, + output, error, timeout_ms, expires_at, started_at, finished_at, client_id, concurrency_limit, + concurrency_step_limit, created_at, updated_at`) + const stepColumns = sql.raw(`id, job_id, parent_step_id, parallel, name, status, output, error, + started_at, finished_at, timeout_ms, expires_at, retries_limit, retries_count, delayed_ms, + history_failed_attempts, created_at, updated_at`) + await elapsedSql( + adapter, + sql`INSERT INTO duron.jobs_active (${jobColumns}) + SELECT ${jobColumns} FROM duron.jobs_archive WHERE id = ${jobId}`, + ) + await elapsedSql( + adapter, + sql`INSERT INTO duron.job_steps_active (${stepColumns}) + SELECT ${stepColumns} FROM duron.job_steps_archive WHERE job_id = ${jobId}`, + ) + await elapsedSql(adapter, sql`DELETE FROM duron.jobs_archive WHERE id = ${jobId}`) +} + async function elapsedSql(adapter: Adapter, query: SQL): Promise { const { db } = adapter as unknown as { db: { execute: (query: SQL) => Promise } @@ -984,8 +1006,9 @@ function runElapsedTests(factory: AdapterFactory) { const targetId = await createCompletedStep(adapter, jobId, 'target') expect(await adapter.completeJob({ jobId, output: { saved: 'elapsed-job' } })).toBe(true) if (storage === 'active') { - // Public false restoration supplies an eligible terminal graph in active storage. - expect(await adapter.timeTravelJob({ jobId, stepId: crypto.randomUUID() })).toBe(false) + // Seeded SQL (labelled): a terminal graph in active storage, as an older version's + // false time travel left it (a false result now rolls back). + await strandInActiveStorage(adapter, jobId) } expect(await getJobStorage(adapter, jobId)).toEqual({ active: storage === 'active', diff --git a/packages/duron/test/wait-read-errors.test.ts b/packages/duron/test/wait-read-errors.test.ts new file mode 100644 index 0000000..6ab92b0 --- /dev/null +++ b/packages/duron/test/wait-read-errors.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'bun:test' + +import { defineAction } from '../src/action.js' +import { Client } from '../src/client.js' +import { WaitReadFailedError, WaitReadTimeoutError } from '../src/errors.js' + +import { pgliteFactory, postgresFactory } from './adapters.js' + +// runActionAndWait's first wait read can expire (waitReadTimeout) or fail while the job +// exists. That must surface as a wait-read error, not as "Job not found". + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`runActionAndWait initial wait read with ${factory.name}`, () => { + for (const fault of ['expires', 'fails'] as const) { + it(`rejects with a wait-read error, not "Job not found", when the read ${fault}`, async () => { + const instance = await factory.create() + const adapter = instance.adapter + const action = defineAction()({ name: 'slow-read', handler: async () => ({}) }) + const client = new Client({ + database: adapter, + actions: { action }, + // Nothing claims the job: it stays created while the caller waits. + syncPattern: false, + recoverJobsOnStart: false, + waitReadTimeout: 40, + logger: 'silent', + }) + const status = adapter.getJobStatus.bind(adapter) + const release = Promise.withResolvers() + adapter.getJobStatus = async (id) => { + if (fault === 'fails') throw new Error('injected status read failure') + await release.promise + return status(id) + } + try { + expect(await client.start()).toBe(true) + const error = await client.runActionAndWait('action', {}, { timeout: 10_000 }).then( + () => null, + (reason: unknown) => reason, + ) + release.resolve() + if (fault === 'expires') { + expect(error).toBeInstanceOf(WaitReadTimeoutError) + expect((error as Error).message).toContain('40ms') + } else { + expect(error).toBeInstanceOf(WaitReadFailedError) + expect(((error as Error).cause as Error).message).toBe('injected status read failure') + } + expect((error as Error).message).not.toBe('Job not found') + // The job exists: the caller's read gave up, the job did not disappear. + const jobs = await adapter.getJobs({ filters: { actionName: 'slow-read' } }) + expect(jobs.total).toBe(1) + } finally { + release.resolve() + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }) + } + }) +} From 0332c46d832faf621a714ac02f877d2ac23aa89e Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 07:26:54 -0300 Subject: [PATCH 071/100] fix: G4 review (stop ordering test, replaced prune locks released, retries, docs) R1: stop-in-handler tests a stop begun from outside any handler context first, then a handler that awaits stop(); both the Client-branch exclusion and the drain wake signal are needed (each mutation fails it). R2: a re-established prune lock releases the replaced one: Lifecycle.dispose() forgets its discharged obligations, the replaced postgres.js client is ended and dropped, and coordination errors are trimmed after each pass and on re-establishment. A native test does 4 re-establishments and asserts obligations, open clients and retained errors do not grow. A1: native test pins the archive FOR UPDATE (a time travel racing an uncommitted prune waits and restores nothing; without the lock it resurrects the job). A2: a replacement lock whose bootstrap fails retries on later ticks with a doubling backoff (interval .. 5 min); it never held key 42. A3: a lost established session (onclose, or a connection-loss error of its statements) is logged as a warning; real faults stay errors. A4: docs: stop() follows the handler's async context (timers, fire-and-forget). A5: renamed the false-time-travel listing test; new seeded legacy listing test. A6: runActionAndWait rejects with "Lifecycle is not accepting work" when the Client stops during the wait. --- packages/docs/content/docs/adapters.mdx | 2 +- packages/docs/content/docs/client-api.mdx | 4 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/src/adapters/postgres/base.ts | 78 ++++++++++-- .../duron/src/adapters/postgres/postgres.ts | 22 +++- .../duron/src/adapters/postgres/prune-lock.ts | 59 ++++++++- packages/duron/src/client.ts | 2 + packages/duron/src/lifecycle.ts | 14 +++ packages/duron/test/adapter.test.ts | 59 ++++++++- packages/duron/test/prune-reestablish.test.ts | 113 +++++++++++++++++- packages/duron/test/prune-scheduler.test.ts | 7 ++ packages/duron/test/prune-transport.test.ts | 4 + packages/duron/test/stop-in-handler.test.ts | 82 +++++++++++-- .../test/time-travel-archive-lock.test.ts | 73 +++++++++++ packages/duron/test/wait-read-errors.test.ts | 32 +++++ 15 files changed, 518 insertions(+), 35 deletions(-) create mode 100644 packages/duron/test/time-travel-archive-lock.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 45e8792..b06ff49 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -90,7 +90,7 @@ An opted-in adapter owns one additional, max-one postgres.js client for coordina Key `42` coordinates **across schemas in the same database**, not just one Duron schema. Separate databases do not contend. Avoid using this advisory key for unrelated application locks. DELETEs still run on the adapter's original query pool, including when that pool has `max: 1`. Custom `_pruneArchive` overrides remain in the dispatch path and can delegate to `super._pruneArchive`. -Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, `idle_session_timeout`, a pooler or load-balancer idle timeout, `pg_terminate_backend`), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so key `42` keeps a single owner. A bootstrap failure, an uncertain or malformed coordination result, a false or rejected unlock, or a failed close keeps scheduling retired until the adapter restarts. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. +Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, `idle_session_timeout`, a pooler or load-balancer idle timeout, `pg_terminate_backend`), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so key `42` keeps a single owner. Such a loss is logged as a warning, not an error. If that replacement client cannot start (the server is still unreachable), later ticks try again after a backoff that doubles from the interval up to five minutes; the replacement never held the lock, so a new attempt keeps a single owner. A bootstrap failure of the first client, an uncertain or malformed coordination result, a false or rejected unlock, or a failed close keeps scheduling retired until the adapter restarts. Each replaced client is closed and released, so repeated losses do not accumulate clients. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. ### Manual pruning and failure limits diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 930ae85..7456779 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -273,7 +273,7 @@ Stop the Duron instance. Stops worker discovery, aborts all running jobs, waits await client.stop() ``` -`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. Like every running job, the calling job is aborted and ends `cancelled`. Code that runs in it after `stop()` resolves cannot issue database calls. +`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. Like every running job, the calling job is aborted and ends `cancelled`. Code that runs in it after `stop()` resolves cannot issue database calls. The exclusion follows the handler's async context, not the `await`: a `stop()` started from a timer, callback or fire-and-forget task that a running handler or step created also excludes that handler or step from the drain, even if nothing awaits `stop()`. To stop and still wait for a handler, call `stop()` from outside it. ## Job Methods @@ -375,7 +375,7 @@ console.log(result.output) // Typed based on action's output schema On abort or timeout the promise rejects immediately and `cancelJob(jobId)` runs in the background (its errors are logged), with the behavior described under [`cancelJob`](#canceljobjobid). `waitForJob` is different: its timeout or abort settles only that waiter and never cancels the job. -If the first read of the job's status does not finish within [`waitReadTimeout`](#waitreadtimeout), the promise rejects with `WaitReadTimeoutError`; if that read fails, it rejects with `WaitReadFailedError` (the read error is its `cause`). Both are exported from `duron`. The job may exist and keep running: only the read gave up, and the job is not cancelled. A job that has no readable detail rejects with `Job not found`. +If the first read of the job's status does not finish within [`waitReadTimeout`](#waitreadtimeout), the promise rejects with `WaitReadTimeoutError`; if that read fails, it rejects with `WaitReadFailedError` (the read error is its `cause`). Both are exported from `duron`. The job may exist and keep running: only the read gave up, and the job is not cancelled. If the Client stops while the call waits, it rejects with `Lifecycle is not accepting work`. A job that has no readable detail rejects with `Job not found`. **Returns:** Promise resolving to the job result with typed input and output diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index fd13419..4540014 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -343,7 +343,7 @@ Client and Adapter share four internal shutdown budgets. Each budget applies to Empty phases are skipped. Later cleanup phases still receive their opportunity after an earlier failure or timeout. The planned asynchronous wait is approximately twenty seconds when all phases are needed, not a hard elapsed-time or natural-process-exit guarantee. -After the drain boundary, no new ordinary SQL may begin. Already-issued SQL is not assumed cancelled. A successful mutation that reaches notification submission too late keeps its successful result; the forbidden hint is omitted and logged as delivery unconfirmed. User JavaScript and external side effects are not forcibly terminated or fenced by these in-process gates. A handler or step that calls `stop()` itself is not waited for by the drain (it waits for `stop()`); the rest of its job, including the abort and cancellation write, still is. +After the drain boundary, no new ordinary SQL may begin. Already-issued SQL is not assumed cancelled. A successful mutation that reaches notification submission too late keeps its successful result; the forbidden hint is omitted and logged as delivery unconfirmed. User JavaScript and external side effects are not forcibly terminated or fenced by these in-process gates. A handler or step that calls `stop()` itself is not waited for by the drain (it waits for `stop()`); the rest of its job, including the abort and cancellation write, still is. This follows the async context: a `stop()` from a timer or fire-and-forget task started by a running handler or step also excludes that handler or step, whether or not it awaits `stop()`. A timeout or cleanup failure rejects `stop()`. A sole error is preserved; multiple failures use `AggregateError`. Log and inspect the rejection rather than treating it as proof that resources closed or work stopped. Concurrent stop callers share cleanup. A later stop joins pending resource operations or retries only safe unfinished cleanup; it does not replay completed application work or allocate a replacement connection. Failed or withheld liveness deletion cannot be repaired after SQL has closed. A failed explicit unsubscribe remains an error for that attempt even if owned close subsequently releases its resources. diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 3464efe..dbbc5e2 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -140,6 +140,9 @@ export abstract class PostgresBaseAdapter< private pruneFaultClose: Promise | undefined /** Set once the isolated lock client of a retirement closed successfully. */ private pruneFaultClosed = false + /** Consecutive replacement locks that failed to start, and the next attempt time. */ + private pruneReplaceFailures = 0 + private pruneReplaceAt = 0 private readonly scheduledPrune = new AsyncLocalStorage() private pruneConfig: PruneSchedulerConfig | null = null private lastPrunedAt: Date | null = null @@ -479,7 +482,17 @@ export abstract class PostgresBaseAdapter< ) }) .then( - () => this.logger?.error(error, 'Scheduled prune coordination retired'), + () => { + // A lost established session is benign and self-healing (idle timeouts): warn. + if (this._canReplacePruneLock()) { + this.logger?.warn( + { err: error }, + 'Scheduled prune coordination session lost; a later tick re-establishes it', + ) + } else { + this.logger?.error(error, 'Scheduled prune coordination retired') + } + }, (failure) => this.logger?.error(failure, 'Scheduled prune coordination retired'), ) } @@ -507,6 +520,11 @@ export abstract class PostgresBaseAdapter< return false } + /** Whether the retired lock is a replacement that failed its bootstrap. */ + protected _pruneLockBootstrapFailed(): boolean { + return false + } + /** Drop the closed isolated lock so the next acquisition builds a new one. */ protected _resetPruneLock(): void {} @@ -514,12 +532,33 @@ export abstract class PostgresBaseAdapter< * Called by a tick while retired and no pass runs. Re-establishes coordination when the * old lock client is confirmed closed; otherwise reports that the tick is skipped. */ - private _reestablishPruning(): boolean { + private _reestablishPruning(interval: number): boolean { if (this.pruneFaultClosed && this._canReplacePruneLock()) { + if (this._pruneLockBootstrapFailed()) { + // A replacement could not start (server unreachable): retry with a bounded backoff + // of the interval doubled per consecutive failure, at most five minutes. + const now = performance.now() + if (this.pruneReplaceAt === 0) { + this.pruneReplaceFailures++ + const delay = Math.max( + interval, + Math.min(interval * 2 ** (this.pruneReplaceFailures - 1), 300_000), + ) + this.pruneReplaceAt = now + delay + this.logger?.warn( + { failures: this.pruneReplaceFailures, delay }, + 'Scheduled prune replacement lock failed to start; retrying after a backoff', + ) + } + if (now < this.pruneReplaceAt) return false + } + this.pruneReplaceAt = 0 this._resetPruneLock() this.pruneRetired = false this.pruneFaultClose = undefined this.pruneFaultClosed = false + // The old retirement's errors were already reported (logged); keep the list bounded. + this.pruneCoordinationErrors = [] this.logger?.info('Scheduled prune coordination re-established on a new lock session') return true } @@ -537,15 +576,19 @@ export abstract class PostgresBaseAdapter< const run = () => { if (!lifecycle.accepting || this.pruneRunning) return Promise.resolve() - if (this.pruneRetired && !this._reestablishPruning()) return Promise.resolve() + if (this.pruneRetired && !this._reestablishPruning(config.intervalMs)) { + return Promise.resolve() + } this.pruneRunning = true + const coordinationStart = this.pruneCoordinationErrors.length return lifecycle .run(async () => { - const coordinationStart = this.pruneCoordinationErrors.length const pruneErrors: unknown[] = [] let acquired = false try { acquired = await this._acquirePruneLock() + // The lock session works again: a later failed replacement starts a new backoff. + this.pruneReplaceFailures = 0 } catch (error) { this._retirePruning(error) } @@ -583,17 +626,34 @@ export abstract class PostgresBaseAdapter< closeErrors.push(error) } } + const coordinationErrors = this.pruneCoordinationErrors.slice(coordinationStart) + // Only a lost established lock session (benign and self-healing): warn. + if ( + !pruneErrors.length && + !closeErrors.length && + coordinationErrors.length && + this.pruneRetired && + this._canReplacePruneLock() + ) { + const err = + coordinationErrors.length === 1 + ? coordinationErrors[0] + : new AggregateError(coordinationErrors, 'Scheduled prune coordination lost') + this.logger?.warn( + { err }, + 'Scheduled prune coordination session lost; a later tick re-establishes it', + ) + return + } throwLifecycleErrors( - [ - ...pruneErrors, - ...this.pruneCoordinationErrors.slice(coordinationStart), - ...closeErrors, - ], + [...pruneErrors, ...coordinationErrors, ...closeErrors], 'Scheduled prune failed: prune first, then coordination/release/close failures', ) }) .catch((error) => this.logger?.error(error, 'Error in prune scheduler')) .finally(() => { + // This pass reported its coordination errors; do not retain them. + this.pruneCoordinationErrors.splice(coordinationStart) this.pruneRunning = false }) } diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index 0ae2db3..5ce3817 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -33,6 +33,8 @@ export type DB = ReturnType | string> { private pruneLock: PostgresPruneLock | undefined + /** The next lock replaces a lost one (see `_resetPruneLock`). */ + private pruneLockReplaced = false protected override async _executeWaitRead( budget: WaitReadBudget, @@ -75,8 +77,11 @@ export class PostgresAdapter extends PostgresBaseAdapter { - this.pruneLock ??= new PostgresPruneLock(this.connection, lifecycleFor(this), (error) => - this._retirePruning(error), + this.pruneLock ??= new PostgresPruneLock( + this.connection, + lifecycleFor(this), + (error) => this._retirePruning(error), + this.pruneLockReplaced, ) return this.pruneLock.acquire() } @@ -90,12 +95,21 @@ export class PostgresAdapter extends PostgresBaseAdapter | string, readonly lifecycle: Lifecycle, readonly retire: (error: unknown) => void, + /** Replaces a lost session's lock: a failed bootstrap may be retried on a later tick. */ + readonly replacement = false, ) { const options: Options = { ...(typeof connection === 'string' ? {} : connection), @@ -97,12 +117,21 @@ export class PostgresPruneLock { // A failed transition cannot establish safe reservation ownership, even // when the transport is still alive and its observed PID is malformed. this.#uncertain = true + if (!this.#established) this.#bootstrapFailed = true throw error } finally { this.#bootstrapPending = false } } + /** An established session whose statement failed because the connection was lost. */ + #noteLoss(statement: Promise): Promise { + return statement.catch((error: unknown) => { + if (this.#established && isConnectionLoss(error)) this.#lostAfterEstablished = true + throw error + }) + } + async acquire(): Promise { this.#setup ??= this.#establish() if (!(await this.#setup) || !this.lifecycle.accepting || this.#uncertain || this.#closing) { @@ -110,9 +139,9 @@ export class PostgresPruneLock { } this.lifecycle.assertContinuation() this.#lock = 'unknown' - const rows = await this.#session!<{ pid: number; acquired: boolean }[]>` + const rows = await this.#noteLoss(this.#session!<{ pid: number; acquired: boolean }[]>` SELECT pg_backend_pid() AS pid, pg_try_advisory_lock(42) AS acquired - ` + `) if (rows.length !== 1 || rows[0]?.pid !== this.#pid || typeof rows[0]?.acquired !== 'boolean') { throw new Error('Malformed scheduled prune acquisition or changed backend') } @@ -124,9 +153,9 @@ export class PostgresPruneLock { if (this.#uncertain || this.#closing) return this.lifecycle.assertContinuation() this.#lock = 'unknown' - const rows = await this.#session!<{ pid: number; released: boolean }[]>` + const rows = await this.#noteLoss(this.#session!<{ pid: number; released: boolean }[]>` SELECT pg_backend_pid() AS pid, pg_advisory_unlock(42) AS released - ` + `) if (rows.length !== 1 || rows[0]?.pid !== this.#pid || rows[0]?.released !== true) { throw new Error('False or malformed scheduled prune unlock or changed backend') } @@ -135,13 +164,33 @@ export class PostgresPruneLock { /** * True when an established reserved session was lost (server restart, idle timeout, - * terminated backend). Once this client's close is confirmed, a new lock may replace it. + * terminated backend): observed as the session closing on its own, or as a statement of + * the session failing with a connection-loss error. Once this client's close is + * confirmed, a new lock may replace it. * Bootstrap failures and uncertain or malformed coordination results never qualify. */ get lostAfterEstablished(): boolean { return this.#lostAfterEstablished } + /** + * True when this replacement lock failed its bootstrap (the server was not reachable yet, + * for example during a failover). It never held key 42, so once its close is confirmed a + * later tick may try another replacement. + */ + get replacementBootstrapFailed(): boolean { + return this.replacement && this.#bootstrapFailed + } + + /** + * After a confirmed close: remove this lock's discharged lifecycle obligations, so the + * lifecycle no longer retains this replaced lock or its postgres.js client. + */ + dispose(): void { + this.lifecycle.dispose(this.#obligation) + this.lifecycle.dispose(this.#returnObligation) + } + faultClose(): Promise { return this.#obligation.observeEarlyClose() } diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 8310e62..27c181a 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -735,6 +735,8 @@ export class Client< if (outcome.reason === 'read-failed') { throw new WaitReadFailedError(jobId, { cause: outcome.error }) } + // The Client stopped while waiting: the usual stop-gate refusal. + if (outcome.reason === 'stop') throw new Error('Lifecycle is not accepting work') throw new Error('Job not found') } diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index 5630292..994d40a 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -228,6 +228,20 @@ export class Lifecycle { this.#quiesce.add(callback) } + /** + * Forget a discharged obligation (its resource is confirmed released), so a replaced + * resource is not retained. An obligation that is not done stays registered. + */ + dispose(obligation: CleanupObligation): boolean { + if (!obligation.done) return false + return this.#obligations.delete(obligation) + } + + /** Diagnostic: the number of registered cleanup obligations (internal; tests). */ + get obligationCount(): number { + return this.#obligations.size + } + obligation( name: string, phase: 'database cleanup' | 'owned close', diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index bb3b620..a3acc1a 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -1222,7 +1222,7 @@ function runAdapterTests(adapterFactory: AdapterFactory) { }) for (const status of [JOB_STATUS_COMPLETED, JOB_STATUS_FAILED, JOB_STATUS_CANCELLED]) { - it(`should list ${status} jobs after false restoration (public operations)`, async () => { + it(`should keep listing a ${status} job unchanged after a false time travel (public operations)`, async () => { const jobId = await adapter.createJob({ queue: 'listing-restoration', groupKey: 'test-group', @@ -1281,6 +1281,63 @@ function runAdapterTests(adapterFactory: AdapterFactory) { }) } + for (const status of [JOB_STATUS_COMPLETED, JOB_STATUS_FAILED, JOB_STATUS_CANCELLED]) { + it(`should list a legacy ${status} job left in active storage (seeded legacy state)`, async () => { + const jobId = await adapter.createJob({ + queue: 'listing-legacy', + groupKey: 'test-group', + input: { retained: 'input' }, + timeoutMs: 60_000, + checksum: 'abc123', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }) + expectToBeDefined(jobId) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + if (status === JOB_STATUS_COMPLETED) { + expect(await adapter.completeJob({ jobId, output: { retained: 'output' } })).toBe(true) + } else if (status === JOB_STATUS_FAILED) { + expect(await adapter.failJob({ jobId, error: { message: 'retained failure' } })).toBe( + true, + ) + } else { + expect(await adapter.cancelJob({ jobId })).toBe(true) + } + const before = await adapter.getJobs({ filters: { status } }) + // Seeded SQL (labelled): an older version's false time travel left the terminal job + // in active storage. Listing still finds it under its status, exactly once. + const { db } = adapter as unknown as { + db: { execute: (query: SQL) => Promise } + } + const columns = sql.raw(`id, action_name, group_key, description, status, checksum, + input, output, error, timeout_ms, expires_at, started_at, finished_at, client_id, + concurrency_limit, concurrency_step_limit, created_at, updated_at`) + await db.execute(sql`INSERT INTO duron.jobs_active (${columns}) + SELECT ${columns} FROM duron.jobs_archive WHERE id = ${jobId}`) + await db.execute(sql`DELETE FROM duron.jobs_archive WHERE id = ${jobId}`) + expect( + rowsOf(await db.execute(sql`SELECT status FROM duron.jobs_active WHERE id = ${jobId}`)), + ).toEqual([{ status }]) + + const legacy = await adapter.getJobs({ filters: { status } }) + expect(legacy).toEqual(before) + for (const filters of [{ status: [JOB_STATUS_CREATED, status] }, {}]) { + const result = await adapter.getJobs({ filters }) + expect(result.jobs.map((job) => job.id)).toEqual([jobId]) + expect(result.total).toBe(1) + } + for (const filters of [ + { status: [JOB_STATUS_CREATED, JOB_STATUS_ACTIVE] }, + { status: [] }, + { status, description: 'not-present' }, + ]) { + const result = await adapter.getJobs({ filters }) + expect(result.jobs).toEqual([]) + expect(result.total).toBe(0) + } + }) + } + it('should leave a terminal job archived, retryable and prunable after a false time travel', async () => { const jobId = await adapter.createJob({ queue: 'false-time-travel', diff --git a/packages/duron/test/prune-reestablish.test.ts b/packages/duron/test/prune-reestablish.test.ts index bd954a4..0689ec7 100644 --- a/packages/duron/test/prune-reestablish.test.ts +++ b/packages/duron/test/prune-reestablish.test.ts @@ -5,6 +5,7 @@ import postgres from 'postgres' import type { PruneArchiveOptions } from '../src/adapters/adapter.js' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { lifecycleFor } from '../src/lifecycle.js' import { getPostgresConnection } from './docker.js' @@ -78,8 +79,11 @@ if (process.env['POSTGRES_TEST'] === 'true') { }) await eventually(async () => expect(hooks).toBeGreaterThan(0)) await observer`SELECT pg_terminate_backend(${lost})` + // A benign loss of an established session is a warning, not an error. await eventually(async () => - expect(entries.some((entry) => entry.level === 'error')).toBe(true), + expect(entries.some((entry) => entry.level === 'warn' && /lost/.test(entry.msg))).toBe( + true, + ), ) const hooksAtLoss = hooks // A new lock session (another backend) serves later passes. @@ -90,6 +94,35 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(hooks).toBeGreaterThan(hooksAtLoss) }) expect(entries.some((entry) => /re-established/.test(entry.msg))).toBe(true) + + // Repeated losses (an idle timeout shorter than the interval) must not accumulate the + // replaced locks: their lifecycle obligations, clients and coordination errors. + const internals = adapter as unknown as { + pruneLock?: { client: { stats?: { connections: number; opening: number } } } + pruneCoordinationErrors: unknown[] + } + const obligations = lifecycleFor(adapter).obligationCount + const replaced: Array<{ stats?: { connections: number; opening: number } }> = [] + let current = (await lockSessions())[0]!.pid + for (let loss = 0; loss < 4; loss++) { + replaced.push(internals.pruneLock!.client) + const hooksBefore = hooks + await observer`SELECT pg_terminate_backend(${current})` + await eventually(async () => { + const sessions = await lockSessions() + expect(sessions).toHaveLength(1) + expect(sessions[0]!.pid).not.toBe(current) + expect(hooks).toBeGreaterThan(hooksBefore) + current = sessions[0]!.pid + }) + expect(lifecycleFor(adapter).obligationCount).toBe(obligations) + expect(internals.pruneCoordinationErrors.length).toBeLessThanOrEqual(1) + } + // Every replaced client was ended: no open or opening connection remains. + for (const client of replaced) { + expect(client.stats).toEqual(expect.objectContaining({ connections: 0, opening: 0 })) + } + expect(entries.filter((entry) => entry.level === 'error')).toEqual([]) expect(await adapter.stop()).toBe(true) } finally { await adapter.stop().catch(() => undefined) @@ -97,4 +130,82 @@ if (process.env['POSTGRES_TEST'] === 'true') { await deleteDb() } }, 30_000) + + it('retries a replacement lock whose bootstrap fails on later ticks with a growing backoff', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() + let hooks = 0 + class CountingPrune extends PostgresAdapter { + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + hooks++ + return super._pruneArchive(options) + } + } + const application = `replacement-retry-${crypto.randomUUID()}` + const url = new URL(CONNECTION_URL) + const connection = { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + connection: { application_name: application }, + } + const adapter = new CountingPrune({ + connection, + pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: 50 }, + }) + adapter.setId(application) + const entries: Array<{ level: string; msg: string; at: number }> = [] + const logger = pino({ level: 'silent' }) + for (const level of ['error', 'warn', 'info'] as const) { + logger[level] = ((value: unknown, message?: string) => { + entries.push({ + level, + msg: message ?? (value instanceof Error ? value.message : String(value)), + at: performance.now(), + }) + }) as never + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + const lockSessions = () => observer<{ pid: number }[]>` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND application_name = ${application} + AND query LIKE '%advisory%lock(42)%' + ` + try { + expect(await adapter.start()).toBe(true) + let lost = 0 + await eventually(async () => { + const sessions = await lockSessions() + expect(sessions).toHaveLength(1) + lost = sessions[0]!.pid + }) + // Replacement lock clients fail to authenticate (as during a failover window). The + // query pool was created at start and keeps its own copy of the options. + connection.password = 'deliberately-invalid-replacement-password' + await observer`SELECT pg_terminate_backend(${lost})` + const retries = () => entries.filter((entry) => /replacement .* retrying/.test(entry.msg)) + await eventually(async () => expect(retries().length).toBeGreaterThanOrEqual(3)) + // The backoff grows between failed replacement attempts. + const [first, second, third] = retries() + expect(third!.at - second!.at).toBeGreaterThan(second!.at - first!.at) + const obligations = lifecycleFor(adapter).obligationCount + // The server is reachable again: a later attempt establishes a new session. + connection.password = url.password + const hooksBefore = hooks + await eventually(async () => { + const sessions = await lockSessions() + expect(sessions).toHaveLength(1) + expect(sessions[0]!.pid).not.toBe(lost) + expect(hooks).toBeGreaterThan(hooksBefore) + }, 20_000) + expect(lifecycleFor(adapter).obligationCount).toBeLessThanOrEqual(obligations) + expect(await adapter.stop()).toBe(true) + } finally { + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 40_000) } diff --git a/packages/duron/test/prune-scheduler.test.ts b/packages/duron/test/prune-scheduler.test.ts index d7af11b..e65ca5a 100644 --- a/packages/duron/test/prune-scheduler.test.ts +++ b/packages/duron/test/prune-scheduler.test.ts @@ -166,6 +166,13 @@ if (process.env['POSTGRES_TEST'] === 'true') { super._retirePruning(error) } protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + // Passes of the re-established coordination (after the loss) do not prune, so the + // direct pruneArchive below finds the job. + const scheduled = ( + this as unknown as { scheduledPrune: { getStore(): boolean | undefined } } + ).scheduledPrune.getStore() + if (entered && scheduled) return 0 + if (entered) return super._pruneArchive(options) entered = true await release.promise try { diff --git a/packages/duron/test/prune-transport.test.ts b/packages/duron/test/prune-transport.test.ts index ad4b40e..5908e3c 100644 --- a/packages/duron/test/prune-transport.test.ts +++ b/packages/duron/test/prune-transport.test.ts @@ -106,6 +106,10 @@ if (process.env['POSTGRES_TEST'] === 'true') { logger.error = (error: unknown) => { reports.push(error) } + // The loss of an established session without a prune error is a benign warning. + logger.warn = ((fields: { err?: unknown }) => { + reports.push(fields?.err ?? fields) + }) as never adapter.setLogger(logger) const observer = postgres(CONNECTION_URL, { max: 1 }) try { diff --git a/packages/duron/test/stop-in-handler.test.ts b/packages/duron/test/stop-in-handler.test.ts index 822ec54..591cb0d 100644 --- a/packages/duron/test/stop-in-handler.test.ts +++ b/packages/duron/test/stop-in-handler.test.ts @@ -26,14 +26,13 @@ for (const factory of [ ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), ]) { describe(`stop() awaited inside admitted work with ${factory.name}`, () => { - for (const where of ['handler', 'step', 'handler after an external stop'] as const) { + for (const where of ['handler', 'step'] as const) { it(`completes promptly when awaited inside a ${where}`, async () => { const instance = await factory.create() const id = `stop-inside-${crypto.randomUUID()}` let client: Client | null = null type Outcome = { result?: unknown; error?: unknown; ms: number } const stopped = Promise.withResolvers() - const external = Promise.withResolvers() const stopHere = async () => { const start = performance.now() try { @@ -46,12 +45,7 @@ for (const factory of [ name: 'shutdown', handler: async (ctx) => { if (where === 'step') await ctx.step('stop', stopHere) - else if (where === 'handler') await stopHere() - else { - // Another caller began stopping first; this handler then awaits stop() too. - void client!.stop().then(external.resolve, external.reject) - await stopHere() - } + else await stopHere() return {} }, }) @@ -74,9 +68,6 @@ for (const factory of [ expect(outcome.error).toBeUndefined() expect(outcome.result).toBe(true) expect(outcome.ms).toBeLessThan(3_000) - if (where === 'handler after an external stop') { - expect(await external.promise).toBe(true) - } if (factory.name === 'postgres') { // The calling job was aborted and wrote its cancellation; liveness was released. const reader = new PostgresAdapter({ connection: instance.connectionUrl }) @@ -94,5 +85,74 @@ for (const factory of [ } }, 15_000) } + + it('completes when a stop from outside began first and the handler then awaits stop()', async () => { + const instance = await factory.create() + const id = `stop-ordering-${crypto.randomUUID()}` + type Outcome = { result?: unknown; error?: unknown; ms: number } + const started = Promise.withResolvers() + const gate = Promise.withResolvers() + const inner = Promise.withResolvers() + let client: Client | null = null + const action = defineAction()({ + name: 'held-shutdown', + handler: async () => { + started.resolve() + // Ignores the abort of the outside stop: its raw promise keeps the drain waiting. + await gate.promise + const start = performance.now() + try { + inner.resolve({ result: await client!.stop(), ms: performance.now() - start }) + } catch (error) { + inner.resolve({ error, ms: performance.now() - start }) + } + return {} + }, + }) + client = new Client({ + id, + database: instance.adapter, + actions: { action }, + syncPattern: false, + recoverJobsOnStart: false, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + const jobId = await client.runAction('action', {}) + await client.fetch() + await started.promise + // The test body has no lifecycle context: this stop excludes nothing. + const begun = performance.now() + const external = client.stop().then( + (result): Outcome => ({ result, ms: performance.now() - begun }), + (error: unknown): Outcome => ({ error, ms: performance.now() - begun }), + ) + await Bun.sleep(100) + gate.resolve() + const outside = await Promise.race([ + external, + Bun.sleep(4_000).then((): Outcome => ({ error: 'stop() did not settle', ms: 4_000 })), + ]) + expect(outside.error).toBeUndefined() + expect(outside.result).toBe(true) + expect(outside.ms).toBeLessThan(3_000) + expect((await inner.promise).result).toBe(true) + if (factory.name === 'postgres') { + const reader = new PostgresAdapter({ connection: instance.connectionUrl }) + reader.setId('stop-ordering-reader') + try { + expect((await reader.getJobById(jobId))?.status).toBe('cancelled') + expect(await livenessRows(reader, id)).toBe(0) + } finally { + await reader.stop() + } + } + } finally { + gate.resolve() + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 15_000) }) } diff --git a/packages/duron/test/time-travel-archive-lock.test.ts b/packages/duron/test/time-travel-archive-lock.test.ts new file mode 100644 index 0000000..2277b85 --- /dev/null +++ b/packages/duron/test/time-travel-archive-lock.test.ts @@ -0,0 +1,73 @@ +import { expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +// Native: time travel locks the archived job row before it copies the job and its steps. +// A concurrent prune (here an uncommitted DELETE of the archived row) makes it wait; once +// the prune commits, the time travel finds nothing to restore and returns false. Without +// the lock it would copy the job from its snapshot and resurrect a pruned job. + +if (process.env['POSTGRES_TEST'] === 'true') { + it('time travel waits for a concurrent prune of the archived job and restores nothing', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() + const adapter = new PostgresAdapter({ connection: CONNECTION_URL }) + adapter.setId('tt-archive-lock') + const pruner = postgres(CONNECTION_URL, { max: 1 }) + const commit = Promise.withResolvers() + const deleted = Promise.withResolvers() + let pruning: Promise | undefined + try { + expect(await adapter.start()).toBe(true) + const jobId = (await adapter.createJob({ + queue: 'tt-archive-lock', + groupKey: 'one', + input: {}, + timeoutMs: 60_000, + checksum: 'tt', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + const step = await adapter.createOrRecoverJobStep({ + jobId, + name: 'target', + timeoutMs: 60_000, + retriesLimit: 0, + }) + expect(await adapter.completeJobStep({ stepId: step!.id, output: 1 })).toBe(true) + expect(await adapter.completeJob({ jobId, output: {} })).toBe(true) + + // A prune holds the archived row (and, by cascade, its steps) until it commits. + pruning = pruner.begin(async (tx) => { + await tx`DELETE FROM duron.jobs_archive WHERE id = ${jobId}` + deleted.resolve() + await commit.promise + }) + pruning.catch((error: unknown) => deleted.reject(error)) + await deleted.promise + + let settled = false + const travel = adapter.timeTravelJob({ jobId, stepId: step!.id }).finally(() => { + settled = true + }) + await Bun.sleep(300) + // It waits on the archive row lock instead of copying a snapshot of the job. + expect(settled).toBe(false) + commit.resolve() + await pruning + expect(await travel).toBe(false) + expect(await adapter.getJobById(jobId)).toBeNull() + expect(await adapter.getJobStepById(step!.id)).toBeNull() + } finally { + commit.resolve() + await pruning?.catch(() => undefined) + await adapter.stop() + await pruner.end({ timeout: 5 }) + await deleteDb() + } + }, 30_000) +} diff --git a/packages/duron/test/wait-read-errors.test.ts b/packages/duron/test/wait-read-errors.test.ts index 6ab92b0..3916fb8 100644 --- a/packages/duron/test/wait-read-errors.test.ts +++ b/packages/duron/test/wait-read-errors.test.ts @@ -62,3 +62,35 @@ for (const factory of [ } }) } + +describe('runActionAndWait while the Client stops', () => { + it('rejects with the stop-gate refusal, not "Job not found"', async () => { + const instance = await pgliteFactory.create() + const action = defineAction()({ name: 'unclaimed', handler: async () => ({}) }) + const client = new Client({ + database: instance.adapter, + actions: { action }, + syncPattern: false, + recoverJobsOnStart: false, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + const waiting = client.runActionAndWait('action', {}).then( + () => null, + (error: unknown) => error, + ) + // The job is created and the wait is pending (nothing claims the job). + const end = performance.now() + 5_000 + while ((await instance.adapter.getJobs()).total === 0 && performance.now() < end) { + await Bun.sleep(10) + } + await Bun.sleep(50) + expect(await client.stop()).toBe(true) + expect(((await waiting) as Error).message).toBe('Lifecycle is not accepting work') + } finally { + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }) +}) From 1ee7267e2fac6867fe90a00be7a4de813af344a6 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 07:44:48 -0300 Subject: [PATCH 072/100] test: count only client backends in native session assertions The gate failure of prune-transport 'post-boundary idle loss' (1 session left after adapter.stop()) was not a leaked connection: a self-attributing rerun caught it as backend_type 'autovacuum worker' (application_name '', started 24 ms after stop began). Autovacuum workers carry the database's datname in pg_stat_activity, so every "sessions of this test database" count could see one. Native session assertions now add backend_type = 'client backend'; the prune-transport post-stop check reports pid/backend_type/application_name/ backend_start/state and the sessions seen before stop. --- packages/duron/test/cancel-storage.test.ts | 2 +- packages/duron/test/claim-isolation.test.ts | 2 +- packages/duron/test/cross-mechanism.test.ts | 2 +- packages/duron/test/lifecycle-budgets.test.ts | 2 +- packages/duron/test/lifecycle-errors.test.ts | 4 +-- .../test/lifecycle-handler-entry.test.ts | 2 +- packages/duron/test/lifecycle-startup.test.ts | 2 +- packages/duron/test/lifecycle.test.ts | 12 ++++----- packages/duron/test/notifications.test.ts | 4 +-- packages/duron/test/prune-bootstrap.test.ts | 8 +++--- packages/duron/test/prune-loss.test.ts | 2 +- packages/duron/test/prune-ownership.test.ts | 26 +++++++++---------- packages/duron/test/prune-replies.test.ts | 4 +-- packages/duron/test/prune-scheduler.test.ts | 6 ++--- packages/duron/test/prune-scope.test.ts | 3 ++- packages/duron/test/prune-transport.test.ts | 15 ++++++++--- packages/duron/test/recover-snapshot.test.ts | 2 +- packages/duron/test/wait-native.test.ts | 4 ++- 18 files changed, 56 insertions(+), 46 deletions(-) diff --git a/packages/duron/test/cancel-storage.test.ts b/packages/duron/test/cancel-storage.test.ts index 3120175..91953ef 100644 --- a/packages/duron/test/cancel-storage.test.ts +++ b/packages/duron/test/cancel-storage.test.ts @@ -325,7 +325,7 @@ async function cancelDatabase() { await eventually(async () => { const rows = await admin` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid()` + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'` return rows[0]!['count'] === 0 }) } catch (error) { diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 2cffdd2..7e825d3 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -226,7 +226,7 @@ async function claimDatabase() { await barrier.end({ timeout: 5 }) await eventually(async () => { const rows = - await admin`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + await admin`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'` return rows[0]!['count'] === 0 }) } catch (error) { diff --git a/packages/duron/test/cross-mechanism.test.ts b/packages/duron/test/cross-mechanism.test.ts index 43332e8..e723dad 100644 --- a/packages/duron/test/cross-mechanism.test.ts +++ b/packages/duron/test/cross-mechanism.test.ts @@ -388,7 +388,7 @@ for (const factory of factories) { let sessions = -1 while (sessions !== 0 && performance.now() < deadline) { const rows = - await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'` sessions = rows[0]!['count'] as number if (sessions !== 0) await Bun.sleep(20) } diff --git a/packages/duron/test/lifecycle-budgets.test.ts b/packages/duron/test/lifecycle-budgets.test.ts index 141bde1..8f2b301 100644 --- a/packages/duron/test/lifecycle-budgets.test.ts +++ b/packages/duron/test/lifecycle-budgets.test.ts @@ -135,7 +135,7 @@ for (const factory of [ if (observer) { const sessions = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions[0]!['count']).toBe(0) } else expect(adapter.db.$client.closed).toBe(true) diff --git a/packages/duron/test/lifecycle-errors.test.ts b/packages/duron/test/lifecycle-errors.test.ts index 7a205b3..04c83cc 100644 --- a/packages/duron/test/lifecycle-errors.test.ts +++ b/packages/duron/test/lifecycle-errors.test.ts @@ -65,7 +65,7 @@ for (const factory of [ if (observer) { const sessions = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions[0]!['count']).toBe(0) } else expect(adapter.db.$client.closed).toBe(true) @@ -167,7 +167,7 @@ for (const factory of [ if (observer) { const sessions = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions[0]!['count']).toBe(0) } else expect(adapter.db.$client.closed).toBe(true) diff --git a/packages/duron/test/lifecycle-handler-entry.test.ts b/packages/duron/test/lifecycle-handler-entry.test.ts index 100982e..2f6b810 100644 --- a/packages/duron/test/lifecycle-handler-entry.test.ts +++ b/packages/duron/test/lifecycle-handler-entry.test.ts @@ -103,7 +103,7 @@ for (const factory of [ expect(calls).toBe(0) if (observer) { const sessions = - await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'` expect(sessions[0]!['count']).toBe(0) const rows = await observer`SELECT count(*)::int AS count FROM duron.clients WHERE client_id = ${clientId}` diff --git a/packages/duron/test/lifecycle-startup.test.ts b/packages/duron/test/lifecycle-startup.test.ts index 54014b6..42147e4 100644 --- a/packages/duron/test/lifecycle-startup.test.ts +++ b/packages/duron/test/lifecycle-startup.test.ts @@ -136,7 +136,7 @@ for (const factory of [ if (observer) { const sessions = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions[0]!['count']).toBe(0) } else expect(driver.closed).toBe(true) diff --git a/packages/duron/test/lifecycle.test.ts b/packages/duron/test/lifecycle.test.ts index 8341afe..92e6699 100644 --- a/packages/duron/test/lifecycle.test.ts +++ b/packages/duron/test/lifecycle.test.ts @@ -108,7 +108,7 @@ for (const factory of [ expect(unlistens).toBe(2) if (observer) { const sessions = - await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + await observer`SELECT count(*)::int AS count FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'` expect(sessions[0]!['count']).toBe(0) } else { expect(adapter.db.$client.closed).toBe(true) @@ -633,7 +633,7 @@ for (const factory of [ if (observer) { const sessions = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions[0]!['count']).toBe(0) } else { @@ -669,7 +669,7 @@ for (const factory of [ if (observer) { const sessions = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions[0]!['count']).toBe(0) } else { @@ -793,7 +793,7 @@ for (const factory of [ if (observer) { const sessions = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions[0]!['count']).toBe(0) const clients = await observer`SELECT client_id FROM duron.clients` @@ -912,7 +912,7 @@ for (const factory of [ if (observer) { const rows = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(rows[0]!['count']).toBe(0) } else { @@ -953,7 +953,7 @@ for (const factory of [ if (observer) { const rows = await observer` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(rows[0]!['count']).toBe(0) } else { diff --git a/packages/duron/test/notifications.test.ts b/packages/duron/test/notifications.test.ts index e17025b..cacdb48 100644 --- a/packages/duron/test/notifications.test.ts +++ b/packages/duron/test/notifications.test.ts @@ -446,7 +446,7 @@ for (const factory of [ // Force a query connection as well as the real dedicated LISTEN pool. await adapter.db.$client.unsafe!('SELECT 1') const sessions = - await observer`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()` + await observer`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'` expect(sessions.length).toBeGreaterThanOrEqual(2) } else { const rows = ( @@ -496,7 +496,7 @@ for (const factory of [ await adapter.stop() if (observer) { expect( - await observer`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid()`, + await observer`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'`, ).toHaveLength(0) } released = true diff --git a/packages/duron/test/prune-bootstrap.test.ts b/packages/duron/test/prune-bootstrap.test.ts index d6dfa99..17333b4 100644 --- a/packages/duron/test/prune-bootstrap.test.ts +++ b/packages/duron/test/prune-bootstrap.test.ts @@ -127,7 +127,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect( await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) }) @@ -220,7 +220,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect( await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) }) @@ -389,7 +389,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect( await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(failure === 'close acknowledgment' ? 0 : 2) if (failure !== 'close acknowledgment') @@ -400,7 +400,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect( await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) }) diff --git a/packages/duron/test/prune-loss.test.ts b/packages/duron/test/prune-loss.test.ts index c747ac3..67629ce 100644 --- a/packages/duron/test/prune-loss.test.ts +++ b/packages/duron/test/prune-loss.test.ts @@ -148,7 +148,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect( await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) }) diff --git a/packages/duron/test/prune-ownership.test.ts b/packages/duron/test/prune-ownership.test.ts index 683aa88..11f17ce 100644 --- a/packages/duron/test/prune-ownership.test.ts +++ b/packages/duron/test/prune-ownership.test.ts @@ -108,7 +108,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(ends).toBe(1) expect( await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) } finally { @@ -158,7 +158,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { expect( await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) }) @@ -343,7 +343,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect( await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) expect(await adapter.stop()).toBe(true) @@ -421,7 +421,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(0) }) @@ -489,7 +489,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(returnCalls).toBe(0) const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(1) expect(await observer`SELECT client_id FROM duron.clients`).toHaveLength(0) @@ -498,7 +498,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const remaining = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(remaining).toHaveLength(0) }) @@ -513,7 +513,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(0) }) @@ -564,7 +564,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(0) }) @@ -607,7 +607,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(0) }) @@ -668,7 +668,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(ends).toBe(0) expect( await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(1) const second = await adapter.stop().catch((error: unknown) => error) @@ -679,7 +679,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { expect( await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) }) @@ -735,7 +735,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(0) }) @@ -750,7 +750,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(0) }) diff --git a/packages/duron/test/prune-replies.test.ts b/packages/duron/test/prune-replies.test.ts index 2cbb574..943c328 100644 --- a/packages/duron/test/prune-replies.test.ts +++ b/packages/duron/test/prune-replies.test.ts @@ -119,7 +119,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { else expect(stats.lastPrunedAt).toBeInstanceOf(Date) expect( await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(2) await Bun.sleep(100) @@ -129,7 +129,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(returns).toBe(0) expect( await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(0) } finally { diff --git a/packages/duron/test/prune-scheduler.test.ts b/packages/duron/test/prune-scheduler.test.ts index e65ca5a..b745c83 100644 --- a/packages/duron/test/prune-scheduler.test.ts +++ b/packages/duron/test/prune-scheduler.test.ts @@ -68,7 +68,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(0) }) @@ -113,7 +113,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(adapter.calls).toBe(1) const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` // Query + dedicated listener still live; isolated lock backend is gone. expect(sessions).toHaveLength(2) @@ -129,7 +129,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const sessions = await observer` SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid() + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions).toHaveLength(0) }) diff --git a/packages/duron/test/prune-scope.test.ts b/packages/duron/test/prune-scope.test.ts index e7e20e8..6e0e21b 100644 --- a/packages/duron/test/prune-scope.test.ts +++ b/packages/duron/test/prune-scope.test.ts @@ -109,6 +109,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await observer` SELECT pid FROM pg_stat_activity WHERE datname IN (${new URL(first.CONNECTION_URL).pathname.slice(1)}, ${new URL(other.CONNECTION_URL).pathname.slice(1)}) + AND backend_type = 'client backend' AND pid <> pg_backend_pid() `, ).toHaveLength(0) @@ -134,7 +135,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect((adapter as unknown as { pruneLock?: unknown }).pruneLock).toBeUndefined() expect( await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' `, ).toHaveLength(2) expect( diff --git a/packages/duron/test/prune-transport.test.ts b/packages/duron/test/prune-transport.test.ts index 5908e3c..269a79c 100644 --- a/packages/duron/test/prune-transport.test.ts +++ b/packages/duron/test/prune-transport.test.ts @@ -163,15 +163,22 @@ if (process.env['POSTGRES_TEST'] === 'true') { // Same single observation; identity columns make an unexpected count self-attributing. const sessions = await observer` SELECT pid, backend_type, application_name, backend_start, state - FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() + FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' ` expect(sessions, JSON.stringify({ phase, cutPid: pid, sessions })).toHaveLength(2) + const stopBegan = new Date() expect(await adapter.stop()).toBe(true) expect(returns).toBe(0) + // Client backends only: background workers of this database (autovacuum) also appear + // in pg_stat_activity with its datname. Identity columns make a failure self-attributing. + const remaining = await observer` + SELECT pid, backend_type, application_name, backend_start, state + FROM pg_stat_activity + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend' + ` expect( - await observer` - SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid() - `, + remaining, + JSON.stringify({ phase, cutPid: pid, stopBegan, before: sessions, remaining }), ).toHaveLength(0) expect(relay.connections).toHaveLength(1) expect(relay.errors).toEqual([]) diff --git a/packages/duron/test/recover-snapshot.test.ts b/packages/duron/test/recover-snapshot.test.ts index fdda0cd..5329c8b 100644 --- a/packages/duron/test/recover-snapshot.test.ts +++ b/packages/duron/test/recover-snapshot.test.ts @@ -400,7 +400,7 @@ async function recoveryDatabase() { await eventually(async () => { const rows = await admin` SELECT count(*)::int AS count FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid()` + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'` return rows[0]!['count'] === 0 }) } catch (error) { diff --git a/packages/duron/test/wait-native.test.ts b/packages/duron/test/wait-native.test.ts index 1517a6e..eb765e0 100644 --- a/packages/duron/test/wait-native.test.ts +++ b/packages/duron/test/wait-native.test.ts @@ -44,7 +44,9 @@ function sessionSnapshot(admin: postgres.Sql): Promise { 'keyword', upper(substring(query FROM '^[[:space:]]*([A-Za-z]+)')) ) ORDER BY pid), '[]'::json) AS sessions FROM pg_stat_activity - WHERE datname = current_database() AND pid <> pg_backend_pid()`.then((rows) => rows[0]) + WHERE datname = current_database() AND pid <> pg_backend_pid() AND backend_type = 'client backend'`.then( + (rows) => rows[0], + ) } // Separate observer on the main database: fresh whole-target zero (no pid exclusion) and catalog From ede07195183265e04b8e2d0166db83f714579e80 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 09:21:35 -0300 Subject: [PATCH 073/100] fix: aborted steps settle before their job; CI-only test timing assumptions Real bugs (red-first: test/step-abort-settlement.test.ts, deterministic with a held step failure write, PGlite + PostgreSQL): - StepManager.drain() called fastq's `drain` hook (a no-op) instead of `drained()`, so a failing job did not wait for its running steps: a slow step failure write lost the race with failJob and the step was archived 'active' under the failed job. ActionManager.drain() had the same mistake. - A step's abort race used waitForAbort's promise with only a fulfilment handler; it rejects on abort, so a parent step that timed out rethrew at once without waiting for its children (the abort branch was dead code). These caused CI's nested-steps 'should abort child steps when parent times out' failure (child archived 'active'; reproduced locally under CPU load). Test assumptions: - time-travel 'keep parallel sibling': branch-b failed while branch-a might not even be created yet (the failure aborts running siblings); branch-b now fails only after branch-a completed. - wait-read-errors and other new PGlite tests had no explicit timeout: Bun ignores bunfig [test] timeout (oven-sh/bun#7789), so the default is 5 s, and the first PGlite start in a file takes 6-13 s on a slow CPU. They now pass 20 s; the misleading bunfig line is replaced by a comment. --- bunfig.toml | 4 +- packages/duron/src/action-manager.ts | 3 +- packages/duron/src/step-manager.ts | 16 +- packages/duron/test/claim-pglite.test.ts | 102 +++++----- .../duron/test/client-adapter-binding.test.ts | 10 +- packages/duron/test/lifecycle-errors.test.ts | 2 +- packages/duron/test/liveness-absence.test.ts | 4 +- .../duron/test/step-abort-settlement.test.ts | 178 ++++++++++++++++++ packages/duron/test/time-travel.test.ts | 42 +++-- packages/duron/test/wait-lifecycle.test.ts | 2 +- packages/duron/test/wait-read-errors.test.ts | 4 +- 11 files changed, 281 insertions(+), 86 deletions(-) create mode 100644 packages/duron/test/step-abort-settlement.test.ts diff --git a/bunfig.toml b/bunfig.toml index c7d218f..2c48ba6 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -1,4 +1,4 @@ [install] linker = "isolated" -[test] -timeout = 10000 # 10 seconds +# Bun ignores a `[test] timeout` key here (oven-sh/bun#7789): the default per-test timeout +# stays 5000 ms, so tests that can take longer (PGlite start-up on a slow CPU) set their own. diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index 4ab0e08..6b6f732 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -148,7 +148,8 @@ export class ActionManager> { * @returns Promise that resolves when the queue is drained */ async drain(): Promise { - return this.#queue.drain() + // fastq's `drain` is the hook called when the queue empties; `drained()` waits for it. + return this.#queue.drained() } /** diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index 31eba36..b89d494 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -468,7 +468,8 @@ export class StepManager { * Should be called when the job completes or is cancelled. */ async drain(): Promise { - await this.#queue.drain() + // fastq's `drain` is the hook called when the queue empties; `drained()` waits for it. + await this.#queue.drained() } /** @@ -707,9 +708,16 @@ export class StepManager { let callbackError: Error | null = null await Promise.race([ - abortPromise.promise.then(() => { - aborted = true - }), + // waitForAbort rejects with the abort reason: record the abort, then fall through + // to the abort branch below, which waits for the child steps before rethrowing. + abortPromise.promise.then( + () => { + aborted = true + }, + () => { + aborted = true + }, + ), callbackPromise .then((res) => { if (res !== undefined && res !== null) { diff --git a/packages/duron/test/claim-pglite.test.ts b/packages/duron/test/claim-pglite.test.ts index ee0e2f1..7983bdb 100644 --- a/packages/duron/test/claim-pglite.test.ts +++ b/packages/duron/test/claim-pglite.test.ts @@ -113,7 +113,7 @@ describe('PGLite claim transaction', () => { } finally { await adapter.stop() } - }) + }, 20_000) it('rolls back a claim statement error and reuses the engine for the next claim', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) @@ -147,7 +147,7 @@ describe('PGLite claim transaction', () => { } finally { await adapter.stop() } - }) + }, 20_000) it('retries a 40001 claim conflict in a fresh transaction and claims the job once', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) @@ -178,7 +178,7 @@ describe('PGLite claim transaction', () => { } finally { await adapter.stop() } - }) + }, 20_000) it('surfaces a persistent 40001 after 5 backed-off retries and claims nothing', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) @@ -216,7 +216,7 @@ describe('PGLite claim transaction', () => { } finally { await adapter.stop() } - }) + }, 20_000) for (const when of ['before', 'during'] as const) { it(`starts no claim retry once stop has begun ${when} the retry delay`, async () => { @@ -270,53 +270,57 @@ describe('PGLite claim transaction', () => { } finally { await adapter.stop() } - }) + }, 20_000) } // Serial: it pins the global Math.random so the last backoff is its full 160 ms. - it.serial('stop ends a pending claim-retry delay at once', async () => { - const adapter = new PGLiteAdapter({ connection: ':memory:' }) - adapter.setId('claim-pglite') - const random = spyOn(Math, 'random').mockReturnValue(0.999) - let stopping: Promise | undefined - let stopAt = 0 - adapter.setLogger( - pino( - { level: 'debug' }, - { - write: (line: string) => { - const entry = JSON.parse(line) - // Stop 20 ms into the 160 ms delay before the 5th retry. - if (/claim conflict/.test(entry['msg']) && entry['attempt'] === 5) { - expect(entry['delay']).toBe(160) - setTimeout(() => { - stopAt = performance.now() - stopping ??= adapter.stop() - }, 20) - } + it.serial( + 'stop ends a pending claim-retry delay at once', + async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:' }) + adapter.setId('claim-pglite') + const random = spyOn(Math, 'random').mockReturnValue(0.999) + let stopping: Promise | undefined + let stopAt = 0 + adapter.setLogger( + pino( + { level: 'debug' }, + { + write: (line: string) => { + const entry = JSON.parse(line) + // Stop 20 ms into the 160 ms delay before the 5th retry. + if (/claim conflict/.test(entry['msg']) && entry['attempt'] === 5) { + expect(entry['delay']).toBe(160) + setTimeout(() => { + stopAt = performance.now() + stopping ??= adapter.stop() + }, 20) + } + }, }, - }, - ), - ) - try { - await adapter.start() - await injectSerializationFailures(engineOf(adapter), null) - await createJobs(adapter, 1, 1) - const failed = await adapter.fetch({ batch: 1 }).then( - () => null, - (error: unknown) => error, + ), ) - const surfacedAfter = performance.now() - stopAt - expect(sqlState(failed)).toBe('40001') - expect(stopAt).toBeGreaterThan(0) - // The delay ended with the stop, well before its 160 ms. - expect(surfacedAfter).toBeLessThan(100) - expect(await stopping).toBe(true) - } finally { - random.mockRestore() - await adapter.stop() - } - }) + try { + await adapter.start() + await injectSerializationFailures(engineOf(adapter), null) + await createJobs(adapter, 1, 1) + const failed = await adapter.fetch({ batch: 1 }).then( + () => null, + (error: unknown) => error, + ) + const surfacedAfter = performance.now() - stopAt + expect(sqlState(failed)).toBe('40001') + expect(stopAt).toBeGreaterThan(0) + // The delay ended with the stop, well before its 160 ms. + expect(surfacedAfter).toBeLessThan(100) + expect(await stopping).toBe(true) + } finally { + random.mockRestore() + await adapter.stop() + } + }, + 20_000, + ) it('logs a claim conflict surfaced by a normal stop at debug level, not as errors', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) @@ -364,7 +368,7 @@ describe('PGLite claim transaction', () => { expect(entries.filter((entry) => entry['level'] >= 50)).toEqual([]) expect(entries.some((entry) => entry['msg'] === 'Error in Adapter.fetch()')).toBe(true) expect(entries.some((entry) => /Background claim failed/.test(entry['msg']))).toBe(true) - }) + }, 20_000) it('keeps a claim failure that stopping did not cause at error level during stop', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) @@ -406,7 +410,7 @@ describe('PGLite claim transaction', () => { const errors = entries.filter((entry) => entry['level'] >= 50).map((entry) => entry['msg']) expect(errors).toContain('Error in Adapter.fetch()') expect(errors.some((msg) => /Background claim failed/.test(msg))).toBe(true) - }) + }, 20_000) it('does not pause Client discovery for a single claim conflict', async () => { const adapter = new PGLiteAdapter({ connection: ':memory:' }) @@ -480,5 +484,5 @@ describe('PGLite claim transaction', () => { } finally { await client.stop() } - }) + }, 20_000) }) diff --git a/packages/duron/test/client-adapter-binding.test.ts b/packages/duron/test/client-adapter-binding.test.ts index 7008c43..27dbc90 100644 --- a/packages/duron/test/client-adapter-binding.test.ts +++ b/packages/duron/test/client-adapter-binding.test.ts @@ -41,7 +41,7 @@ describe('Client adapter binding', () => { } finally { await first.stop() } - }) + }, 20_000) // A constructor that throws after its option checks must not touch the adapter either. for (const [name, bad] of [ @@ -90,7 +90,7 @@ describe('Client adapter binding', () => { } finally { expect(await client.stop()).toBe(true) } - }) + }, 20_000) } it('accepts one Client per adapter instance on the same database', async () => { @@ -110,7 +110,7 @@ describe('Client adapter binding', () => { } finally { for (const client of clients) await client.stop() } - }) + }, 20_000) }) describe('Client.fetch without a started Client', () => { @@ -142,7 +142,7 @@ describe('Client.fetch without a started Client', () => { } finally { await client.stop() } - }) + }, 20_000) }) describe('Client.fetch racing stop', () => { @@ -160,5 +160,5 @@ describe('Client.fetch racing stop', () => { const stopping = client.stop() await expect(fetching).rejects.toThrow('Lifecycle is not accepting work') expect(await stopping).toBe(true) - }) + }, 20_000) }) diff --git a/packages/duron/test/lifecycle-errors.test.ts b/packages/duron/test/lifecycle-errors.test.ts index 04c83cc..ff87988 100644 --- a/packages/duron/test/lifecycle-errors.test.ts +++ b/packages/duron/test/lifecycle-errors.test.ts @@ -41,7 +41,7 @@ for (const factory of [ await adapter.stop().catch(() => undefined) await instance.deleteDb() } - }) + }, 20_000) it('does not suppress an expected-relation absence after successful initialization', async () => { const instance = await factory.create() diff --git a/packages/duron/test/liveness-absence.test.ts b/packages/duron/test/liveness-absence.test.ts index 1f190e9..3f23941 100644 --- a/packages/duron/test/liveness-absence.test.ts +++ b/packages/duron/test/liveness-absence.test.ts @@ -49,7 +49,7 @@ describe('Liveness table absence before migration', () => { 'CREATE SCHEMA IF NOT EXISTS duron; CREATE TABLE duron.clients (client_id text PRIMARY KEY)', ) expect(await adapter.stop()).toBe(true) - }) + }, 20_000) }) describe('Liveness table probe failure', () => { @@ -87,5 +87,5 @@ describe('Liveness table probe failure', () => { expect(probe?.['originalCode']).toBe('42P01') expect(probe?.['originalMessage']).toContain('clients') await adapter.stop().catch(() => undefined) - }) + }, 20_000) }) diff --git a/packages/duron/test/step-abort-settlement.test.ts b/packages/duron/test/step-abort-settlement.test.ts new file mode 100644 index 0000000..7d164c6 --- /dev/null +++ b/packages/duron/test/step-abort-settlement.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, it } from 'bun:test' + +import { defineAction } from '../src/action.js' +import { Client } from '../src/client.js' + +import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' + +// An aborted step's own status write must happen before its job's terminal write: +// 1. a job that fails waits for its running steps to settle (StepManager.drain); +// 2. a parent step that times out waits for its children before it settles itself. +// Otherwise a slow step write loses the race, returns false (job no longer active) and the +// step is archived as 'active' under a finished job. Fault-injected: the step's failure +// write is held for a while, as on a slow database. + +const TEST_MS = 30_000 + +// A long step body that ends when the step is aborted (so stop does not wait for it). +function sleepUntilAborted(signal: AbortSignal, ms: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(resolve, ms) + signal.addEventListener('abort', () => { + clearTimeout(timer) + resolve() + }) + }) +} + +type Trace = { + ids: Map + created: Map> + events: string[] +} + +// Pass-through wrappers on public Adapter methods: record step ids by name, and hold the +// failure write of `held` for `holdMs`. +function instrument(adapter: Adapter, held: string, holdMs: number): Trace { + const trace: Trace = { ids: new Map(), created: new Map(), events: [] } + const create = adapter.createOrRecoverJobStep.bind(adapter) + adapter.createOrRecoverJobStep = async (options) => { + const step = await create(options) + if (step) { + trace.ids.set(step.id, options.name) + void created(trace, options.name) + trace.created.get(options.name)!.resolve() + } + return step + } + const fail = adapter.failJobStep.bind(adapter) + adapter.failJobStep = async (options) => { + const name = trace.ids.get(options.stepId) ?? '?' + trace.events.push(`fail-step:${name}:start`) + if (name === held) await Bun.sleep(holdMs) + const result = await fail(options) + trace.events.push(`fail-step:${name}:${result}`) + return result + } + const failJob = adapter.failJob.bind(adapter) + adapter.failJob = async (options) => { + trace.events.push('fail-job') + return failJob(options) + } + return trace +} + +function created(trace: Trace, name: string): Promise { + let entry = trace.created.get(name) + if (!entry) { + entry = Promise.withResolvers() + trace.created.set(name, entry) + } + return entry.promise +} + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`Aborted step settlement with ${factory.name}`, () => { + it( + 'a failing job waits for a running step to write its own failure first', + async () => { + const instance = await factory.create() + const trace = instrument(instance.adapter, 'slow', 300) + const action = defineAction()({ + name: 'job-fails-while-step-runs', + handler: async (ctx) => { + const slow = ctx.step('slow', async ({ signal }) => { + await sleepUntilAborted(signal, 5_000) + }) + slow.catch(() => undefined) + // The step row exists before the handler fails. + await created(trace, 'slow') + throw new Error('handler failure') + }, + }) + const client = new Client({ + database: instance.adapter, + actions: { action }, + syncPattern: false, + recoverJobsOnStart: false, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + const jobId = await client.runAction('action', {}) + await client.fetch() + const job = await client.waitForJob(jobId, { timeout: 10_000 }) + expect(job?.status).toBe('failed') + const steps = (await client.getJobSteps({ jobId })).steps + expect(steps.map((step) => [step.name, step.status])).toEqual([['slow', 'failed']]) + expect(trace.events).toEqual(['fail-step:slow:start', 'fail-step:slow:true', 'fail-job']) + } finally { + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + + it( + 'a parent step that times out waits for its child to write its own failure first', + async () => { + const instance = await factory.create() + const trace = instrument(instance.adapter, 'child', 300) + const action = defineAction()({ + name: 'parent-times-out', + steps: { retry: { limit: 0 } }, + handler: async (ctx) => { + await ctx.step( + 'parent', + async (stepCtx) => { + await stepCtx.step( + 'child', + async ({ signal }) => { + await sleepUntilAborted(signal, 5_000) + }, + { expire: 10_000 }, + ) + }, + { expire: 200 }, + ) + }, + }) + const client = new Client({ + database: instance.adapter, + actions: { action }, + syncPattern: false, + recoverJobsOnStart: false, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + const jobId = await client.runAction('action', {}) + await client.fetch() + const job = await client.waitForJob(jobId, { timeout: 10_000 }) + expect(job?.status).toBe('failed') + const steps = (await client.getJobSteps({ jobId })).steps + expect(Object.fromEntries(steps.map((step) => [step.name, step.status]))).toEqual({ + parent: 'failed', + child: 'failed', + }) + // The child's write finished before the parent wrote, and both before the job. + expect(trace.events).toEqual([ + 'fail-step:child:start', + 'fail-step:child:true', + 'fail-step:parent:start', + 'fail-step:parent:true', + 'fail-job', + ]) + } finally { + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, + TEST_MS, + ) + }) +} diff --git a/packages/duron/test/time-travel.test.ts b/packages/duron/test/time-travel.test.ts index 4128841..396dde4 100644 --- a/packages/duron/test/time-travel.test.ts +++ b/packages/duron/test/time-travel.test.ts @@ -158,25 +158,29 @@ const branchAction = defineAction()({ const executed: string[] = [] // Two root-level parallel steps - await Promise.all([ - ctx.step( - 'branch-a', - async () => { - executed.push('branch-a') - return { result: 'a' } - }, - { parallel: true }, - ), - ctx.step( - 'branch-b', - async () => { - if (ctx.input['failAtStep'] === 'branch-b') throw new Error('branch-b failed') - executed.push('branch-b') - return { result: 'b' } - }, - { parallel: true }, - ), - ]) + const branchA = ctx.step( + 'branch-a', + async () => { + executed.push('branch-a') + return { result: 'a' } + }, + { parallel: true }, + ) + const branchB = ctx.step( + 'branch-b', + async () => { + if (ctx.input['failAtStep'] === 'branch-b') { + // Fail only once branch-a has completed: the failure aborts every running sibling, + // so without this the completed sibling the tests rely on depends on timing. + await branchA + throw new Error('branch-b failed') + } + executed.push('branch-b') + return { result: 'b' } + }, + { parallel: true }, + ) + await Promise.all([branchA, branchB]) await ctx.step('final-step', async () => { if (ctx.input['failAtStep'] === 'final-step') throw new Error('final-step failed') diff --git a/packages/duron/test/wait-lifecycle.test.ts b/packages/duron/test/wait-lifecycle.test.ts index 24a1f44..6578c96 100644 --- a/packages/duron/test/wait-lifecycle.test.ts +++ b/packages/duron/test/wait-lifecycle.test.ts @@ -36,7 +36,7 @@ for (const factory of [ await client.stop().catch(() => undefined) await instance.deleteDb() } - }) + }, 20_000) for (const waitReadTimeout of [40, 15_000]) { it(`retains the shared five-second drain with a ${waitReadTimeout}ms read budget`, async () => { diff --git a/packages/duron/test/wait-read-errors.test.ts b/packages/duron/test/wait-read-errors.test.ts index 3916fb8..24eb808 100644 --- a/packages/duron/test/wait-read-errors.test.ts +++ b/packages/duron/test/wait-read-errors.test.ts @@ -58,7 +58,7 @@ for (const factory of [ await client.stop().catch(() => undefined) await instance.deleteDb() } - }) + }, 20_000) } }) } @@ -92,5 +92,5 @@ describe('runActionAndWait while the Client stops', () => { await client.stop().catch(() => undefined) await instance.deleteDb() } - }) + }, 20_000) }) From e9c11cc22784c7d56c7506907b68534d8f9061fd Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 09:28:43 -0300 Subject: [PATCH 074/100] chore(test): pass --timeout 10000 explicitly to bun test (bunfig timeout is ignored) Bun ignores [test] timeout in bunfig.toml (oven-sh/bun#7789). The duron test script and both CI bun test steps now pass --timeout 10000; the bunfig comment and AGENTS.md say so. A 6 s probe test fails without the flag (5000 ms) and passes with it and via 'bun run test'. --- .github/workflows/test.yml | 4 ++-- AGENTS.md | 13 +++++++------ bunfig.toml | 5 +++-- packages/duron/package.json | 2 +- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2654ad0..a2dbd0b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -31,7 +31,7 @@ jobs: - name: Build run: bun run build - name: Run tests - run: bun test + run: bun test --timeout 10000 # The native PostgreSQL suite (POSTGRES_TEST=true) on every supported server major. # test/docker.ts provisions the server itself: it runs DURON_TEST_POSTGRES_IMAGE as the @@ -61,7 +61,7 @@ jobs: run: docker pull "$DURON_TEST_POSTGRES_IMAGE" # Includes the PostgreSQL path of client.test.ts, which runs only with POSTGRES_TEST. - name: Run native tests - run: bun test + run: bun test --timeout 10000 - name: PostgreSQL container logs if: failure() run: docker logs "duron-postgres-test-${DURON_TEST_POSTGRES_IMAGE//[^a-zA-Z0-9_.-]/-}" 2>&1 | tail -200 diff --git a/AGENTS.md b/AGENTS.md index 4ddc787..feef5d0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ bun run lint # oxlint check bun run lint:fix # oxlint fix bun run fmt:check # oxfmt check bun run fmt # oxfmt fix -bun test # runs packages/duron tests (same as `bun run test`) +bun test --timeout 10000 # runs packages/duron tests (same as `bun run test`) # Build bun run build # all packages @@ -60,8 +60,9 @@ bun run build:docs # docs only - Framework: `bun:test` - Tests live in `packages/duron/test/*.test.ts` -- Run single file: `bun test specific.test.ts` -- Core tests run with plain `bun test` (no `--concurrent`: many suites share native resources and time-sensitive lifecycle budgets, and fail under cross-file concurrency) +- Run single file: `bun test --timeout 10000 specific.test.ts` +- Default per-test timeout: pass `--timeout 10000` (the `test` script and CI do). Bun ignores a `timeout` key in `bunfig.toml` (oven-sh/bun#7789), so a plain `bun test` uses 5000 ms. +- Core tests run with `bun test --timeout 10000` (no `--concurrent`: many suites share native resources and time-sensitive lifecycle budgets, and fail under cross-file concurrency) - `test/docker.ts` auto-creates a Docker container on port 5440 for PostgreSQL tests. Docker must be running. - Image: `DURON_TEST_POSTGRES_IMAGE` (default `postgres:19-alpine`). The suite is also verified on `postgres:16-alpine`. - Container: `duron-postgres-test-` (for example `duron-postgres-test-postgres-19-alpine`), so a changed image never reuses a container of another version. `DURON_TEST_POSTGRES_CONTAINER` overrides the name; an existing container must run the selected image. @@ -109,8 +110,8 @@ bun run build:docs # docs only Workflow `.github/workflows/test.yml` (Bun pinned with `BUN_VERSION`, currently 1.4.5) has two jobs: -- `test`: `bun install --frozen-lockfile` → `typecheck` → `lint` → `fmt:check` → `build` → `bun test` (mostly PGlite; a few suites also run PostgreSQL through `test/docker.ts` without `POSTGRES_TEST`). -- `native`: matrix over `postgres:16-alpine` and `postgres:19-alpine` (`DURON_TEST_POSTGRES_IMAGE`), `POSTGRES_TEST=true bun test`. `test/docker.ts` starts the container on the runner's Docker. +- `test`: `bun install --frozen-lockfile` → `typecheck` → `lint` → `fmt:check` → `build` → `bun test --timeout 10000` (mostly PGlite; a few suites also run PostgreSQL through `test/docker.ts` without `POSTGRES_TEST`). +- `native`: matrix over `postgres:16-alpine` and `postgres:19-alpine` (`DURON_TEST_POSTGRES_IMAGE`), `POSTGRES_TEST=true bun test --timeout 10000`. `test/docker.ts` starts the container on the runner's Docker. ## Branch Workflow @@ -121,7 +122,7 @@ Workflow `.github/workflows/test.yml` (Bun pinned with `BUN_VERSION`, currently ```bash bun run typecheck # TypeScript check across all packages bun run lint # Lint check - bun test # Full test suite (not just packages/duron) + bun test --timeout 10000 # Full test suite (not just packages/duron) ``` ## Telemetry diff --git a/bunfig.toml b/bunfig.toml index 2c48ba6..994fdcc 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -1,4 +1,5 @@ [install] linker = "isolated" -# Bun ignores a `[test] timeout` key here (oven-sh/bun#7789): the default per-test timeout -# stays 5000 ms, so tests that can take longer (PGlite start-up on a slow CPU) set their own. +# Bun ignores a `[test] timeout` key here (oven-sh/bun#7789), so the default per-test timeout +# would stay 5000 ms. The `test` script and CI pass `--timeout 10000` instead; a plain +# `bun test` keeps 5000 ms. Tests that can take longer still set their own timeout. diff --git a/packages/duron/package.json b/packages/duron/package.json index 73e80c1..c3c06b3 100644 --- a/packages/duron/package.json +++ b/packages/duron/package.json @@ -76,7 +76,7 @@ "build": "rm -rf dist && tsc --project tsconfig.node.json", "dev": "tsc --watch --project tsconfig.node.json", "prepublishOnly": "bun run build", - "test": "bun test", + "test": "bun test --timeout 10000", "generate:postgres": "bunx --bun drizzle-kit generate --config ./drizzle.config.ts", "typecheck": "bun check --no-script" }, From d4ffb80295e909369e061f0caf8410c8f01525df Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 10:09:14 -0300 Subject: [PATCH 075/100] fix: an aborted parent step waits only for started children (G5 review) R1/A2: with a low steps.concurrency a parent holds the slot its queued child needs, so waiting for every child deadlocked: the job stayed active and stop() failed after its drain budget. The parent now waits only for children whose queue worker started (TaskStep.onStart, called by the fastq worker); a child that starts after the abort throws before creating its row. Applied to the timeout/abort, callback-error and unhandled-children paths, each with a concurrency-1 regression test (job fails, no child row, stop() < 2 s). A1: the settlement test's parent expire is 2 s, so the child's row exists first. A3: remove ActionManager.drain(), which had no callers. --- packages/duron/src/action-manager.ts | 10 --- packages/duron/src/step-manager.ts | 35 ++++++++--- .../duron/test/step-abort-settlement.test.ts | 62 ++++++++++++++++++- 3 files changed, 86 insertions(+), 21 deletions(-) diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index 6b6f732..b8ee034 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -142,16 +142,6 @@ export class ActionManager> { return this.#queue.idle() } - /** - * Wait for the queue to drain (all jobs completed). - * - * @returns Promise that resolves when the queue is drained - */ - async drain(): Promise { - // fastq's `drain` is the hook called when the queue empties; `drained()` waits for it. - return this.#queue.drained() - } - /** * Stop the action manager. * Aborts all active jobs and waits for the queue to drain. diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index b89d494..45389b3 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -205,6 +205,8 @@ export interface TaskStep { abortSignal: AbortSignal parentStepId: string | null parallel: boolean + /** Called when the queue's worker starts this task (it may wait for a free slot first). */ + onStart?: () => void } /** @@ -355,6 +357,7 @@ export class StepManager { this.#stepStore = new StepStore(options.adapter) this.#lifecycle = lifecycleFor(options.adapter) this.#queue = fastq.promise(async (task: TaskStep) => { + task.onStart?.() // Create composite key: name + parentStepId (allows same name under different parents) const stepKey = `${task.parentStepId ?? 'root'}:${task.name}` if (this.#historySteps.has(stepKey)) { @@ -614,8 +617,15 @@ export class StepManager { interface TrackedChildStep { promise: Promise settled: boolean + /** Its queue worker started. A child still queued is never waited for: it starts + * only after this parent frees a slot, sees the abort and creates no row. */ + started: boolean } const childSteps: TrackedChildStep[] = [] + // Children whose queue worker started. Waiting for a still-queued child could + // deadlock: this parent may hold the slot that child needs (low steps.concurrency). + const startedChildren = (children: TrackedChildStep[]) => + children.filter((child) => child.started).map((child) => child.promise) // Create abort controller for child steps (used when parent returns with pending children) const childAbortController = new AbortController() @@ -642,6 +652,11 @@ export class StepManager { ...childOptions, }) + const trackedChild: TrackedChildStep = { + promise: Promise.resolve(), + settled: false, + started: false, + } // Push child step with this step as parent const childPromise = this.push({ name: childName, @@ -650,13 +665,13 @@ export class StepManager { abortSignal: childSignal, // Child uses composed signal parentStepId: step!.id, // This step is the parent parallel: parsedChildOptions.parallel, // Pass parallel option + onStart: () => { + trackedChild.started = true + }, }) // Track the child promise - const trackedChild: TrackedChildStep = { - promise: childPromise, - settled: false, - } + trackedChild.promise = childPromise childSteps.push(trackedChild) // Mark as settled when done (success or failure) @@ -737,17 +752,17 @@ export class StepManager { if (childSteps.length > 0) { // Abort all children with the callback error as reason childAbortController.abort(callbackError) - // Wait for all children to settle - await Promise.allSettled(childSteps.map((c) => c.promise)) + // Wait for the started children to settle + await Promise.allSettled(startedChildren(childSteps)) } throw callbackError } // If aborted, wait for child steps to settle before propagating if (aborted) { - // Wait for all child steps to settle (they'll be aborted via signal propagation) + // Wait for the started child steps to settle (aborted via signal propagation) if (childSteps.length > 0) { - await Promise.allSettled(childSteps.map((c) => c.promise)) + await Promise.allSettled(startedChildren(childSteps)) } // Re-throw the abort reason throw stepSignal.reason @@ -776,8 +791,8 @@ export class StepManager { }) childAbortController.abort(unhandledError) - // Wait for all children to settle (they'll reject with cancellation) - await Promise.allSettled(unsettledChildren.map((c) => c.promise)) + // Wait for the started children to settle (they'll reject with cancellation) + await Promise.allSettled(startedChildren(unsettledChildren)) // Now throw the error throw unhandledError diff --git a/packages/duron/test/step-abort-settlement.test.ts b/packages/duron/test/step-abort-settlement.test.ts index 7d164c6..6ead514 100644 --- a/packages/duron/test/step-abort-settlement.test.ts +++ b/packages/duron/test/step-abort-settlement.test.ts @@ -137,7 +137,8 @@ for (const factory of [ { expire: 10_000 }, ) }, - { expire: 200 }, + // Long enough for the child's row to exist first, even on a slow machine. + { expire: 2_000 }, ) }, }) @@ -174,5 +175,64 @@ for (const factory of [ }, TEST_MS, ) + + // With steps.concurrency 1 a parent holds the only slot, so its child stays queued. An + // aborted or failing parent must not wait for a child that never started: that child + // starts after the parent settles, sees the abort and writes no row. + for (const path of ['times out', 'throws', 'returns without awaiting it'] as const) { + it( + `a parent that ${path} does not wait for a child still queued behind it`, + async () => { + const instance = await factory.create() + const action = defineAction()({ + name: `queued-child-${path.replaceAll(' ', '-')}`, + steps: { concurrency: 1, retry: { limit: 0 } }, + handler: async (ctx) => { + await ctx.step( + 'parent', + async (stepCtx) => { + const child = stepCtx.step('child', async () => ({})) + if (path === 'times out') return child + child.catch(() => undefined) + if (path === 'throws') throw new Error('parent failure') + return {} + }, + { expire: 300 }, + ) + }, + }) + const client = new Client({ + database: instance.adapter, + actions: { action }, + syncPattern: false, + recoverJobsOnStart: false, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + const jobId = await client.runAction('action', {}) + await client.fetch() + const job = await client.waitForJob(jobId, { timeout: 5_000 }) + expect(job?.status).toBe('failed') + expect((job?.error as { name?: string } | null)?.name).toBe( + path === 'times out' + ? 'StepTimeoutError' + : path === 'throws' + ? 'NonRetriableError' + : 'UnhandledChildStepsError', + ) + // The queued child never started, so it has no row. + const steps = (await client.getJobSteps({ jobId })).steps + expect(steps.map((step) => [step.name, step.status])).toEqual([['parent', 'failed']]) + } finally { + const begun = performance.now() + expect(await client.stop()).toBe(true) + expect(performance.now() - begun).toBeLessThan(2_000) + await instance.deleteDb() + } + }, + TEST_MS, + ) + } }) } From 317429adc3756502467d953db058c80d96dfa10e Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 12:11:42 -0300 Subject: [PATCH 076/100] fix: prune-lock replacement edge cases (G4 recheck N1-N4) - N1: a replacement lock's bootstrap failure is classified. Connection and server startup faults retry with backoff as warnings; other faults (28P01, configuration) retry with backoff but log an error on every attempt; malformed or changed backend identity retires as on the first lock. Replacement faults are no longer reported as "session lost". - N2: when the bootstrap session closes while reserve() is pending, the replacement is retried as a connection fault. The new reservation is given back to the ending client so the fault close confirms it closed promptly. - N3: the established-session loss set drops CONNECTION_DESTROYED, CONNECTION_ENDED (own end()) and 57P03; adds ETIMEDOUT and 57P05. - N4: the backoff counts from the failure, and the tick nearest the due time retries, so an early tick does not add an interval. - Hooks: _pruneLockReplacement() replaces _canReplacePruneLock() and _pruneLockBootstrapFailed(); the tick is _pruneTick() with an injectable clock for tests. --- packages/docs/content/docs/adapters.mdx | 8 +- packages/duron/src/adapters/postgres/base.ts | 254 ++++++----- .../duron/src/adapters/postgres/postgres.ts | 13 +- .../duron/src/adapters/postgres/prune-lock.ts | 134 +++++- packages/duron/test/prune-backoff.test.ts | 59 +++ packages/duron/test/prune-reestablish.test.ts | 428 +++++++++++++----- 6 files changed, 652 insertions(+), 244 deletions(-) create mode 100644 packages/duron/test/prune-backoff.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index b06ff49..ee0f097 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -90,7 +90,13 @@ An opted-in adapter owns one additional, max-one postgres.js client for coordina Key `42` coordinates **across schemas in the same database**, not just one Duron schema. Separate databases do not contend. Avoid using this advisory key for unrelated application locks. DELETEs still run on the adapter's original query pool, including when that pool has `max: 1`. Custom `_pruneArchive` overrides remain in the dispatch path and can delegate to `super._pruneArchive`. -Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, `idle_session_timeout`, a pooler or load-balancer idle timeout, `pg_terminate_backend`), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so key `42` keeps a single owner. Such a loss is logged as a warning, not an error. If that replacement client cannot start (the server is still unreachable), later ticks try again after a backoff that doubles from the interval up to five minutes; the replacement never held the lock, so a new attempt keeps a single owner. A bootstrap failure of the first client, an uncertain or malformed coordination result, a false or rejected unlock, or a failed close keeps scheduling retired until the adapter restarts. Each replaced client is closed and released, so repeated losses do not accumulate clients. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. +Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, `idle_session_timeout`, a pooler or load-balancer idle timeout, `pg_terminate_backend`), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so key `42` keeps a single owner. Such a loss is logged as a warning, not an error. If that replacement client cannot start, later ticks try again after a backoff that doubles from the interval up to five minutes. The backoff counts from the failure, and the tick nearest to the due time retries, so a tick that fires slightly early does not add an interval. The replacement never requested the lock, and a new attempt starts only after its close is confirmed, so key `42` keeps a single owner. The fault decides the log level: + +- A connection or server startup fault (connection refused, reset or closed, a connect timeout, SQLSTATE class `08`, `57P01`, `57P02`, `57P03` or `57P05`, also a session that closes between the bootstrap and the reservation) is logged as a warning, as during a failover. +- Another fault, such as rejected credentials (`28P01`) or a configuration error, is logged as an error on every attempt. The attempts continue, because the credentials can be restored. +- A bootstrap result that does not prove the backend identity (malformed, or a reservation on another backend) retires scheduling, as on the first client. + +A bootstrap failure of the first client, an uncertain or malformed coordination result, a false or rejected unlock, or a failed close keeps scheduling retired until the adapter restarts. Each replaced client is closed and released, so repeated losses do not accumulate clients. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. ### Manual pruning and failure limits diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index dbbc5e2..9674fe7 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -114,6 +114,16 @@ export interface PruneSchedulerConfig { maxBatches?: number } +/** + * How a retired isolated prune lock may be replaced: + * - `none`: scheduling stays retired until the adapter restarts; + * - `lost`: its established session was lost; the next tick replaces it; + * - `unreachable`: a replacement lock could not connect; a later tick retries after a backoff; + * - `failed`: a replacement lock failed with another fault that is not a single-owner risk + * (rejected credentials, configuration); a later tick retries after a backoff. + */ +export type PruneLockReplacement = 'none' | 'lost' | 'unreachable' | 'failed' + export interface AdapterOptions { connection: Connection schema?: string @@ -143,6 +153,10 @@ export abstract class PostgresBaseAdapter< /** Consecutive replacement locks that failed to start, and the next attempt time. */ private pruneReplaceFailures = 0 private pruneReplaceAt = 0 + /** When the current retirement started: a replacement backoff counts from the failure. */ + private pruneRetiredAt = 0 + /** Monotonic clock of the prune scheduler. */ + private pruneClock = () => performance.now() private readonly scheduledPrune = new AsyncLocalStorage() private pruneConfig: PruneSchedulerConfig | null = null private lastPrunedAt: Date | null = null @@ -463,6 +477,7 @@ export abstract class PostgresBaseAdapter< protected _retirePruning(error: unknown): void { this.pruneCoordinationErrors.push(error) + if (!this.pruneRetired) this.pruneRetiredAt = this.pruneClock() this.pruneRetired = true // The timer keeps ticking: a later tick re-establishes coordination once the isolated // lock client is confirmed closed (see `_reestablishPruning`), or reports the retired state. @@ -483,13 +498,7 @@ export abstract class PostgresBaseAdapter< }) .then( () => { - // A lost established session is benign and self-healing (idle timeouts): warn. - if (this._canReplacePruneLock()) { - this.logger?.warn( - { err: error }, - 'Scheduled prune coordination session lost; a later tick re-establishes it', - ) - } else { + if (!this._logReplaceableRetirement(error)) { this.logger?.error(error, 'Scheduled prune coordination retired') } }, @@ -502,6 +511,35 @@ export abstract class PostgresBaseAdapter< // PGLite has no isolated resource: its engine stays available until normal stop. } + /** + * Logs a retirement whose lock a later tick replaces, and returns true. Returns false for a + * retirement that is final. A lost established session and a replacement that could not + * connect are benign and self-healing (idle timeouts, failovers): warn. A replacement that + * failed with another fault (rejected credentials) is retried too, but each attempt is an + * error. + */ + private _logReplaceableRetirement(err: unknown): boolean { + switch (this._pruneLockReplacement()) { + case 'lost': + this.logger?.warn( + { err }, + 'Scheduled prune coordination session lost; a later tick re-establishes it', + ) + return true + case 'unreachable': + this.logger?.warn( + { err }, + 'Scheduled prune replacement lock could not connect; a later tick retries it', + ) + return true + case 'failed': + this.logger?.error(err, 'Scheduled prune replacement lock failed; a later tick retries it') + return true + case 'none': + return false + } + } + /** The retirement's isolated close; records its success for re-establishment. */ private _observePruneLockClose(): Promise { return this._closePruneLock().then(() => { @@ -511,18 +549,15 @@ export abstract class PostgresBaseAdapter< /** * Whether coordination can start again with a new isolated lock after a retirement whose - * lock client closed successfully. Only the loss of an established isolated lock session - * qualifies: the server released that session's advisory lock when it ended. Bootstrap - * failures and uncertain or malformed coordination results keep the scheduler retired, and - * so does PGLite, which coordinates on its shared engine. + * lock client closed successfully (see `PruneLockReplacement`). The loss of an established + * isolated lock session qualifies: the server released that session's advisory lock when it + * ended. A replacement lock that failed its bootstrap never requested the lock: it is + * retried after a backoff, except when its backend identity was not proven. A bootstrap + * failure of the first lock and uncertain or malformed coordination results keep the + * scheduler retired, and so does PGLite, which coordinates on its shared engine. */ - protected _canReplacePruneLock(): boolean { - return false - } - - /** Whether the retired lock is a replacement that failed its bootstrap. */ - protected _pruneLockBootstrapFailed(): boolean { - return false + protected _pruneLockReplacement(): PruneLockReplacement { + return 'none' } /** Drop the closed isolated lock so the next acquisition builds a new one. */ @@ -533,24 +568,28 @@ export abstract class PostgresBaseAdapter< * old lock client is confirmed closed; otherwise reports that the tick is skipped. */ private _reestablishPruning(interval: number): boolean { - if (this.pruneFaultClosed && this._canReplacePruneLock()) { - if (this._pruneLockBootstrapFailed()) { - // A replacement could not start (server unreachable): retry with a bounded backoff - // of the interval doubled per consecutive failure, at most five minutes. - const now = performance.now() + const replacement = this.pruneFaultClosed ? this._pruneLockReplacement() : 'none' + if (replacement !== 'none') { + if (replacement !== 'lost') { + // A replacement could not start: retry with a bounded backoff of the interval doubled + // per consecutive failure, at most five minutes, counted from the failure. + const now = this.pruneClock() if (this.pruneReplaceAt === 0) { this.pruneReplaceFailures++ const delay = Math.max( interval, Math.min(interval * 2 ** (this.pruneReplaceFailures - 1), 300_000), ) - this.pruneReplaceAt = now + delay - this.logger?.warn( - { failures: this.pruneReplaceFailures, delay }, - 'Scheduled prune replacement lock failed to start; retrying after a backoff', - ) + this.pruneReplaceAt = this.pruneRetiredAt + delay + const details = { failures: this.pruneReplaceFailures, delay } + const message = + 'Scheduled prune replacement lock failed to start; retrying after a backoff' + if (replacement === 'failed') this.logger?.error(details, message) + else this.logger?.warn(details, message) } - if (now < this.pruneReplaceAt) return false + // Ticks are one interval apart and can fire slightly early. The tick nearest to the due + // time retries: waiting for the tick after it would add a whole interval. + if (now + interval / 2 < this.pruneReplaceAt) return false } this.pruneReplaceAt = 0 this._resetPruneLock() @@ -574,93 +613,92 @@ export abstract class PostgresBaseAdapter< const lifecycle = lifecycleFor(this) if (!config || !lifecycle.accepting) return - const run = () => { - if (!lifecycle.accepting || this.pruneRunning) return Promise.resolve() - if (this.pruneRetired && !this._reestablishPruning(config.intervalMs)) { - return Promise.resolve() - } - this.pruneRunning = true - const coordinationStart = this.pruneCoordinationErrors.length - return lifecycle - .run(async () => { - const pruneErrors: unknown[] = [] - let acquired = false + // Run immediately on start, then on interval + this._pruneTick(config).catch((err) => this.logger?.error(err, 'Initial prune run failed')) + this.pruneTimer = setInterval(() => this._pruneTick(config), config.intervalMs) + } + + /** One scheduler tick: re-establish a retired coordination if possible, then run a pass. */ + private _pruneTick(config: PruneSchedulerConfig): Promise { + const lifecycle = lifecycleFor(this) + if (!lifecycle.accepting || this.pruneRunning) return Promise.resolve() + if (this.pruneRetired && !this._reestablishPruning(config.intervalMs)) { + return Promise.resolve() + } + this.pruneRunning = true + const coordinationStart = this.pruneCoordinationErrors.length + return lifecycle + .run(async () => { + const pruneErrors: unknown[] = [] + let acquired = false + try { + acquired = await this._acquirePruneLock() + // The lock session works again: a later failed replacement starts a new backoff. + this.pruneReplaceFailures = 0 + } catch (error) { + this._retirePruning(error) + } + if (acquired) { try { - acquired = await this._acquirePruneLock() - // The lock session works again: a later failed replacement starts a new backoff. - this.pruneReplaceFailures = 0 - } catch (error) { - this._retirePruning(error) - } - if (acquired) { - try { - // A late acquisition must not start a hook after stop or loss. - if (lifecycle.accepting && !this.pruneRetired) { - const deleted = await this.scheduledPrune.run(true, () => - this._pruneArchive({ - olderThan: config.olderThan, - batchSize: config.batchSize, - maxBatches: config.maxBatches, - }), - ) - this.lastPrunedAt = new Date() - this.logger?.info({ deletedJobs: deleted }, 'Archive prune completed') - } - } catch (error) { - pruneErrors.push(error) - } finally { - try { - await this._releasePruneLock() - } catch (error) { - this._retirePruning(error) - } + // A late acquisition must not start a hook after stop or loss. + if (lifecycle.accepting && !this.pruneRetired) { + const deleted = await this.scheduledPrune.run(true, () => + this._pruneArchive({ + olderThan: config.olderThan, + batchSize: config.batchSize, + maxBatches: config.maxBatches, + }), + ) + this.lastPrunedAt = new Date() + this.logger?.info({ deletedJobs: deleted }, 'Archive prune completed') } - } - const closeErrors: unknown[] = [] - // Observe a started fault close even if stop has since quiesced the - // adapter. Positive resource release does not erase its earlier error. - if (this.pruneFaultClose || (this.pruneRetired && lifecycle.accepting)) { + } catch (error) { + pruneErrors.push(error) + } finally { try { - await (this.pruneFaultClose ??= this._observePruneLockClose()) + await this._releasePruneLock() } catch (error) { - closeErrors.push(error) + this._retirePruning(error) } } - const coordinationErrors = this.pruneCoordinationErrors.slice(coordinationStart) - // Only a lost established lock session (benign and self-healing): warn. - if ( - !pruneErrors.length && - !closeErrors.length && - coordinationErrors.length && - this.pruneRetired && - this._canReplacePruneLock() - ) { - const err = - coordinationErrors.length === 1 - ? coordinationErrors[0] - : new AggregateError(coordinationErrors, 'Scheduled prune coordination lost') - this.logger?.warn( - { err }, - 'Scheduled prune coordination session lost; a later tick re-establishes it', - ) - return + } + const closeErrors: unknown[] = [] + // Observe a started fault close even if stop has since quiesced the + // adapter. Positive resource release does not erase its earlier error. + if (this.pruneFaultClose || (this.pruneRetired && lifecycle.accepting)) { + try { + await (this.pruneFaultClose ??= this._observePruneLockClose()) + } catch (error) { + closeErrors.push(error) } - throwLifecycleErrors( - [...pruneErrors, ...coordinationErrors, ...closeErrors], - 'Scheduled prune failed: prune first, then coordination/release/close failures', + } + const coordinationErrors = this.pruneCoordinationErrors.slice(coordinationStart) + // Only a retirement whose lock a later tick replaces is logged here; see + // `_logReplaceableRetirement` for its level. + if ( + !pruneErrors.length && + !closeErrors.length && + coordinationErrors.length && + this.pruneRetired && + this._logReplaceableRetirement( + coordinationErrors.length === 1 + ? coordinationErrors[0] + : new AggregateError(coordinationErrors, 'Scheduled prune coordination failed'), ) - }) - .catch((error) => this.logger?.error(error, 'Error in prune scheduler')) - .finally(() => { - // This pass reported its coordination errors; do not retain them. - this.pruneCoordinationErrors.splice(coordinationStart) - this.pruneRunning = false - }) - } - - // Run immediately on start, then on interval - run().catch((err) => this.logger?.error(err, 'Initial prune run failed')) - this.pruneTimer = setInterval(run, config.intervalMs) + ) { + return + } + throwLifecycleErrors( + [...pruneErrors, ...coordinationErrors, ...closeErrors], + 'Scheduled prune failed: prune first, then coordination/release/close failures', + ) + }) + .catch((error) => this.logger?.error(error, 'Error in prune scheduler')) + .finally(() => { + // This pass reported its coordination errors; do not retain them. + this.pruneCoordinationErrors.splice(coordinationStart) + this.pruneRunning = false + }) } /** diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index 5ce3817..ed3216b 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -9,7 +9,7 @@ import type { Options as PostgresOptions } from 'postgres' import { lifecycleFor } from '../../lifecycle.js' import type { WaitReadBudget } from '../../wait-read.js' -import { type AdapterOptions, PostgresBaseAdapter } from './base.js' +import { type AdapterOptions, PostgresBaseAdapter, type PruneLockReplacement } from './base.js' import { PostgresPruneLock } from './prune-lock.js' import type createSchema from './schema.js' @@ -94,15 +94,8 @@ export class PostgresAdapter extends PostgresBaseAdapter | string, @@ -99,17 +156,24 @@ export class PostgresPruneLock { this.#closed = this.#observeNativeClose() } if (rows.length !== 1 || typeof rows[0]?.pid !== 'number') { - throw new Error('Malformed scheduled prune bootstrap identity') + throw new SingleOwnerFault('Malformed scheduled prune bootstrap identity') } this.#pid = rows[0].pid // No await between bootstrap success and reserve: the exclusive client's // ready connection must not become a new connection-establishment attempt. if (!this.lifecycle.accepting || this.#uncertain || this.#closing) return false this.#session = await this.client.reserve() + if (this.#uncertain && this.lifecycle.accepting) { + // The bootstrap session closed while reserve() was pending: its onclose retired this + // lock, whose fault close has started. A connection loss before the lock was requested. + this.#bootstrapFault = 'startup' + this.#abandonLostBootstrapReservation() + return false + } if (!this.lifecycle.accepting || this.#uncertain || this.#closing) return false const identity = await this.#session<{ pid: number }[]>`SELECT pg_backend_pid() AS pid` if (identity.length !== 1 || identity[0]?.pid !== this.#pid) { - throw new Error('Scheduled prune reservation changed backend identity') + throw new SingleOwnerFault('Scheduled prune reservation changed backend identity') } this.#established = true return true @@ -117,13 +181,47 @@ export class PostgresPruneLock { // A failed transition cannot establish safe reservation ownership, even // when the transport is still alive and its observed PID is malformed. this.#uncertain = true - if (!this.#established) this.#bootstrapFailed = true + if (!this.#established) { + this.#bootstrapFault ??= + error instanceof SingleOwnerFault + ? 'single-owner' + : isStartupFault(error) + ? 'startup' + : 'fault' + } throw error } finally { this.#bootstrapPending = false } } + /** + * The bootstrap session closed while reserve() was pending. postgres.js then opened a new + * connection for the pending reservation (or granted the closing one). That reservation never + * ran a statement and never requested key 42, and this lock never uses its client again + * (`#uncertain` is set and the setup is not repeated). Give the connection back so that the + * fault close's `end()` closes it at once: a reserved connection would stay open until the + * end timeout destroys it, and the close would fail its five-second budget. The client is + * ending, so postgres.js does not lease the connection again. The bootstrap close + * observation does not cover a new connection: when one is open, the close waits for native + * evidence that it closed. + */ + #abandonLostBootstrapReservation(): void { + const session = this.#session + if (!session) return + this.#session = undefined + const stats = (this.client as { stats?: { connections: number } }).stats + if (this.#physicallyClosed && stats !== undefined && stats.connections > 0) { + this.#physicallyClosed = false + this.#closed = this.#observeNativeClose() + } + try { + session.release() + } catch { + // The connection is closed already; the client's end() remains the cleanup. + } + } + /** An established session whose statement failed because the connection was lost. */ #noteLoss(statement: Promise): Promise { return statement.catch((error: unknown) => { @@ -174,12 +272,22 @@ export class PostgresPruneLock { } /** - * True when this replacement lock failed its bootstrap (the server was not reachable yet, - * for example during a failover). It never held key 42, so once its close is confirmed a - * later tick may try another replacement. + * How this lock may be replaced after its retirement, once its close is confirmed (see + * `PruneLockReplacement`): + * - `lost`: its established session was lost; + * - `unreachable`: this replacement lock failed its bootstrap with a connection or server + * startup fault (for example during a failover); + * - `failed`: this replacement lock failed its bootstrap with another fault (rejected + * credentials, configuration). + * A failed replacement never requested key 42, so another attempt keeps a single owner. + * A bootstrap failure of the first lock, and a bootstrap result that does not prove the + * backend identity, give `none`. */ - get replacementBootstrapFailed(): boolean { - return this.replacement && this.#bootstrapFailed + get replacementKind(): 'none' | 'lost' | 'unreachable' | 'failed' { + if (this.#lostAfterEstablished) return 'lost' + if (!this.replacement || this.#bootstrapFault === undefined) return 'none' + if (this.#bootstrapFault === 'single-owner') return 'none' + return this.#bootstrapFault === 'startup' ? 'unreachable' : 'failed' } /** diff --git a/packages/duron/test/prune-backoff.test.ts b/packages/duron/test/prune-backoff.test.ts new file mode 100644 index 0000000..f305532 --- /dev/null +++ b/packages/duron/test/prune-backoff.test.ts @@ -0,0 +1,59 @@ +import { expect, it } from 'bun:test' + +import pino from 'pino' + +import type { PruneLockReplacement } from '../src/adapters/postgres/base.js' +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' + +// The backoff of a failed replacement lock is computed from the failure time, and a tick that +// fires slightly before the due time retries: timers drift, and waiting for the following tick +// would add a whole interval to each delay. Ticks and the clock are driven by the test. + +const interval = 60_000 + +it('retries a failed replacement on the tick nearest to its backoff, also when the tick is early', async () => { + let now = 0 + const attempts: number[] = [] + class FailingReplacement extends PGLiteAdapter { + protected override async _acquirePruneLock(): Promise { + attempts.push(now) + // The attempt fails a few milliseconds after its tick. + now += 5 + throw Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }) + } + protected override _pruneLockReplacement(): PruneLockReplacement { + return 'unreachable' + } + } + const adapter = new FailingReplacement({ + connection: ':memory:', + // The real timer does not fire during the test: the test calls each tick. + pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: interval }, + }) + adapter.setId('prune-backoff') + adapter.setLogger(pino({ level: 'silent' })) + const internals = adapter as unknown as { + pruneClock: () => number + pruneRunning: boolean + _pruneTick: (config: { olderThan: Date; intervalMs: number }) => Promise + } + internals.pruneClock = () => now + const config = { olderThan: new Date('2099-01-01'), intervalMs: interval } + try { + expect(await adapter.start()).toBe(true) + // The start pass (tick 0) runs on its own. + while (internals.pruneRunning || attempts.length === 0) await Bun.sleep(1) + const ticks: number[] = [] + for (let tick = 1; tick <= 8; tick++) { + // Each tick fires one millisecond early. + now = tick * interval - 1 + const before = attempts.length + await internals._pruneTick(config) + if (attempts.length > before) ticks.push(tick) + } + // Backoffs of 1, 2 and 4 intervals from each failure: ticks 1, 3 and 7. + expect(ticks).toEqual([1, 3, 7]) + } finally { + await adapter.stop() + } +}) diff --git a/packages/duron/test/prune-reestablish.test.ts b/packages/duron/test/prune-reestablish.test.ts index 0689ec7..ec8fb65 100644 --- a/packages/duron/test/prune-reestablish.test.ts +++ b/packages/duron/test/prune-reestablish.test.ts @@ -5,6 +5,7 @@ import postgres from 'postgres' import type { PruneArchiveOptions } from '../src/adapters/adapter.js' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { PostgresPruneLock } from '../src/adapters/postgres/prune-lock.js' import { lifecycleFor } from '../src/lifecycle.js' import { getPostgresConnection } from './docker.js' @@ -13,6 +14,9 @@ import { getPostgresConnection } from './docker.js' // retires the scheduler only until the old session is confirmed closed: a later tick builds // a new lock session and pruning continues. Key 42 keeps one owner: the server released the // old session's lock when it ended, and no pass overlaps the re-establishment. +// A replacement lock that cannot start is retried after a backoff: a connection fault logs a +// warning, another fault (rejected credentials) an error. A single-owner fault (changed or +// malformed backend identity) retires the scheduler as on the first lock. async function eventually(check: () => Promise, timeout = 10_000): Promise { const deadline = performance.now() + timeout @@ -27,57 +31,131 @@ async function eventually(check: () => Promise, timeout = 10_000): Promise } } -if (process.env['POSTGRES_TEST'] === 'true') { - it('re-establishes scheduled pruning on a new lock session after the old one was lost', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection() - let hooks = 0 - class CountingPrune extends PostgresAdapter { - protected override async _pruneArchive(options: PruneArchiveOptions): Promise { - hooks++ - return super._pruneArchive(options) - } - } - const application = `reestablish-${crypto.randomUUID()}` - const url = new URL(CONNECTION_URL) - const adapter = new CountingPrune({ - connection: { - host: url.hostname, - port: Number(url.port), - database: url.pathname.slice(1), - user: url.username, - password: url.password, - connection: { application_name: application }, - }, - pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: 50 }, - }) - adapter.setId(application) - const entries: Array<{ level: string; msg: string }> = [] - const logger = pino({ level: 'silent' }) - for (const level of ['error', 'warn', 'info'] as const) { - logger[level] = ((value: unknown, message?: string) => { - entries.push({ - level, - msg: message ?? (value instanceof Error ? value.message : String(value)), - }) - }) as never +interface Entry { + level: 'error' | 'warn' | 'info' + msg: string + /** Messages and codes of the logged errors, with their nested errors. */ + errors: Array<{ message: string; code?: unknown }> + at: number +} + +function loggedErrors(value: unknown): Entry['errors'] { + const errors: Entry['errors'] = [] + const visit = (error: unknown) => { + if (!(error instanceof Error)) return + errors.push({ message: error.message, code: (error as { code?: unknown }).code }) + if (error instanceof AggregateError) error.errors.forEach(visit) + } + visit(value) + visit((value as { err?: unknown } | null)?.err) + return errors +} + +type Connection = { + host: string + port: number + database: string + user: string + password: string + connection: Record +} + +async function harness( + name: string, + Base: typeof PostgresAdapter = PostgresAdapter, +): Promise<{ + adapter: PostgresAdapter + connection: Connection + url: URL + application: string + entries: Entry[] + hooks: () => number + observer: postgres.Sql + lockSessions: () => Promise> + /** Starts the adapter and returns the pid of its first lock session. */ + start: () => Promise + dispose: () => Promise +}> { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() + let hooks = 0 + class CountingPrune extends Base { + protected override async _pruneArchive(options: PruneArchiveOptions): Promise { + hooks++ + return super._pruneArchive(options) } - adapter.setLogger(logger) - const observer = postgres(CONNECTION_URL, { max: 1 }) - // The lock session is the backend whose last statement used advisory key 42. - const lockSessions = () => observer<{ pid: number }[]>` - SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND application_name = ${application} - AND query LIKE '%advisory%lock(42)%' - ` - try { + } + const application = `${name}-${crypto.randomUUID()}` + const url = new URL(CONNECTION_URL) + const connection: Connection = { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + connection: { application_name: application }, + } + const adapter = new CountingPrune({ + connection, + pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: 50 }, + }) + adapter.setId(application) + const entries: Entry[] = [] + const logger = pino({ level: 'silent' }) + for (const level of ['error', 'warn', 'info'] as const) { + logger[level] = ((value: unknown, message?: string) => { + entries.push({ + level, + msg: message ?? (value instanceof Error ? value.message : String(value)), + errors: loggedErrors(value), + at: performance.now(), + }) + }) as never + } + adapter.setLogger(logger) + const observer = postgres(CONNECTION_URL, { max: 1 }) + // The lock session is the backend whose last statement used advisory key 42. + const lockSessions = () => observer<{ pid: number }[]>` + SELECT pid FROM pg_stat_activity + WHERE datname = current_database() AND application_name = ${application} + AND query LIKE '%advisory%lock(42)%' + ` + return { + adapter, + connection, + url, + application, + entries, + hooks: () => hooks, + observer, + lockSessions, + start: async () => { expect(await adapter.start()).toBe(true) - let lost = 0 + let pid = 0 await eventually(async () => { const sessions = await lockSessions() expect(sessions).toHaveLength(1) - lost = sessions[0]!.pid + pid = sessions[0]!.pid }) await eventually(async () => expect(hooks).toBeGreaterThan(0)) + return pid + }, + dispose: async () => { + await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + }, + } +} + +const retries = (entries: Entry[]) => + entries.filter((entry) => /replacement .* retrying/.test(entry.msg)) + +if (process.env['POSTGRES_TEST'] === 'true') { + it('re-establishes scheduled pruning on a new lock session after the old one was lost', async () => { + const h = await harness('reestablish') + const { adapter, entries, observer, lockSessions } = h + try { + const lost = await h.start() await observer`SELECT pg_terminate_backend(${lost})` // A benign loss of an established session is a warning, not an error. await eventually(async () => @@ -85,13 +163,13 @@ if (process.env['POSTGRES_TEST'] === 'true') { true, ), ) - const hooksAtLoss = hooks + const hooksAtLoss = h.hooks() // A new lock session (another backend) serves later passes. await eventually(async () => { const sessions = await lockSessions() expect(sessions).toHaveLength(1) expect(sessions[0]!.pid).not.toBe(lost) - expect(hooks).toBeGreaterThan(hooksAtLoss) + expect(h.hooks()).toBeGreaterThan(hooksAtLoss) }) expect(entries.some((entry) => /re-established/.test(entry.msg))).toBe(true) @@ -106,13 +184,13 @@ if (process.env['POSTGRES_TEST'] === 'true') { let current = (await lockSessions())[0]!.pid for (let loss = 0; loss < 4; loss++) { replaced.push(internals.pruneLock!.client) - const hooksBefore = hooks + const hooksBefore = h.hooks() await observer`SELECT pg_terminate_backend(${current})` await eventually(async () => { const sessions = await lockSessions() expect(sessions).toHaveLength(1) expect(sessions[0]!.pid).not.toBe(current) - expect(hooks).toBeGreaterThan(hooksBefore) + expect(h.hooks()).toBeGreaterThan(hooksBefore) current = sessions[0]!.pid }) expect(lifecycleFor(adapter).obligationCount).toBe(obligations) @@ -125,87 +203,213 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(entries.filter((entry) => entry.level === 'error')).toEqual([]) expect(await adapter.stop()).toBe(true) } finally { - await adapter.stop().catch(() => undefined) - await observer.end({ timeout: 5 }) - await deleteDb() + await h.dispose() } }, 30_000) - it('retries a replacement lock whose bootstrap fails on later ticks with a growing backoff', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection() - let hooks = 0 - class CountingPrune extends PostgresAdapter { - protected override async _pruneArchive(options: PruneArchiveOptions): Promise { - hooks++ - return super._pruneArchive(options) - } - } - const application = `replacement-retry-${crypto.randomUUID()}` - const url = new URL(CONNECTION_URL) - const connection = { - host: url.hostname, - port: Number(url.port), - database: url.pathname.slice(1), - user: url.username, - password: url.password, - connection: { application_name: application }, - } - const adapter = new CountingPrune({ - connection, - pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: 50 }, - }) - adapter.setId(application) - const entries: Array<{ level: string; msg: string; at: number }> = [] - const logger = pino({ level: 'silent' }) - for (const level of ['error', 'warn', 'info'] as const) { - logger[level] = ((value: unknown, message?: string) => { - entries.push({ - level, - msg: message ?? (value instanceof Error ? value.message : String(value)), - at: performance.now(), - }) - }) as never - } - adapter.setLogger(logger) - const observer = postgres(CONNECTION_URL, { max: 1 }) - const lockSessions = () => observer<{ pid: number }[]>` - SELECT pid FROM pg_stat_activity - WHERE datname = current_database() AND application_name = ${application} - AND query LIKE '%advisory%lock(42)%' - ` + it('retries a replacement lock that cannot connect with a growing backoff, as warnings', async () => { + const h = await harness('replacement-unreachable') + const { adapter, connection, url, entries, observer, lockSessions } = h try { - expect(await adapter.start()).toBe(true) - let lost = 0 - await eventually(async () => { - const sessions = await lockSessions() - expect(sessions).toHaveLength(1) - lost = sessions[0]!.pid - }) - // Replacement lock clients fail to authenticate (as during a failover window). The - // query pool was created at start and keeps its own copy of the options. - connection.password = 'deliberately-invalid-replacement-password' + const lost = await h.start() + // Replacement lock clients cannot connect (as during a failover window). The query pool + // was created at start and keeps its own copy of the options. + const closed = Bun.listen({ hostname: url.hostname, port: 0, socket: { data() {} } }) + const refusedPort = closed.port + closed.stop(true) + connection.port = refusedPort await observer`SELECT pg_terminate_backend(${lost})` - const retries = () => entries.filter((entry) => /replacement .* retrying/.test(entry.msg)) - await eventually(async () => expect(retries().length).toBeGreaterThanOrEqual(3)) + await eventually(async () => expect(retries(entries).length).toBeGreaterThanOrEqual(3)) // The backoff grows between failed replacement attempts. - const [first, second, third] = retries() + const [first, second, third] = retries(entries) expect(third!.at - second!.at).toBeGreaterThan(second!.at - first!.at) + // A connection fault is a warning on every attempt, and is not reported as a lost session. + const refused = entries.filter((entry) => + entry.errors.some((error) => error.code === 'ECONNREFUSED'), + ) + expect(refused.length).toBeGreaterThanOrEqual(3) + for (const entry of [...refused, ...retries(entries)]) { + expect(entry.level).toBe('warn') + expect(entry.msg).not.toMatch(/session lost/) + } const obligations = lifecycleFor(adapter).obligationCount // The server is reachable again: a later attempt establishes a new session. - connection.password = url.password - const hooksBefore = hooks + connection.port = Number(url.port) + const hooksBefore = h.hooks() await eventually(async () => { const sessions = await lockSessions() expect(sessions).toHaveLength(1) expect(sessions[0]!.pid).not.toBe(lost) - expect(hooks).toBeGreaterThan(hooksBefore) + expect(h.hooks()).toBeGreaterThan(hooksBefore) }, 20_000) expect(lifecycleFor(adapter).obligationCount).toBeLessThanOrEqual(obligations) + expect(entries.filter((entry) => entry.level === 'error')).toEqual([]) expect(await adapter.stop()).toBe(true) } finally { - await adapter.stop().catch(() => undefined) - await observer.end({ timeout: 5 }) - await deleteDb() + await h.dispose() } }, 40_000) + + it('retries a replacement lock whose credentials are rejected, logging an error on every attempt', async () => { + const h = await harness('replacement-auth') + const { adapter, connection, url, entries, observer, lockSessions } = h + try { + const lost = await h.start() + // Credentials can be rotated back: the attempts continue, but each one is an error. + connection.password = 'deliberately-invalid-replacement-password' + await observer`SELECT pg_terminate_backend(${lost})` + await eventually(async () => expect(retries(entries).length).toBeGreaterThanOrEqual(3)) + const rejected = entries.filter((entry) => + entry.errors.some((error) => error.code === '28P01'), + ) + expect(rejected.length).toBeGreaterThanOrEqual(3) + for (const entry of [...rejected, ...retries(entries)]) { + expect(entry.level).toBe('error') + expect(entry.msg).not.toMatch(/session lost/) + } + connection.password = url.password + const hooksBefore = h.hooks() + await eventually(async () => { + const sessions = await lockSessions() + expect(sessions).toHaveLength(1) + expect(sessions[0]!.pid).not.toBe(lost) + expect(h.hooks()).toBeGreaterThan(hooksBefore) + }, 20_000) + expect(await adapter.stop()).toBe(true) + } finally { + await h.dispose() + } + }, 40_000) + + for (const fault of ['malformed bootstrap identity', 'changed backend identity'] as const) { + it(`retires scheduling when a replacement lock reports a ${fault}`, async () => { + const h = await harness('replacement-identity') + const { adapter, connection, entries, observer, lockSessions } = h + try { + const lost = await h.start() + // Fault injection on the server: the replacement session resolves pg_backend_pid() to + // a function that returns NULL, or another value on each call. + await observer.unsafe(` + CREATE SCHEMA prune_inject; + CREATE SEQUENCE prune_inject.pids; + CREATE FUNCTION prune_inject.pg_backend_pid() RETURNS integer + LANGUAGE sql AS $$ SELECT ${ + fault === 'malformed bootstrap identity' + ? 'NULL::integer' + : "nextval('prune_inject.pids')::integer" + } $$; + `) + connection.connection = { + ...connection.connection, + search_path: 'prune_inject, pg_catalog', + } + await observer`SELECT pg_terminate_backend(${lost})` + const identity = () => + entries.filter((entry) => + entry.errors.some((error) => + (fault === 'malformed bootstrap identity' + ? /Malformed scheduled prune bootstrap identity/ + : /changed backend identity/ + ).test(error.message), + ), + ) + await eventually(async () => expect(identity().length).toBe(1)) + expect(identity()[0]!.level).toBe('error') + // No further attempt, also once the fault is gone: about 20 ticks are skipped. + connection.connection = { application_name: h.application } + await Bun.sleep(1_000) + expect(identity()).toHaveLength(1) + expect(retries(entries)).toEqual([]) + expect(entries.filter((entry) => /re-established/.test(entry.msg))).toHaveLength(1) + expect(entries.some((entry) => /skipped: coordination is retired/.test(entry.msg))).toBe( + true, + ) + expect(await lockSessions()).toEqual([]) + expect(await adapter.stop()).toBe(true) + } finally { + await h.dispose() + } + }, 30_000) + } + + it('retries a replacement lock whose session closes between its bootstrap and its reservation', async () => { + let injected: PostgresPruneLock | undefined + let injectedApplication = '' + let inject = false + let observer!: postgres.Sql + /** The injected lock's driver state when the next replacement starts. */ + let atNextAttempt: { connections: number; opening: number } | undefined + class ReserveWindow extends PostgresAdapter { + protected override _acquirePruneLock(): Promise { + const self = this as unknown as { + pruneLock?: PostgresPruneLock + pruneLockReplaced: boolean + connection: Connection + _retirePruning: (error: unknown) => void + } + if (self.pruneLock === undefined && self.pruneLockReplaced) { + if (inject) { + inject = false + injectedApplication = `${self.connection.connection['application_name']}-window` + const lock = new PostgresPruneLock( + { + ...self.connection, + connection: { application_name: injectedApplication }, + }, + lifecycleFor(this), + (error) => self._retirePruning(error), + true, + ) + const client = lock.client as postgres.Sql & { + stats: { connections: number; opening: number } + } + const reserve = client.reserve.bind(client) + // The bootstrap SELECT succeeded. Its session is busy, so reserve() waits; then the + // session closes. postgres.js opens a new connection for the pending reservation. + client.reserve = (async () => { + void client`SELECT pg_sleep(10)`.catch(() => undefined) + const reservation = reserve() + await observer` + SELECT pg_terminate_backend(pid) FROM pg_stat_activity + WHERE application_name = ${injectedApplication} + ` + return reservation + }) as unknown as typeof client.reserve + self.pruneLock = injected = lock + } else if (injected && !atNextAttempt) { + const stats = ( + injected.client as unknown as { stats: { connections: number; opening: number } } + ).stats + atNextAttempt = { connections: stats.connections, opening: stats.opening } + } + } + return super._acquirePruneLock() + } + } + const h = await harness('replacement-window', ReserveWindow) + observer = h.observer + const { adapter, entries, lockSessions } = h + try { + const lost = await h.start() + inject = true + await observer`SELECT pg_terminate_backend(${lost})` + // A later attempt establishes a new session, after the injected one was closed. + await eventually(async () => { + expect(atNextAttempt).toBeDefined() + const sessions = await lockSessions() + expect(sessions).toHaveLength(1) + expect(sessions[0]!.pid).not.toBe(lost) + }) + expect(injected).toBeDefined() + expect(atNextAttempt).toEqual({ connections: 0, opening: 0 }) + const hooksBefore = h.hooks() + await eventually(async () => expect(h.hooks()).toBeGreaterThan(hooksBefore)) + // A connection loss in the bootstrap window is retried as a warning. + expect(entries.filter((entry) => entry.level === 'error')).toEqual([]) + expect(retries(entries).length).toBeGreaterThanOrEqual(1) + expect(await adapter.stop()).toBe(true) + } finally { + await h.dispose() + } + }, 30_000) } From ad2f2a7463be3f5ed6cbacf2c87a1a3817b64a87 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 12:43:31 -0300 Subject: [PATCH 077/100] fix: prune replacement review (R1, A1, A2, A4) - R1: during a stop, a replacement fault (also our own CONNECTION_DESTROYED) is not logged as a replaceable retirement; the pass reports it as an error. - A1: an acquisition that resolves false after its lock retired (N2) keeps the backoff counter, so repeated N2 faults back off. - A2: drop the #physicallyClosed reset in the N2 abandon path: postgres.js 4 end() resolves only with no connection left, and close() awaits it first. - A4: the N4 test pins the lower bound of the early-tick tolerance. --- packages/docs/content/docs/adapters.mdx | 2 + packages/duron/src/adapters/postgres/base.ts | 9 +- .../duron/src/adapters/postgres/prune-lock.ts | 13 +- packages/duron/test/prune-backoff.test.ts | 137 +++++++++++++----- 4 files changed, 113 insertions(+), 48 deletions(-) diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index ee0f097..7c8041a 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -96,6 +96,8 @@ Observed session loss, uncertain/malformed coordination results, or false/reject - Another fault, such as rejected credentials (`28P01`) or a configuration error, is logged as an error on every attempt. The attempts continue, because the credentials can be restored. - A bootstrap result that does not prove the backend identity (malformed, or a reservation on another backend) retires scheduling, as on the first client. +A replacement that fails during a stop is reported as an error: no later tick retries it, and the fault can be the stop's own close of the client. + A bootstrap failure of the first client, an uncertain or malformed coordination result, a false or rejected unlock, or a failed close keeps scheduling retired until the adapter restarts. Each replaced client is closed and released, so repeated losses do not accumulate clients. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. ### Manual pruning and failure limits diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 9674fe7..ee02476 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -519,6 +519,9 @@ export abstract class PostgresBaseAdapter< * error. */ private _logReplaceableRetirement(err: unknown): boolean { + // During a stop no later tick runs. The fault can also be the stop's own close of the lock + // client (postgres.js CONNECTION_DESTROYED): the caller reports it as an error. + if (!lifecycleFor(this).accepting) return false switch (this._pruneLockReplacement()) { case 'lost': this.logger?.warn( @@ -633,8 +636,10 @@ export abstract class PostgresBaseAdapter< let acquired = false try { acquired = await this._acquirePruneLock() - // The lock session works again: a later failed replacement starts a new backoff. - this.pruneReplaceFailures = 0 + // The lock session works again: a later failed replacement starts a new backoff. An + // acquisition that resolves false after its lock retired (its bootstrap session + // closed while reserve() was pending) is a failed replacement. + if (acquired || !this.pruneRetired) this.pruneReplaceFailures = 0 } catch (error) { this._retirePruning(error) } diff --git a/packages/duron/src/adapters/postgres/prune-lock.ts b/packages/duron/src/adapters/postgres/prune-lock.ts index 4c68584..2d9b23f 100644 --- a/packages/duron/src/adapters/postgres/prune-lock.ts +++ b/packages/duron/src/adapters/postgres/prune-lock.ts @@ -202,19 +202,16 @@ export class PostgresPruneLock { * (`#uncertain` is set and the setup is not repeated). Give the connection back so that the * fault close's `end()` closes it at once: a reserved connection would stay open until the * end timeout destroys it, and the close would fail its five-second budget. The client is - * ending, so postgres.js does not lease the connection again. The bootstrap close - * observation does not cover a new connection: when one is open, the close waits for native - * evidence that it closed. + * ending, so postgres.js does not lease the connection again. + * `#physicallyClosed` stays true from the bootstrap session's close, although a new + * connection can be open here. The close is still confirmed only after that connection + * closed: postgres.js 4 (the supported peer) resolves `end()` only when it has no connection + * left, also after its timeout destroys them, and `close()` awaits `end()` first. */ #abandonLostBootstrapReservation(): void { const session = this.#session if (!session) return this.#session = undefined - const stats = (this.client as { stats?: { connections: number } }).stats - if (this.#physicallyClosed && stats !== undefined && stats.connections > 0) { - this.#physicallyClosed = false - this.#closed = this.#observeNativeClose() - } try { session.release() } catch { diff --git a/packages/duron/test/prune-backoff.test.ts b/packages/duron/test/prune-backoff.test.ts index f305532..9bb6460 100644 --- a/packages/duron/test/prune-backoff.test.ts +++ b/packages/duron/test/prune-backoff.test.ts @@ -10,50 +10,111 @@ import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' // would add a whole interval to each delay. Ticks and the clock are driven by the test. const interval = 60_000 +const config = { olderThan: new Date('2099-01-01'), intervalMs: interval } -it('retries a failed replacement on the tick nearest to its backoff, also when the tick is early', async () => { - let now = 0 - const attempts: number[] = [] - class FailingReplacement extends PGLiteAdapter { - protected override async _acquirePruneLock(): Promise { - attempts.push(now) - // The attempt fails a few milliseconds after its tick. - now += 5 - throw Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }) +interface Internals { + pruneClock: () => number + pruneRunning: boolean + _pruneTick: (config: { olderThan: Date; intervalMs: number }) => Promise +} + +for (const failure of ['throws', 'resolves false after its retirement'] as const) { + it(`retries a failed replacement on the tick nearest to its backoff (acquisition ${failure})`, async () => { + let now = 0 + const attempts: number[] = [] + class FailingReplacement extends PGLiteAdapter { + protected override async _acquirePruneLock(): Promise { + attempts.push(now) + // The attempt fails a few milliseconds after its tick. + now += 5 + const error = Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }) + if (failure === 'throws') throw error + // As when the bootstrap session closes while reserve() is pending: the session's + // close retires the lock, and the acquisition resolves false. + this._retirePruning(error) + return false + } + protected override _pruneLockReplacement(): PruneLockReplacement { + return 'unreachable' + } + } + const adapter = new FailingReplacement({ + connection: ':memory:', + // The real timer does not fire during the test: the test calls each tick. + pruneArchive: config, + }) + adapter.setId('prune-backoff') + adapter.setLogger(pino({ level: 'silent' })) + const internals = adapter as unknown as Internals + internals.pruneClock = () => now + try { + expect(await adapter.start()).toBe(true) + // The start pass (tick 0) runs on its own. + while (internals.pruneRunning || attempts.length === 0) await Bun.sleep(1) + const ticks: number[] = [] + for (let tick = 1; tick <= 8; tick++) { + // A tick more than half an interval before the due time does not retry. + now = tick * interval - interval / 2 - 10 + const before = attempts.length + await internals._pruneTick(config) + expect(attempts.length).toBe(before) + // Each tick fires one millisecond early. + now = tick * interval - 1 + await internals._pruneTick(config) + if (attempts.length > before) ticks.push(tick) + } + // Backoffs of 1, 2 and 4 intervals from each failure: ticks 1, 3 and 7. + expect(ticks).toEqual([1, 3, 7]) + } finally { + await adapter.stop() + } + }) +} + +it('reports a replacement that fails during a stop as an error, not as a later retry', async () => { + let rejectAttempt!: (error: unknown) => void + let attempts = 0 + class StoppedReplacement extends PGLiteAdapter { + protected override _acquirePruneLock(): Promise { + attempts++ + if (attempts === 1) { + return Promise.reject(Object.assign(new Error('refused'), { code: 'ECONNREFUSED' })) + } + // The replacement bootstrap is pending when the stop starts. + return new Promise((_, reject) => { + rejectAttempt = reject + }) } protected override _pruneLockReplacement(): PruneLockReplacement { return 'unreachable' } } - const adapter = new FailingReplacement({ - connection: ':memory:', - // The real timer does not fire during the test: the test calls each tick. - pruneArchive: { olderThan: new Date('2099-01-01'), intervalMs: interval }, - }) - adapter.setId('prune-backoff') - adapter.setLogger(pino({ level: 'silent' })) - const internals = adapter as unknown as { - pruneClock: () => number - pruneRunning: boolean - _pruneTick: (config: { olderThan: Date; intervalMs: number }) => Promise + const adapter = new StoppedReplacement({ connection: ':memory:', pruneArchive: config }) + adapter.setId('prune-stop-replacement') + const entries: Array<{ level: string; msg: string }> = [] + const logger = pino({ level: 'silent' }) + for (const level of ['error', 'warn'] as const) { + logger[level] = ((_: unknown, message?: string) => { + entries.push({ level, msg: message ?? '' }) + }) as never } + adapter.setLogger(logger) + const internals = adapter as unknown as Internals + let now = 0 internals.pruneClock = () => now - const config = { olderThan: new Date('2099-01-01'), intervalMs: interval } - try { - expect(await adapter.start()).toBe(true) - // The start pass (tick 0) runs on its own. - while (internals.pruneRunning || attempts.length === 0) await Bun.sleep(1) - const ticks: number[] = [] - for (let tick = 1; tick <= 8; tick++) { - // Each tick fires one millisecond early. - now = tick * interval - 1 - const before = attempts.length - await internals._pruneTick(config) - if (attempts.length > before) ticks.push(tick) - } - // Backoffs of 1, 2 and 4 intervals from each failure: ticks 1, 3 and 7. - expect(ticks).toEqual([1, 3, 7]) - } finally { - await adapter.stop() - } + expect(await adapter.start()).toBe(true) + while (internals.pruneRunning || attempts === 0) await Bun.sleep(1) + now = interval + void internals._pruneTick(config) + while (attempts < 2) await Bun.sleep(1) + const stopping = adapter.stop() + await Bun.sleep(10) + // The stop ends the replacement client: postgres.js rejects its bootstrap. + rejectAttempt( + Object.assign(new Error('write CONNECTION_DESTROYED'), { code: 'CONNECTION_DESTROYED' }), + ) + await stopping + const after = entries.slice(entries.findIndex((entry) => /retrying after/.test(entry.msg)) + 1) + expect(after.filter((entry) => /retries it/.test(entry.msg))).toEqual([]) + expect(after).toContainEqual({ level: 'error', msg: 'Error in prune scheduler' }) }) From 8322af2dfbb1e2535f70f36174245980c990f69f Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 13:09:35 -0300 Subject: [PATCH 078/100] test: prune backoff probes only after the due time is recorded (R2); docs wording (A5) --- packages/docs/content/docs/adapters.mdx | 2 +- packages/duron/test/prune-backoff.test.ts | 13 +++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 7c8041a..2e81a3f 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -96,7 +96,7 @@ Observed session loss, uncertain/malformed coordination results, or false/reject - Another fault, such as rejected credentials (`28P01`) or a configuration error, is logged as an error on every attempt. The attempts continue, because the credentials can be restored. - A bootstrap result that does not prove the backend identity (malformed, or a reservation on another backend) retires scheduling, as on the first client. -A replacement that fails during a stop is reported as an error: no later tick retries it, and the fault can be the stop's own close of the client. +A retirement during a stop is reported as an error, also the loss of an established session or a failed replacement: no later tick replaces the client, and the fault can be the stop's own close of the client. A bootstrap failure of the first client, an uncertain or malformed coordination result, a false or rejected unlock, or a failed close keeps scheduling retired until the adapter restarts. Each replaced client is closed and released, so repeated losses do not accumulate clients. PGLite instead coordinates locally on its existing engine: a coordination fault retires scheduling without closing that shared engine until normal adapter shutdown. This is not an independent-engine or multiprocess isolation guarantee. diff --git a/packages/duron/test/prune-backoff.test.ts b/packages/duron/test/prune-backoff.test.ts index 9bb6460..81bd50d 100644 --- a/packages/duron/test/prune-backoff.test.ts +++ b/packages/duron/test/prune-backoff.test.ts @@ -15,6 +15,8 @@ const config = { olderThan: new Date('2099-01-01'), intervalMs: interval } interface Internals { pruneClock: () => number pruneRunning: boolean + /** The due time of the next replacement attempt, once a tick recorded it (0 before). */ + pruneReplaceAt: number _pruneTick: (config: { olderThan: Date; intervalMs: number }) => Promise } @@ -53,11 +55,14 @@ for (const failure of ['throws', 'resolves false after its retirement'] as const while (internals.pruneRunning || attempts.length === 0) await Bun.sleep(1) const ticks: number[] = [] for (let tick = 1; tick <= 8; tick++) { - // A tick more than half an interval before the due time does not retry. - now = tick * interval - interval / 2 - 10 const before = attempts.length - await internals._pruneTick(config) - expect(attempts.length).toBe(before) + // A tick more than half an interval before the due time does not retry. Only once a + // tick recorded the due time: a probe that recorded it would move it with the tick. + if (internals.pruneReplaceAt !== 0) { + now = tick * interval - interval / 2 - 10 + await internals._pruneTick(config) + expect(attempts.length).toBe(before) + } // Each tick fires one millisecond early. now = tick * interval - 1 await internals._pruneTick(config) From 0a51ad59e10f9d4815293cf167d4bc1b7ebd765a Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 14:08:56 -0300 Subject: [PATCH 079/100] test(worker-discovery): seed direct-claim fixtures before the Client starts Two push-worker tests started the Client, created a job with runAction and then claimed it with a direct adapter.fetch. On a slow runner the Client's own periodic discovery (pullInterval 200 ms) claimed the job first, so the direct claim returned [] (CI native PG19 failure at line 345). - recovery-produced work: create, claim and abandon the job with direct Adapter calls before client.start(). Only the discovery chain's periodic recovery can requeue it; ran === 1 and the creation hint is dropped. - expiry frees group capacity: seed and claim the blocker (timeoutMs 500) before client.start(). The action has no short expire now, so a slow run of the waiting job cannot expire before completeJob (second flake mode: 'periodic safety claims after expiry' timed out under CPU load). The sleep + 'created' check becomes a timing-free assertion: the waiting job's startedAt >= the blocker's expiresAt (both database clock). --- packages/duron/test/worker-discovery.test.ts | 46 ++++++++++++++++---- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index fc7cd3c..d982e52 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -337,15 +337,28 @@ for (const factory of factories) { recoverJobsInterval: 100, logger: 'silent', }) + expect(await instance.adapter.start()).toBe(true) const dropped = dropAvailabilityHints(instance.adapter) - expect(await client.start()).toBe(true) - const jobId = await client.runAction('recovered', {}) + // Fixture, seeded before the Client starts: its own discovery cannot claim the job + // before the direct claim below. The creation hint is dropped. + const jobId = (await instance.adapter.createJob({ + queue: action.name, + groupKey: '@default', + input: {}, + timeoutMs: action.expire, + checksum: action.checksum, + concurrencyLimit: 10, + concurrencyStepLimit: 10, + description: null, + }))! // Direct Adapter claim is outside the Client coordinator: SQL-active, never executed. const claimed = await instance.adapter.fetch({ batch: 1 }) expect(claimed.map((job) => job.id)).toEqual([jobId]) - // Fixture: hand the claim to another owner without liveness. Periodic recovery - // rescues other owners' work, never this worker's own claims. + // Fixture: hand the claim to another owner without liveness. Only the periodic + // recovery of the discovery chain (recoverJobsInterval; recoverJobsOnStart is off) + // can requeue it, and recovery sends no hint. await abandonTo(instance.adapter, jobId, 'gone-worker') + expect(await client.start()).toBe(true) await eventually( async () => (await status(instance.adapter, jobId)) === 'completed', 'periodic recovery requeues and the worker completes the same job', @@ -420,7 +433,6 @@ for (const factory of factories) { let ran = 0 const action = defineAction()({ name: 'expiry', - expire: 500, groups: { concurrency: async () => 1 }, handler: async () => { ran++ @@ -436,19 +448,35 @@ for (const factory of factories) { recoverJobsInterval: 0, logger: 'silent', }) + expect(await instance.adapter.start()).toBe(true) const dropped = dropAvailabilityHints(instance.adapter) - expect(await client.start()).toBe(true) - const blocker = await client.runAction('expiry', {}) + // Fixture, seeded before the Client starts: its own discovery cannot claim the + // blocker before the direct claim below. Only the blocker has the short timeout, so + // a slow run of the waiting job cannot expire it before completion. + const blocker = (await instance.adapter.createJob({ + queue: action.name, + groupKey: '@default', + input: {}, + timeoutMs: 500, + checksum: action.checksum, + concurrencyLimit: 1, + concurrencyStepLimit: 10, + description: null, + }))! // Direct Adapter claim outside the coordinator holds the only group slot until expiry. const held = await instance.adapter.fetch({ batch: 1 }) expect(held.map((job) => job.id)).toEqual([blocker]) + expect(await client.start()).toBe(true) const waiting = await client.runAction('expiry', {}) - await Bun.sleep(100) - expect(await status(instance.adapter, waiting)).toBe('created') await eventually( async () => (await status(instance.adapter, waiting)) === 'completed', 'periodic safety claims after expiry', ) + // Claimed only after the blocker's expiry freed the slot. Both times come from + // the database clock. + const expiresAt = (await instance.adapter.getJobById(blocker))?.expiresAt + const startedAt = (await instance.adapter.getJobById(waiting))?.startedAt + expect(startedAt!.getTime()).toBeGreaterThanOrEqual(expiresAt!.getTime()) expect(ran).toBe(1) expect(dropped()).toBe(2) } finally { From 9f4ce559ee0c17b8e19abb6f964e2e5eb1e85959 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 14:09:48 -0300 Subject: [PATCH 080/100] test: silence no-unmodified-loop-condition in prune-backoff (async counter) --- packages/duron/test/prune-backoff.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/duron/test/prune-backoff.test.ts b/packages/duron/test/prune-backoff.test.ts index 81bd50d..eb1b109 100644 --- a/packages/duron/test/prune-backoff.test.ts +++ b/packages/duron/test/prune-backoff.test.ts @@ -108,10 +108,12 @@ it('reports a replacement that fails during a stop as an error, not as a later r let now = 0 internals.pruneClock = () => now expect(await adapter.start()).toBe(true) - while (internals.pruneRunning || attempts === 0) await Bun.sleep(1) + // Read through a function: the replacement bootstrap increments the counter asynchronously. + const attemptCount = () => attempts + while (internals.pruneRunning || attemptCount() === 0) await Bun.sleep(1) now = interval void internals._pruneTick(config) - while (attempts < 2) await Bun.sleep(1) + while (attemptCount() < 2) await Bun.sleep(1) const stopping = adapter.stop() await Bun.sleep(10) // The stop ends the replacement client: postgres.js rejects its bootstrap. From 8838a2098603b56a02fbf21204d861dda93dc5a4 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 15:32:57 -0300 Subject: [PATCH 081/100] fix: scope stop() drain exclusion to the caller's job; hide heldJobIds; review follow-ups N1: framework-started work (the worker discovery chain run, the ActionManager job run and the heartbeat) now starts a root lifecycle context (`run(work, { root: true })`), so it no longer inherits the context of the job or claim that triggered it. stop() awaited in job B (enqueued and started from job A) waits for A's handler again, and the context chain stays bounded while a backlog drains (it grew by one link per claim). The chain step callback -> step queue run -> handler -> job run is unchanged, so stop() in a handler or step still excludes its own work. Tests: stop-drain-scope.test.ts (PGlite + native; red before). C3: heldJobIds is no longer a public RecoverJobsOptions field. The Client passes its held job ids through the internal recoverJobsForClient (recovery-scope.ts), bound to the parsed options object; the built-in _recoverJobs reads them with heldJobIdsOf. A direct recoverJobs() keeps skipping the own id on a Client-bound adapter and includes it on a Client-less adapter (documented). Custom _recoverJobs overrides keep working. C2: docs and the multi-worker example use a unique id per process (`worker-${crypto.randomUUID()}`) and explain that shared ids make recovery requeue peers' running jobs. Nits: prune-lock CONNECTION_LOSS comment (a half-open backend can keep key 42 until reaped); error-handling.mdx lists WaitReadTimeoutError / WaitReadFailedError; claim-pglite pins one attempt for a non-40001 (22012) claim error (the 'retry every error' mutant now fails). Tests: adapter, server, archive, delete-jobs-safety and sql-injection run PGlite always and PostgreSQL only with POSTGRES_TEST, so a plain `bun test` needs no Docker (AGENTS.md, CI comment updated). --- .github/workflows/test.yml | 2 +- AGENTS.md | 6 +- packages/docs/content/docs/adapters.mdx | 2 +- packages/docs/content/docs/client-api.mdx | 4 +- packages/docs/content/docs/error-handling.mdx | 16 +++ packages/docs/content/docs/multi-worker.mdx | 33 +++-- packages/duron/src/action-manager.ts | 11 +- packages/duron/src/adapters/adapter.ts | 13 +- packages/duron/src/adapters/postgres/base.ts | 13 +- .../duron/src/adapters/postgres/prune-lock.ts | 7 +- packages/duron/src/adapters/schemas.ts | 8 -- packages/duron/src/client.ts | 48 ++++--- packages/duron/src/lifecycle.ts | 29 ++++- packages/duron/src/recovery-scope.ts | 43 ++++++- packages/duron/src/worker-discovery.ts | 3 +- packages/duron/test/adapter.test.ts | 4 +- packages/duron/test/archive.test.ts | 5 +- packages/duron/test/claim-pglite.test.ts | 4 + .../duron/test/delete-jobs-safety.test.ts | 5 +- packages/duron/test/recover-own-jobs.test.ts | 58 +++++++-- packages/duron/test/server.test.ts | 4 +- packages/duron/test/sql-injection.test.ts | 5 +- packages/duron/test/stop-drain-scope.test.ts | 117 ++++++++++++++++++ packages/examples/multi-worker/worker.ts | 5 +- 24 files changed, 358 insertions(+), 87 deletions(-) create mode 100644 packages/duron/test/stop-drain-scope.test.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a2dbd0b..86f4c29 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -59,7 +59,7 @@ jobs: # Pull before the tests, so the first test's timeout does not include the download. - name: Pull PostgreSQL image run: docker pull "$DURON_TEST_POSTGRES_IMAGE" - # Includes the PostgreSQL path of client.test.ts, which runs only with POSTGRES_TEST. + # Every PostgreSQL test runs only with POSTGRES_TEST; the test job above is PGlite only. - name: Run native tests run: bun test --timeout 10000 - name: PostgreSQL container logs diff --git a/AGENTS.md b/AGENTS.md index feef5d0..e0be5f4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,11 +63,11 @@ bun run build:docs # docs only - Run single file: `bun test --timeout 10000 specific.test.ts` - Default per-test timeout: pass `--timeout 10000` (the `test` script and CI do). Bun ignores a `timeout` key in `bunfig.toml` (oven-sh/bun#7789), so a plain `bun test` uses 5000 ms. - Core tests run with `bun test --timeout 10000` (no `--concurrent`: many suites share native resources and time-sensitive lifecycle budgets, and fail under cross-file concurrency) -- `test/docker.ts` auto-creates a Docker container on port 5440 for PostgreSQL tests. Docker must be running. +- A plain `bun test --timeout 10000` runs PGlite only and needs no Docker. PostgreSQL tests run only with `POSTGRES_TEST=true`; every file that uses PostgreSQL gates it on that variable. +- With `POSTGRES_TEST=true`, `test/docker.ts` auto-creates a Docker container on port 5440 for the PostgreSQL tests. Docker must be running. - Image: `DURON_TEST_POSTGRES_IMAGE` (default `postgres:19-alpine`). The suite is also verified on `postgres:16-alpine`. - Container: `duron-postgres-test-` (for example `duron-postgres-test-postgres-19-alpine`), so a changed image never reuses a container of another version. `DURON_TEST_POSTGRES_CONTAINER` overrides the name; an existing container must run the selected image. - Only one test container can publish port 5440: stop the other one before switching images. - - Native-only tests run with `POSTGRES_TEST=true`. ## Lint / Format (Oxlint/Oxfmt) @@ -110,7 +110,7 @@ bun run build:docs # docs only Workflow `.github/workflows/test.yml` (Bun pinned with `BUN_VERSION`, currently 1.4.5) has two jobs: -- `test`: `bun install --frozen-lockfile` → `typecheck` → `lint` → `fmt:check` → `build` → `bun test --timeout 10000` (mostly PGlite; a few suites also run PostgreSQL through `test/docker.ts` without `POSTGRES_TEST`). +- `test`: `bun install --frozen-lockfile` → `typecheck` → `lint` → `fmt:check` → `build` → `bun test --timeout 10000` (PGlite only, no Docker). - `native`: matrix over `postgres:16-alpine` and `postgres:19-alpine` (`DURON_TEST_POSTGRES_IMAGE`), `POSTGRES_TEST=true bun test --timeout 10000`. `test/docker.ts` starts the container on the runner's Docker. ## Branch Workflow diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 2e81a3f..fadc607 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -348,7 +348,7 @@ See the [Adapter API Reference](/docs/adapters) for all required methods. `Adapter.fetch()` dispatches to your `_fetch` override, and so does `Client.fetch()` when the Client has actions configured. A custom `_fetch` is responsible for its own cross-worker capacity safety; it only receives the built-in `SERIALIZABLE` claim protection when it delegates to the built-in PostgreSQL/PGLite `_fetch` (see [Multi-Worker Setup](/docs/multi-worker#claim-admission-and-group-capacity)). -Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). The Client passes an internal `heldJobIds` field in the recovery options: the job ids it holds locally, which the built-in `_recoverJobs` leaves alone while it rescues the adapter's other own jobs (`null` means skip the adapter's own id). A custom `_recoverJobs` that ignores it keeps its own behavior for the adapter's own jobs. +Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). For its own recoveries, the Client tells the built-in `_recoverJobs` which jobs it holds locally, through an internal channel tied to the options object (not an option field): the built-in method leaves those jobs alone while it rescues the adapter's other own jobs. A custom `_recoverJobs` keeps its own behavior for the adapter's own jobs; one that calls the built-in method with the same options object keeps the Client's held jobs, and one that passes a new options object gets the default of a direct call. A direct `recoverJobs()` call on an adapter used by a Client skips the adapter's own id; on an adapter without a Client it includes the adapter's own id entirely, including jobs that adapter claimed and still runs. ## Best Practices diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 7456779..4f85b2e 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -67,6 +67,8 @@ const client = duron({ **Optional.** Unique identifier for this Duron instance. Defaults to a random UUID. +The id must be unique per running process. Recovery requeues the jobs of this Client's own `id` that it does not hold, so two running Clients with the same `id` requeue each other's running jobs. Do not derive it from `process.pid` alone: in containers every worker is usually PID 1. See [Worker IDs](/docs/multi-worker#worker-ids). + ```ts { id: 'worker-1', @@ -273,7 +275,7 @@ Stop the Duron instance. Stops worker discovery, aborts all running jobs, waits await client.stop() ``` -`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. Like every running job, the calling job is aborted and ends `cancelled`. Code that runs in it after `stop()` resolves cannot issue database calls. The exclusion follows the handler's async context, not the `await`: a `stop()` started from a timer, callback or fire-and-forget task that a running handler or step created also excludes that handler or step from the drain, even if nothing awaits `stop()`. To stop and still wait for a handler, call `stop()` from outside it. +`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. Like every running job, the calling job is aborted and ends `cancelled`. Code that runs in it after `stop()` resolves cannot issue database calls. The exclusion follows the handler's async context, not the `await`: a `stop()` started from a timer, callback or fire-and-forget task that a running handler or step created also excludes that handler or step from the drain, even if nothing awaits `stop()`. To stop and still wait for a handler, call `stop()` from outside it. The exclusion never crosses a job boundary: when job A enqueues job B and B calls `stop()`, the drain still waits for A's handler. ## Job Methods diff --git a/packages/docs/content/docs/error-handling.mdx b/packages/docs/content/docs/error-handling.mdx index e2fde86..58ceaf8 100644 --- a/packages/docs/content/docs/error-handling.mdx +++ b/packages/docs/content/docs/error-handling.mdx @@ -385,6 +385,22 @@ Thrown when an action is cancelled (e.g., via `client.cancelJob()`). This is a n await client.cancelJob(jobId) ``` +### WaitReadTimeoutError and WaitReadFailedError + +Thrown by `client.runActionAndWait()` when its first read of the job's status did not finish within the Client's [`waitReadTimeout`](/docs/client-api#waitreadtimeout) (`WaitReadTimeoutError`), or failed (`WaitReadFailedError`, with the read error as its `cause`). Both carry the job id in `metadata.jobId`. The job may exist and keep running: only the caller's read gave up, and the job is not cancelled. + +```ts +import { WaitReadFailedError, WaitReadTimeoutError } from 'duron' + +try { + await client.runActionAndWait('sendEmail', { to: 'user@example.com' }) +} catch (error) { + if (error instanceof WaitReadTimeoutError || error instanceof WaitReadFailedError) { + // The job may still run: look it up later with client.getJobById(error.metadata.jobId) + } +} +``` + ## Error Utility Functions Duron exports utility functions for checking error types without using `instanceof`: diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 4540014..9034da4 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -36,14 +36,15 @@ All processes share the same database, so jobs created through any process are a Each worker process needs: -- **Unique ID**: Each worker must have a unique identifier +- **Unique ID**: Each worker process must have its own identifier (see [Worker IDs](#worker-ids)) - **Sync pattern**: Use `syncPattern: 'hybrid'` for efficient processing ```ts import { duron } from 'duron' import { postgresAdapter } from 'duron/adapters/postgres' -const workerId = process.env.WORKER_ID || `worker-${process.pid}` +// Unique per running process. Not `worker-${process.pid}`: in containers every PID is 1. +const workerId = process.env.WORKER_ID || `worker-${crypto.randomUUID()}` const client = duron({ id: workerId, // Unique ID for this worker @@ -190,7 +191,8 @@ client.logger.info(`🚀 Dashboard server running at http://localhost:${port}`) import { duron } from 'duron' import { postgresAdapter } from 'duron/adapters/postgres' -const workerId = process.env.WORKER_ID || `worker-${process.pid}` +// Unique per running process. Not `worker-${process.pid}`: in containers every PID is 1. +const workerId = process.env.WORKER_ID || `worker-${crypto.randomUUID()}` const client = duron({ id: workerId, @@ -286,7 +288,7 @@ Duron uses heartbeat-based liveness detection for crashed-instance recovery: 3. **On startup**: When `recoverJobsOnStart` is enabled, a worker recovers eligible jobs for its configured actions during startup. 4. **Dead detection**: A foreign owner is fresh only when `last_seen_at > now() - heartbeatTimeout`. Equality is stale; a missing liveness row is also eligible. Recovery does not newly include null owners. - **Own jobs**: Every startup and periodic recovery also includes the current client ID, regardless of its heartbeat, except for the jobs this Client holds locally: claimed, queued, running or writing their result (including a timed-out handler that still runs). Discovery runs recovery and claims one after the other, so no claim of this Client is in flight during it. This rescues jobs that a previous process with the same ID left active, and this process's own jobs that a rejected write left active: a failed `cancelJob` before the handler started, a failed final `completeJob`/`failJob` write, or a failed cancellation write of a running job that was aborted (that job is requeued and runs again). A job this worker holds is never requeued; a job claimed by a direct `client.database.fetch()` is not held, so it can be. Use one adapter instance per Client; a second Client constructor on an adapter that a Client already uses throws a `TypeError`, also when that Client was stopped (a stopped adapter cannot start again). - - **Direct calls**: A direct `client.database.recoverJobs()` call cannot see which jobs the Client holds, so it skips this worker's own ID and rescues only other owners. With `recoverJobsOnStart: false` and `recoverJobsInterval: 0`, Duron runs no recovery, so this worker's own leftovers stay active until this worker stops and its heartbeat goes stale; then other workers' recovery rescues them. + - **Direct calls**: A direct `client.database.recoverJobs()` call cannot see which jobs the Client holds, so it skips this worker's own ID and rescues only other owners. The jobs a Client holds are not a `recoverJobs` option. On an adapter that no Client uses, a direct call includes the adapter's own ID entirely, so it also requeues jobs that this adapter claimed and is still running. With `recoverJobsOnStart: false` and `recoverJobsInterval: 0`, Duron runs no recovery, so this worker's own leftovers stay active until this worker stops and its heartbeat goes stale; then other workers' recovery rescues them. 5. **Recovery behavior**: - **Expired jobs** (exceeded timeout): Archived as failed with error information - **Stuck jobs** (not expired): Reset to `created` status and can be picked up by any worker @@ -353,19 +355,24 @@ Failed startup is cleanup-only: Duron automatically attempts cleanup and does no ### Worker IDs -Use descriptive, unique IDs for each worker: +Every running process must use its own Client `id`. Recovery treats the jobs of its own `id` that this Client does not hold as leftovers of an earlier process, and requeues them. If two running workers share an `id`, each recovery (on start and every `recoverJobsInterval`) requeues the jobs the other worker is running, so those jobs run twice. ```ts -// Good: Descriptive and unique -id: `worker-${process.env.WORKER_ID || process.pid}` +// Good: unique per process (the default when `id` is omitted is also a random UUID) +id: `worker-${crypto.randomUUID()}` -// Good: Environment-based -id: process.env.WORKER_ID || `worker-${Date.now()}` +// Good: host name, PID and a random part +id: `worker-${os.hostname()}-${process.pid}-${crypto.randomUUID()}` -// Avoid: Random IDs that change on restart -id: `worker-${Math.random()}` +// Good only if no two running processes ever get the same value (for example a StatefulSet pod name) +id: process.env.WORKER_ID + +// Avoid: not unique. Containers usually run the worker as PID 1, so every replica is `worker-1` +id: `worker-${process.pid}` ``` +A stable `id` that is reused only after the previous process ended (such as a StatefulSet pod name) lets startup recovery rescue that process's leftover jobs at once. With a random `id`, other workers rescue them once the old process's heartbeat goes stale (`heartbeatTimeout`). + ### Heartbeat Settings Configure heartbeat timing based on your deployment: @@ -409,13 +416,13 @@ If jobs aren't being processed: If jobs remain in `active` status: 1. **Check heartbeat settings**: Ensure `heartbeatTimeout` is appropriate (default: 15s) -2. **Manual recovery**: Use `client.recoverJobs()` to manually recover stuck jobs +2. **Manual recovery**: Use `client.database.recoverJobs({ checksums })` to recover stuck jobs of other workers manually (it skips this worker's own ID; see [Job Recovery](#job-recovery)) ### Duplicate Job Processing If jobs are processed multiple times: -1. **Check worker IDs**: Ensure each worker has a unique ID +1. **Check worker IDs**: Ensure each running worker has its own ID (shared IDs make recovery requeue a peer's running jobs) 2. **Check database isolation**: Verify database connection isolation 3. **Check concurrency limits**: Review group concurrency limits diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index b8ee034..646363a 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -74,10 +74,13 @@ export class ActionManager> { let settlement: (() => Promise) | undefined try { if (this.#stopped || !lifecycleFor(this.#database).accepting) return - await lifecycleFor(this.#database).run(() => - this.#executeJob(entry.job, (settled) => { - settlement = settled - }), + // A root context: the queue can start this job from another job's settlement. + await lifecycleFor(this.#database).run( + () => + this.#executeJob(entry.job, (settled) => { + settlement = settled + }), + { root: true }, ) } finally { // Dequeued without reaching #executeJob (early return or rejected admission): release diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index c205621..71994aa 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -10,7 +10,7 @@ import { type JobStatus, } from '../constants.js' import { isStopFailure, lifecycleFor } from '../lifecycle.js' -import { usedByClient } from '../recovery-scope.js' +import { scopeRecovery } from '../recovery-scope.js' import { ArchiveStatsSchema, @@ -469,9 +469,10 @@ export abstract class Adapter extends EventEmitter { /** * Recover stuck jobs (jobs that were active but the process that owned them is no longer running). * - * Without the internal `heldJobIds` option, a call on an adapter used by a Client skips the - * adapter's own id (it cannot tell which own jobs the Client is running); a call on an - * adapter without a Client includes it. + * A direct call on an adapter used by a Client skips the adapter's own id (it cannot tell + * which own jobs the Client is running); a call on an adapter without a Client includes it + * (its own running jobs too). Only the Client's own recoveries rescue the adapter's own + * jobs that the Client does not hold. * * @returns Promise resolving to the number of jobs recovered */ @@ -482,9 +483,7 @@ export abstract class Adapter extends EventEmitter { throw new Error('Adapter is not accepting work') } const parsedOptions = RecoverJobsOptionsSchema.parse(options) - if (parsedOptions.heldJobIds === undefined) { - parsedOptions.heldJobIds = usedByClient(this) ? null : [] - } + scopeRecovery(this, options, parsedOptions) const result = await this._recoverJobs(parsedOptions) return NumberResultSchema.parse(result) } catch (error) { diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index ee02476..a07a085 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -29,6 +29,7 @@ import { STEP_STATUS_FAILED, } from '../../constants.js' import { lifecycleFor, throwLifecycleErrors } from '../../lifecycle.js' +import { heldJobIdsOf } from '../../recovery-scope.js' import { type WaitReadBudget, registerWaitReadExecutor } from '../../wait-read.js' import { Adapter, @@ -1553,16 +1554,18 @@ export abstract class PostgresBaseAdapter< /** * Internal method to recover stuck jobs (jobs that were active but the process that owned them is no longer running). * Uses the clients liveness table to detect dead owners: a client whose heartbeat is older than staleTimeoutMs (or missing) is considered dead. - * This adapter's own id is included too, except for the jobs listed in `heldJobIds` (the jobs - * its Client holds locally), so own jobs a previous process left, or that a rejected write - * left active, are rescued while held jobs are never touched. `heldJobIds: null` skips the own - * id. Expired archival and then requeue each run in their own transaction (see + * In a recovery of this adapter's Client, its own id is included too, except for the jobs + * the Client holds locally, so own jobs a previous process left, or that a rejected write + * left active, are rescued while held jobs are never touched. A direct call skips the own id + * when a Client uses this adapter, and includes it entirely otherwise (see + * `recovery-scope.ts`). Expired archival and then requeue each run in their own transaction (see * `_recoverLockedJobs`). * * @returns Promise resolving to the number of jobs recovered */ protected async _recoverJobs(options: RecoverJobsOptions): Promise { - const { checksums, staleTimeoutMs = 15_000, heldJobIds = [] } = options + const { checksums, staleTimeoutMs = 15_000 } = options + const heldJobIds = heldJobIdsOf(this, options) // Find owners of active jobs that are dead: no liveness row or stale heartbeat. // This instance's own id is added below, apart from its held jobs (null: skipped). diff --git a/packages/duron/src/adapters/postgres/prune-lock.ts b/packages/duron/src/adapters/postgres/prune-lock.ts index 2d9b23f..41204f3 100644 --- a/packages/duron/src/adapters/postgres/prune-lock.ts +++ b/packages/duron/src/adapters/postgres/prune-lock.ts @@ -3,8 +3,11 @@ import postgres, { type Options, type ReservedSql, type Sql } from 'postgres' import type { Lifecycle } from '../../lifecycle.js' /** - * Errors of a statement on an established session whose server session ended. The server - * released the session's advisory lock with it. + * Errors of a statement on an established session that this lock lost: its server session + * ended, or its socket failed. When the server ends the session, it releases the session's + * advisory lock. After a socket failure, a half-open backend can keep the lock (key 42) until + * the server reaps it; until then the replacement lock simply does not acquire it, so no + * pass runs twice. * - `CONNECTION_CLOSED`: postgres.js, the socket closed under a pending statement; * - `ECONNRESET`, `EPIPE`, `ETIMEDOUT`: the socket failed (reset, broken, keepalive timeout); * - `57P01` admin shutdown (also `pg_terminate_backend`), `57P02` crash shutdown, diff --git a/packages/duron/src/adapters/schemas.ts b/packages/duron/src/adapters/schemas.ts index c4c951b..a99cb65 100644 --- a/packages/duron/src/adapters/schemas.ts +++ b/packages/duron/src/adapters/schemas.ts @@ -173,14 +173,6 @@ export const RecoverJobsOptionsSchema = z.object({ staleTimeoutMs: z.optional(z.number()), /** AbortSignal to cancel recovery (e.g., during shutdown) */ signal: z.optional(z.instanceof(AbortSignal)), - /** - * Internal: set by Duron's Client, not a public option. The job ids the adapter's Client - * holds locally. An array: the adapter's own id counts as an unresponsive owner too, except - * for these jobs. `null`: skip the adapter's own id. When omitted, `Adapter.recoverJobs()` - * uses `null` for an adapter used by a Client and `[]` otherwise. Adapters that do not - * support it ignore it. - */ - heldJobIds: z.optional(z.nullable(z.array(z.string()))), }) export const FetchOptionsSchema = z.object({ diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 27c181a..9565644 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -27,7 +27,7 @@ import { JOB_STATUS_CANCELLED, JOB_STATUS_FAILED, type JobStatus } from './const import { WaitReadFailedError, WaitReadTimeoutError } from './errors.js' import { type Lifecycle, lifecycleFor } from './lifecycle.js' import { type FetchToken, LocalCancellation } from './local-cancellation.js' -import { markClientAdapter, usedByClient } from './recovery-scope.js' +import { markClientAdapter, recoverJobsForClient, usedByClient } from './recovery-scope.js' import { validateSchema } from './standard-schema.js' import { WaitManager, type WaitOutcome } from './wait-manager.js' import { type ClaimedBatch, WorkerDiscovery } from './worker-discovery.js' @@ -484,11 +484,14 @@ export class Client< recoverJobsInterval: this.#options.recoverJobsInterval, // Automatic and manual discovery call the Adapter's public methods directly. recover: () => - this.#database.recoverJobs({ - checksums: Object.values(actions).map((action) => action.checksum), - staleTimeoutMs: this.#options.heartbeatTimeout, - heldJobIds: this.#heldJobIds(), - }), + recoverJobsForClient( + this.#database, + { + checksums: Object.values(actions).map((action) => action.checksum), + staleTimeoutMs: this.#options.heartbeatTimeout, + }, + this.#heldJobIds(), + ), claim: (batch) => this.#claim(batch), }) } @@ -1168,11 +1171,14 @@ export class Client< await this.#database.heartbeat() if (!this.#lifecycle.accepting) return false if (this.#actions && this.#options.recoverJobsOnStart) { - await this.#database.recoverJobs({ - checksums: Object.values(this.#actions).map((action) => action.checksum), - staleTimeoutMs: this.#options.heartbeatTimeout, - heldJobIds: this.#heldJobIds(), - }) + await recoverJobsForClient( + this.#database, + { + checksums: Object.values(this.#actions).map((action) => action.checksum), + staleTimeoutMs: this.#options.heartbeatTimeout, + }, + this.#heldJobIds(), + ) if (!this.#lifecycle.accepting) return false this.#discovery?.anchorRecovery() } @@ -1379,15 +1385,19 @@ export class Client< this.#heartbeatTimer = setTimeout(() => { if (!this.#lifecycle.accepting) return + // A root context: each beat schedules the next, so they must not link into a chain. void this.#lifecycle - .run(async () => { - try { - await this.#database.heartbeat() - } catch (error) { - this.#logger.error({ error }, '[Duron] Periodic heartbeat failed') - } - this.#scheduleHeartbeat() - }) + .run( + async () => { + try { + await this.#database.heartbeat() + } catch (error) { + this.#logger.error({ error }, '[Duron] Periodic heartbeat failed') + } + this.#scheduleHeartbeat() + }, + { root: true }, + ) .catch((error: unknown) => { this.#logger.error({ error }, '[Duron] Heartbeat callback failed') }) diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index 994d40a..f477db1 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -338,7 +338,23 @@ export class Lifecycle { } } - run(work: () => Promise, options?: { userCode?: boolean }): Promise { + /** Diagnostic: the number of this lifecycle's contexts linked around the caller. */ + contextDepth(): number { + let depth = 0 + for (let token = context.getStore(); token; token = token.parent) { + if (token.lifecycle === this) depth++ + } + return depth + } + + /** + * Admit ordinary work. `root` starts a context without a parent: use it for work that the + * framework starts itself (a discovery chain, a job run, a heartbeat), so that it does not + * inherit the context of the job or claim that happened to trigger it. Without it, + * `excludeCallerFromDrain` could exclude another job's handler, and the chain of linked + * contexts would grow with every claim while a backlog drains. + */ + run(work: () => Promise, options?: { userCode?: boolean; root?: boolean }): Promise { const caller = context.getStore() if ( !this.#ordinaryOpen || @@ -347,7 +363,7 @@ export class Lifecycle { ) { return Promise.reject(new Error('Lifecycle is not accepting work')) } - const promise = this.#inContext('operation', work, options?.userCode) + const promise = this.#inContext('operation', work, options?.userCode, options?.root) this.#observe(promise, this.#work) return promise } @@ -488,8 +504,13 @@ export class Lifecycle { ) } - #inContext(kind: Context['kind'], work: () => Promise, userCode = false): Promise { - const enclosing = context.getStore() + #inContext( + kind: Context['kind'], + work: () => Promise, + userCode = false, + root = false, + ): Promise { + const enclosing = root ? undefined : context.getStore() const token: Context = { lifecycle: this, kind, diff --git a/packages/duron/src/recovery-scope.ts b/packages/duron/src/recovery-scope.ts index e40ebf2..21b3bb7 100644 --- a/packages/duron/src/recovery-scope.ts +++ b/packages/duron/src/recovery-scope.ts @@ -1,12 +1,23 @@ +import type { Adapter } from './adapters/adapter.js' +import type { RecoverJobsOptions } from './adapters/schemas.js' + /** * Internal recovery scope registry: not exported by the package. * * Adapters used by a Client (at most one Client per adapter; a second Client constructor on * a marked adapter throws). A direct `recoverJobs()` call on such an adapter cannot know * which of the adapter's own jobs the Client holds locally (claimed, queued, running or - * finalizing), so it skips the adapter's own id. The Client passes its held job ids itself. + * finalizing), so it skips the adapter's own id. Only the Client passes its held job ids, + * through `recoverJobsForClient`; they are not a public `recoverJobs` option. + * + * Held job ids: an array means the adapter's own id counts as an unresponsive owner too, + * except for these jobs; `null` means skip the adapter's own id. */ const clientAdapters = new WeakSet() +/** Held ids of a Client recovery, keyed by the options object the Client passed. */ +const requested = new WeakMap() +/** Held ids of a recovery, keyed by the parsed options object given to `_recoverJobs`. */ +const scoped = new WeakMap() /** Mark `adapter` as used by a Client. */ export function markClientAdapter(adapter: object): void { @@ -17,3 +28,33 @@ export function markClientAdapter(adapter: object): void { export function usedByClient(adapter: object): boolean { return clientAdapters.has(adapter) } + +/** The Client's recovery: `Adapter.recoverJobs` with the job ids the Client holds locally. */ +export function recoverJobsForClient( + adapter: Adapter, + options: RecoverJobsOptions, + heldJobIds: string[] | null, +): Promise { + const request = { ...options } + requested.set(request, heldJobIds) + return adapter.recoverJobs(request) +} + +/** + * Called by `Adapter.recoverJobs`: binds the held ids of this call to its parsed options. + * A call that did not come from `recoverJobsForClient` uses the adapter's default: skip the + * own id when a Client uses the adapter, include it entirely otherwise. + */ +export function scopeRecovery(adapter: object, input: object, parsed: object): void { + scoped.set(parsed, requested.has(input) ? requested.get(input)! : defaultHeld(adapter)) + requested.delete(input) +} + +/** The held ids for a `_recoverJobs` call (the adapter's default for unknown options). */ +export function heldJobIdsOf(adapter: object, options: object): string[] | null { + return scoped.has(options) ? scoped.get(options)! : defaultHeld(adapter) +} + +function defaultHeld(adapter: object): string[] | null { + return usedByClient(adapter) ? null : [] +} diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index 9c2ffc4..c286e04 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -221,7 +221,8 @@ export class WorkerDiscovery { this.#chain = true let chain: Promise try { - chain = this.#options.lifecycle.run(() => this.#chainWork(request, recover)) + // A root context: the chain does not inherit the job or claim that triggered it. + chain = this.#options.lifecycle.run(() => this.#chainWork(request, recover), { root: true }) } catch (error) { chain = Promise.reject(error) } diff --git a/packages/duron/test/adapter.test.ts b/packages/duron/test/adapter.test.ts index a3acc1a..ebb609c 100644 --- a/packages/duron/test/adapter.test.ts +++ b/packages/duron/test/adapter.test.ts @@ -1782,8 +1782,8 @@ function runAdapterTests(adapterFactory: AdapterFactory) { }) } -runAdapterTests(postgresFactory) +runAdapterTests(pgliteFactory) // oxlint-disable-next-line useLiteralKeys if (process.env['POSTGRES_TEST'] === 'true') { - runAdapterTests(pgliteFactory) + runAdapterTests(postgresFactory) } diff --git a/packages/duron/test/archive.test.ts b/packages/duron/test/archive.test.ts index dd8b71f..861827c 100644 --- a/packages/duron/test/archive.test.ts +++ b/packages/duron/test/archive.test.ts @@ -623,4 +623,7 @@ function runArchiveTests(adapterFactory: AdapterFactory) { } runArchiveTests(pgliteFactory) -runArchiveTests(postgresFactory) +// oxlint-disable-next-line useLiteralKeys +if (process.env['POSTGRES_TEST'] === 'true') { + runArchiveTests(postgresFactory) +} diff --git a/packages/duron/test/claim-pglite.test.ts b/packages/duron/test/claim-pglite.test.ts index 7983bdb..155427c 100644 --- a/packages/duron/test/claim-pglite.test.ts +++ b/packages/duron/test/claim-pglite.test.ts @@ -124,8 +124,10 @@ describe('PGLite claim transaction', () => { await engine.exec(` CREATE TABLE duron.claim_test_faults (armed boolean); INSERT INTO duron.claim_test_faults VALUES (true); + CREATE SEQUENCE duron.claim_test_attempts; CREATE FUNCTION duron.claim_test_fault() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + PERFORM nextval('duron.claim_test_attempts'); IF (SELECT armed FROM duron.claim_test_faults) THEN PERFORM 1 / 0; END IF; RETURN NULL; END $$; @@ -138,6 +140,8 @@ describe('PGLite claim transaction', () => { (error: { cause?: { code?: string } }) => error, ) expect(failed?.cause?.code).toBe('22012') + // Only a 40001 conflict is retried: any other statement error surfaces after one attempt. + expect(await claimAttempts(engine)).toBe(1) const statuses = await engine.query<{ status: string }>( 'SELECT status FROM duron.jobs_active', ) diff --git a/packages/duron/test/delete-jobs-safety.test.ts b/packages/duron/test/delete-jobs-safety.test.ts index 1020070..8c7996f 100644 --- a/packages/duron/test/delete-jobs-safety.test.ts +++ b/packages/duron/test/delete-jobs-safety.test.ts @@ -128,6 +128,9 @@ function runDeleteJobsSafetyTests(adapterFactory: AdapterFactory) { } describe('Delete Jobs Safety Tests', () => { - runDeleteJobsSafetyTests(postgresFactory) runDeleteJobsSafetyTests(pgliteFactory) + // oxlint-disable-next-line useLiteralKeys + if (process.env['POSTGRES_TEST'] === 'true') { + runDeleteJobsSafetyTests(postgresFactory) + } }) diff --git a/packages/duron/test/recover-own-jobs.test.ts b/packages/duron/test/recover-own-jobs.test.ts index 323b668..fc4f756 100644 --- a/packages/duron/test/recover-own-jobs.test.ts +++ b/packages/duron/test/recover-own-jobs.test.ts @@ -7,14 +7,16 @@ import { defineAction } from '../src/action.js' import type { Adapter } from '../src/adapters/adapter.js' import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import type { RecoverJobsOptions } from '../src/adapters/schemas.js' import { Client } from '../src/client.js' +import { recoverJobsForClient } from '../src/recovery-scope.js' import { getPostgresConnection } from './docker.js' // Own-id recovery scope (adapter level). Recovery rescues owners whose liveness is missing // or stale and, unless told to skip it, this adapter's own id too, except the job ids its -// Client holds locally (internal `heldJobIds` option). An adapter used by a Client skips its -// own id in direct calls. Controls: public Adapter calls and reads; setId to claim as another +// Client holds locally (passed only through the internal `recoverJobsForClient`). An adapter +// used by a Client skips its own id in direct calls. Controls: public Adapter calls and reads; setId to claim as another // owner (no liveness row); one fault-injected recovery transaction. const TEST_MS = 30_000 @@ -157,7 +159,7 @@ for (const engine of engines) { await Bun.sleep(400) const heldJobIds = [heldRunning, heldExpired, deadHeld] - expect(await adapter.recoverJobs({ checksums: [CHECKSUM], heldJobIds })).toBe(5) + expect(await recoverJobsForClient(adapter, { checksums: [CHECKSUM] }, heldJobIds)).toBe(5) expect(await job(adapter, heldRunning)).toEqual({ ...before, status: 'active' }) expect(await job(adapter, heldExpired)).toMatchObject({ status: 'active', clientId: OWN }) expect(await job(adapter, ownRunning)).toMatchObject({ status: 'created' }) @@ -166,20 +168,20 @@ for (const engine of engines) { expect(await job(adapter, deadExpired)).toMatchObject({ status: 'failed' }) expect(await job(adapter, deadHeld)).toMatchObject({ status: 'created' }) // With only held jobs left, a later recovery has nothing to rescue. - expect(await adapter.recoverJobs({ checksums: [CHECKSUM], heldJobIds })).toBe(0) + expect(await recoverJobsForClient(adapter, { checksums: [CHECKSUM] }, heldJobIds)).toBe(0) expect(await job(adapter, heldRunning)).toEqual({ ...before, status: 'active' }) }), TEST_MS, ) it( - 'heldJobIds null skips the own id, and so does a direct call on an adapter used by a Client', + 'held ids null skip the own id, and so does a direct call on an adapter used by a Client', () => withStore(async (start) => { const adapter = await start() const own = await claimAs(adapter, OWN) const dead = await claimAs(adapter, DEAD) - expect(await adapter.recoverJobs({ checksums: [CHECKSUM], heldJobIds: null })).toBe(1) + expect(await recoverJobsForClient(adapter, { checksums: [CHECKSUM] }, null)).toBe(1) expect(await job(adapter, own)).toMatchObject({ status: 'active', clientId: OWN }) expect(await job(adapter, dead)).toMatchObject({ status: 'created' }) @@ -199,6 +201,44 @@ for (const engine of engines) { expect(adapter.id).toBe(OWN) expect(await adapter.recoverJobs({ checksums: [CHECKSUM] })).toBe(0) expect(await job(adapter, own)).toMatchObject({ status: 'active', clientId: OWN }) + // The held ids are not a public option: passing them cannot widen a direct call. + // @ts-expect-error heldJobIds is not part of RecoverJobsOptions + const typed: RecoverJobsOptions = { checksums: [CHECKSUM], heldJobIds: [] } + expect(typed.checksums).toEqual([CHECKSUM]) + const widened = { checksums: [CHECKSUM], heldJobIds: [] } + expect(await adapter.recoverJobs(widened)).toBe(0) + expect(await job(adapter, own)).toMatchObject({ status: 'active', clientId: OWN }) + }), + TEST_MS, + ) + + it( + 'a custom _recoverJobs that forwards the options keeps the held ids; new options use the default', + () => + withStore(async (start) => { + const adapter = await start() + const own = await claimAs(adapter, OWN) + const client = new Client({ + id: OWN, + database: adapter, + actions: { + action: defineAction()({ name: 'own-recovery', handler: async () => ({}) }), + }, + syncPattern: false, + logger: 'silent', + }) + expect(client.getConfig().id).toBe(OWN) + type Recover = (options: RecoverJobsOptions) => Promise + const custom = adapter as unknown as { _recoverJobs: Recover } + const builtIn = custom._recoverJobs.bind(adapter) + // New options object: the Client-bound default applies (skip the own id). + custom._recoverJobs = (options) => builtIn({ ...options }) + expect(await recoverJobsForClient(adapter, { checksums: [CHECKSUM] }, [])).toBe(0) + expect(await job(adapter, own)).toMatchObject({ status: 'active', clientId: OWN }) + // Forwarded options: the Client's held ids apply (none held, so the own job is rescued). + custom._recoverJobs = (options) => builtIn(options) + expect(await recoverJobsForClient(adapter, { checksums: [CHECKSUM] }, [])).toBe(1) + expect(await job(adapter, own)).toMatchObject({ status: 'created' }) }), TEST_MS, ) @@ -212,12 +252,14 @@ for (const engine of engines) { expect(await first.stop()).toBe(true) const restarted = await start() - expect(await restarted.recoverJobs({ checksums: [CHECKSUM], heldJobIds: [] })).toBe(1) + expect(await recoverJobsForClient(restarted, { checksums: [CHECKSUM] }, [])).toBe(1) expect(await job(restarted, leftover)).toMatchObject({ status: 'created' }) expect((await restarted.fetch({ batch: 1 })).map((value) => value.id)).toEqual([leftover]) const heldJobIds = [leftover] - expect(await restarted.recoverJobs({ checksums: [CHECKSUM], heldJobIds })).toBe(0) + expect(await recoverJobsForClient(restarted, { checksums: [CHECKSUM] }, heldJobIds)).toBe( + 0, + ) expect(await job(restarted, leftover)).toMatchObject({ status: 'active', clientId: OWN }) }), TEST_MS, diff --git a/packages/duron/test/server.test.ts b/packages/duron/test/server.test.ts index f7948d2..3ecc4f7 100644 --- a/packages/duron/test/server.test.ts +++ b/packages/duron/test/server.test.ts @@ -703,8 +703,8 @@ function runServerTests(adapterFactory: AdapterFactory) { }) } -runServerTests(postgresFactory) +runServerTests(pgliteFactory) // oxlint-disable-next-line useLiteralKeys if (process.env['POSTGRES_TEST'] === 'true') { - runServerTests(pgliteFactory) + runServerTests(postgresFactory) } diff --git a/packages/duron/test/sql-injection.test.ts b/packages/duron/test/sql-injection.test.ts index b66086c..7ec8a13 100644 --- a/packages/duron/test/sql-injection.test.ts +++ b/packages/duron/test/sql-injection.test.ts @@ -200,6 +200,9 @@ function runSqlInjectionTests(adapterFactory: AdapterFactory) { } describe('SQL Injection Tests', () => { - runSqlInjectionTests(postgresFactory) runSqlInjectionTests(pgliteFactory) + // oxlint-disable-next-line useLiteralKeys + if (process.env['POSTGRES_TEST'] === 'true') { + runSqlInjectionTests(postgresFactory) + } }) diff --git a/packages/duron/test/stop-drain-scope.test.ts b/packages/duron/test/stop-drain-scope.test.ts new file mode 100644 index 0000000..c376f3e --- /dev/null +++ b/packages/duron/test/stop-drain-scope.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'bun:test' + +import { defineAction } from '../src/action.js' +import { Client } from '../src/client.js' +import { lifecycleFor } from '../src/lifecycle.js' + +import { pgliteFactory, postgresFactory } from './adapters.js' + +// stop() awaited inside a handler excludes only the caller's own job from the drain. Work that +// the framework starts itself (a discovery chain, a job run) starts a root context, so a job +// that another job enqueued and started does not inherit that job's context. + +for (const factory of [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +]) { + describe(`stop() drain scope with ${factory.name}`, () => { + // 'hint': B starts through the job-available hint (in-process on PGlite). + // 'fetch': A starts B itself through client.fetch() (the same on every engine). + for (const start of ['hint', 'fetch'] as const) { + it(`waits for the handler of the job that enqueued the stopping job (${start})`, async () => { + const instance = await factory.create() + let client: Client | null = null + const t0 = performance.now() + let aSettled = -1 + type Outcome = { result?: unknown; error?: unknown; at: number } + const stopped = Promise.withResolvers() + const a = defineAction()({ + name: 'a', + handler: async () => { + await client!.runAction('b', {}) + if (start === 'fetch') await client!.fetch() + // Ignores the abort of stop(): the drain must wait for this raw handler. + await Bun.sleep(1_000) + aSettled = performance.now() - t0 + return {} + }, + }) + const b = defineAction()({ + name: 'b', + handler: async () => { + try { + stopped.resolve({ result: await client!.stop(), at: performance.now() - t0 }) + } catch (error) { + stopped.resolve({ error, at: performance.now() - t0 }) + } + return {} + }, + }) + client = new Client({ + id: `drain-scope-${crypto.randomUUID()}`, + database: instance.adapter, + actions: { a, b }, + syncPattern: start === 'hint' ? 'hybrid' : false, + pullInterval: 60_000, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + await client.runAction('a', {}) + if (start === 'fetch') await client.fetch() + const outcome = await Promise.race([ + stopped.promise, + Bun.sleep(8_000).then((): Outcome => ({ error: 'stop() did not settle', at: -1 })), + ]) + expect(outcome.error).toBeUndefined() + expect(outcome.result).toBe(true) + expect(aSettled).toBeGreaterThan(0) + expect(outcome.at).toBeGreaterThanOrEqual(aSettled) + } finally { + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 15_000) + } + + it('keeps the context chain bounded while a backlog drains', async () => { + const instance = await factory.create() + const lifecycle = lifecycleFor(instance.adapter) + const jobs = 60 + const depths: number[] = [] + const action = defineAction()({ + name: 'plain', + handler: async () => { + depths.push(lifecycle.contextDepth()) + await Bun.sleep(1) + return {} + }, + }) + const client = new Client({ + id: `drain-depth-${crypto.randomUUID()}`, + database: instance.adapter, + actions: { plain: action }, + syncPattern: 'hybrid', + batchSize: 1, + pullInterval: 60_000, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + for (let i = 0; i < jobs; i++) await client.runAction('plain', {}) + const deadline = performance.now() + 10_000 + while (depths.length < jobs && performance.now() < deadline) await Bun.sleep(20) + expect(depths.length).toBe(jobs) + // The handler context and its job run; nothing links back to earlier jobs or claims. + expect(Math.max(...depths)).toBe(2) + } finally { + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 20_000) + }) +} diff --git a/packages/examples/multi-worker/worker.ts b/packages/examples/multi-worker/worker.ts index 2c9fd7e..3ca015d 100644 --- a/packages/examples/multi-worker/worker.ts +++ b/packages/examples/multi-worker/worker.ts @@ -3,8 +3,9 @@ import { duron } from 'duron' import { postgresAdapter } from 'duron/adapters/postgres' // Worker process: Processes jobs from the database -// Each worker has a unique ID and processes jobs independently -const workerId = process.env.WORKER_ID || `worker-${process.pid}` +// Each worker has a unique ID and processes jobs independently. The ID must be unique per +// running process: a shared ID makes recovery requeue the jobs another worker is running. +const workerId = process.env.WORKER_ID || `worker-${crypto.randomUUID()}` const client = duron({ id: workerId, From 98a4ceeee13ba84b37e624d3d6181621839ea476 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 16:06:34 -0300 Subject: [PATCH 082/100] fix: run queued steps in the pusher's context; pin the discovery and heartbeat roots R1: fastq starts a queued task from the settlement of the task that finished, in that task's async context. A step queued behind a sibling's child step therefore inherited the sibling's callback context, and its stop() excluded the sibling from the drain. StepManager now captures AsyncLocalStorage.snapshot() in push() and runs the worker inside it. Test: stop-drain-scope 'waits for a sibling step of the stopping step' (nested fails without the fix on PGlite and native; flat is the control). R2: the bounded-chain test now also records the lifecycle context depth inside adapter.fetch (each claim) and adapter.heartbeat (each beat, heartbeatInterval 20) and asserts 1. Removing the discovery root fails it (62), removing the heartbeat root fails it (30/32), removing the ActionManager root fails it (3), on PGlite and native. A1: error-handling.mdx error-code table lists WAIT_READ_TIMEOUT and WAIT_READ_FAILED; client-api.mdx states that the stop() exclusion never covers a sibling step. --- packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/error-handling.mdx | 2 + packages/duron/src/step-manager.ts | 59 ++++++---- packages/duron/test/stop-drain-scope.test.ts | 110 ++++++++++++++++-- 4 files changed, 143 insertions(+), 30 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 4f85b2e..39d0168 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -275,7 +275,7 @@ Stop the Duron instance. Stops worker discovery, aborts all running jobs, waits await client.stop() ``` -`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. Like every running job, the calling job is aborted and ends `cancelled`. Code that runs in it after `stop()` resolves cannot issue database calls. The exclusion follows the handler's async context, not the `await`: a `stop()` started from a timer, callback or fire-and-forget task that a running handler or step created also excludes that handler or step from the drain, even if nothing awaits `stop()`. To stop and still wait for a handler, call `stop()` from outside it. The exclusion never crosses a job boundary: when job A enqueues job B and B calls `stop()`, the drain still waits for A's handler. +`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. Like every running job, the calling job is aborted and ends `cancelled`. Code that runs in it after `stop()` resolves cannot issue database calls. The exclusion follows the handler's async context, not the `await`: a `stop()` started from a timer, callback or fire-and-forget task that a running handler or step created also excludes that handler or step from the drain, even if nothing awaits `stop()`. To stop and still wait for a handler, call `stop()` from outside it. The exclusion covers only the calling handler or step and the steps that enclose it. It never covers a sibling step, and it never crosses a job boundary: when job A enqueues job B and B calls `stop()`, the drain still waits for A's handler. ## Job Methods diff --git a/packages/docs/content/docs/error-handling.mdx b/packages/docs/content/docs/error-handling.mdx index 58ceaf8..dd89dc6 100644 --- a/packages/docs/content/docs/error-handling.mdx +++ b/packages/docs/content/docs/error-handling.mdx @@ -459,3 +459,5 @@ Each Duron error has a `code` property for identification: | `StepTimeoutError` | `STEP_TIMEOUT` | | `ActionCancelError` | `ACTION_CANCEL` | | `UnhandledChildStepsError` | `UNHANDLED_CHILD_STEPS` | +| `WaitReadTimeoutError` | `WAIT_READ_TIMEOUT` | +| `WaitReadFailedError` | `WAIT_READ_FAILED` | diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index 45389b3..e121b73 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -1,3 +1,5 @@ +import { AsyncLocalStorage } from 'node:async_hooks' + import { type Context, context, @@ -209,6 +211,12 @@ export interface TaskStep { onStart?: () => void } +/** A queued step task with the async context of the code that pushed it. */ +interface QueuedTask { + task: TaskStep + pusher: (fn: () => R) => R +} + /** * StepStore manages step records in the database. * Provides methods to create, update, and delay steps. @@ -327,7 +335,7 @@ export class StepManager { #stepStore: StepStore #lifecycle: Lifecycle #tracer: Tracer - #queue: fastq.queueAsPromised + #queue: fastq.queueAsPromised #logger: Logger // each step name should be executed only once per parent (name + parentStepId) #historySteps = new Set() @@ -356,25 +364,34 @@ export class StepManager { this.#tracer = options.tracer this.#stepStore = new StepStore(options.adapter) this.#lifecycle = lifecycleFor(options.adapter) - this.#queue = fastq.promise(async (task: TaskStep) => { - task.onStart?.() - // Create composite key: name + parentStepId (allows same name under different parents) - const stepKey = `${task.parentStepId ?? 'root'}:${task.name}` - if (this.#historySteps.has(stepKey)) { - throw new StepAlreadyExecutedError(task.name, this.#jobId, this.#actionName) - } - this.#historySteps.add(stepKey) - return this.#lifecycle.run(() => - this.#executeStep( - task.name, - task.cb, - task.options, - task.abortSignal, - task.parentStepId, - task.parallel, - ), - ) - }, options.concurrencyLimit) + // fastq starts a queued task from the settlement of the task that finished, in that task's + // async context. Run each task in the context of the code that pushed it instead, so a + // queued step never inherits a sibling step's callback context (which would let its + // stop() exclude that sibling from the drain). + this.#queue = fastq.promise( + ({ task, pusher }: QueuedTask) => pusher(() => this.#runTask(task)), + options.concurrencyLimit, + ) + } + + async #runTask(task: TaskStep): Promise { + task.onStart?.() + // Create composite key: name + parentStepId (allows same name under different parents) + const stepKey = `${task.parentStepId ?? 'root'}:${task.name}` + if (this.#historySteps.has(stepKey)) { + throw new StepAlreadyExecutedError(task.name, this.#jobId, this.#actionName) + } + this.#historySteps.add(stepKey) + return this.#lifecycle.run(() => + this.#executeStep( + task.name, + task.cb, + task.options, + task.abortSignal, + task.parentStepId, + task.parallel, + ), + ) } /** @@ -463,7 +480,7 @@ export class StepManager { '[StepManager] Potential starvation: child step queued while all concurrency slots are occupied by parent steps. Consider increasing steps.concurrency.', ) } - return this.#queue.push(task) + return this.#queue.push({ task, pusher: AsyncLocalStorage.snapshot() }) } /** diff --git a/packages/duron/test/stop-drain-scope.test.ts b/packages/duron/test/stop-drain-scope.test.ts index c376f3e..2d9d9ae 100644 --- a/packages/duron/test/stop-drain-scope.test.ts +++ b/packages/duron/test/stop-drain-scope.test.ts @@ -76,26 +76,110 @@ for (const factory of [ }, 15_000) } - it('keeps the context chain bounded while a backlog drains', async () => { + // fastq starts a queued task from the settlement of the task that finished. A queued step + // must not start in that context: when step A's child A1 finishes, the queued step B would + // inherit A's callback context, and B's stop() would skip waiting for A. + for (const nested of [true, false]) { + it(`waits for a sibling step of the stopping step (${nested ? 'nested' : 'flat'})`, async () => { + const instance = await factory.create() + let client: Client | null = null + const t0 = performance.now() + let aSettled = -1 + type Outcome = { result?: unknown; error?: unknown; at: number } + const stopped = Promise.withResolvers() + const action = defineAction()({ + name: 'siblings', + steps: { concurrency: 2 }, + handler: async (ctx) => { + const a = ctx.step('A', async ({ step }) => { + if (nested) await step('A1', () => Bun.sleep(100).then(() => 1)) + else await Bun.sleep(100) + // Ignores the abort of stop(): the drain must wait for this step callback. + await Bun.sleep(1_000) + aSettled = performance.now() - t0 + return 1 + }) + // Fills the second slot in the flat variant, so B is queued in both variants. + const x = nested + ? Promise.resolve(0) + : ctx.step('X', () => Bun.sleep(100).then(() => 1)) + await Bun.sleep(30) + const b = ctx.step('B', async () => { + try { + stopped.resolve({ result: await client!.stop(), at: performance.now() - t0 }) + } catch (error) { + stopped.resolve({ error, at: performance.now() - t0 }) + } + return 1 + }) + await Promise.allSettled([a, b, x]) + return {} + }, + }) + client = new Client({ + id: `drain-siblings-${crypto.randomUUID()}`, + database: instance.adapter, + actions: { action }, + syncPattern: false, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + try { + expect(await client.start()).toBe(true) + await client.runAction('action', {}) + await client.fetch() + const outcome = await Promise.race([ + stopped.promise, + Bun.sleep(8_000).then((): Outcome => ({ error: 'stop() did not settle', at: -1 })), + ]) + expect(outcome.error).toBeUndefined() + expect(outcome.result).toBe(true) + expect(aSettled).toBeGreaterThan(0) + expect(outcome.at).toBeGreaterThanOrEqual(aSettled) + } finally { + await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 15_000) + } + + // Each claim and each heartbeat is framework work in its own root context: a claim does not + // link to the claim or job settlement that requested it, and a beat does not link to the + // beat that scheduled it. Recorded where the Client calls the adapter. + it('keeps the context chain bounded over many claims, jobs and heartbeats', async () => { const instance = await factory.create() - const lifecycle = lifecycleFor(instance.adapter) + const adapter = instance.adapter + const lifecycle = lifecycleFor(adapter) const jobs = 60 - const depths: number[] = [] + const depths = { handler: [] as number[], fetch: [] as number[], heartbeat: [] as number[] } + const fetch = adapter.fetch.bind(adapter) + adapter.fetch = (options) => { + depths.fetch.push(lifecycle.contextDepth()) + return fetch(options) + } + const heartbeat = adapter.heartbeat.bind(adapter) + adapter.heartbeat = () => { + depths.heartbeat.push(lifecycle.contextDepth()) + return heartbeat() + } const action = defineAction()({ name: 'plain', handler: async () => { - depths.push(lifecycle.contextDepth()) + depths.handler.push(lifecycle.contextDepth()) await Bun.sleep(1) return {} }, }) const client = new Client({ id: `drain-depth-${crypto.randomUUID()}`, - database: instance.adapter, + database: adapter, actions: { plain: action }, syncPattern: 'hybrid', batchSize: 1, pullInterval: 60_000, + heartbeatInterval: 20, + heartbeatTimeout: 1_000, recoverJobsOnStart: false, recoverJobsInterval: 0, logger: 'silent', @@ -104,10 +188,20 @@ for (const factory of [ expect(await client.start()).toBe(true) for (let i = 0; i < jobs; i++) await client.runAction('plain', {}) const deadline = performance.now() + 10_000 - while (depths.length < jobs && performance.now() < deadline) await Bun.sleep(20) - expect(depths.length).toBe(jobs) + while ( + (depths.handler.length < jobs || depths.heartbeat.length < 30) && + performance.now() < deadline + ) { + await Bun.sleep(20) + } + expect(depths.handler.length).toBe(jobs) + expect(depths.fetch.length).toBeGreaterThanOrEqual(jobs) + expect(depths.heartbeat.length).toBeGreaterThanOrEqual(30) // The handler context and its job run; nothing links back to earlier jobs or claims. - expect(Math.max(...depths)).toBe(2) + expect(Math.max(...depths.handler)).toBe(2) + // Only the discovery chain run around each claim, only the beat's run around each beat. + expect(Math.max(...depths.fetch)).toBe(1) + expect(Math.max(...depths.heartbeat)).toBe(1) } finally { await client.stop().catch(() => undefined) await instance.deleteDb() From 78986c8b9ae5aa345ae5124af1c6496a365cc86e Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 17:12:13 -0300 Subject: [PATCH 083/100] fix(discovery): follow up short claims; wake discovery when a job of an uncovered claim settles C1: under several workers, a claim that returned fewer jobs than requested dropped its remaining demand, so part of a burst waited for the periodic tick. A claim locks every eligible row it sees (FOR UPDATE SKIP LOCKED in candidate_jobs) until it commits, so a concurrent claim returns few or even no jobs while work remains. Now a short claim with hinted (finite) demand left queues one follow-up after a random 10-50 ms delay. After an empty claim this happens only for more than one uncovered hint and only once in a row, so an empty queue is never polled and a lone hint that a peer won is not retried. The delay timer respects stop, cooldown and room (it only merges demand and pumps). Backlog: a completed job never woke discovery, so a group-limited backlog drained at L jobs per pullInterval. A job from a claim that did not cover its demand now requests discovery (unbounded demand, coalesced, trigger 'settled') when it settles locally. Jobs of a claim that covered its demand (one job for one hint) do not, so sparse traffic costs no extra claims. Tests: discovery-throughput.test.ts. A group-limited burst and backlog (limit 3, 20 ms jobs, 200 jobs, pullInterval 5 s) finish at handler speed with about one claim per freed slot and no claims once idle (PGlite + native). Native, 4 workers, 10 bursts of 300 jobs with 20 ms and 3000 ms jobs: every job starts before pullInterval / 2. worker-discovery: lone-hint empty claim is not retried, stop cancels a pending retry; two expectations updated for the new follow-ups. Docs: client-api batchSize, multi-worker Worker Discovery. --- packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 3 +- packages/duron/src/worker-discovery.ts | 87 +++++++- .../duron/test/discovery-throughput.test.ts | 188 ++++++++++++++++++ packages/duron/test/worker-discovery.test.ts | 70 ++++++- 5 files changed, 335 insertions(+), 15 deletions(-) create mode 100644 packages/duron/test/discovery-throughput.test.ts diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 39d0168..5fb0663 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -127,7 +127,7 @@ Periodic discovery is not reset or postponed by notifications or `fetch()` calls **Optional.** Defaults to `10`. Two meanings: -- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Notifications add up: the first one starts an automatic request for one job, and each later notification adds one job to it while it waits (behind a running discovery, for a cooldown, or for room). Startup and periodic checks make the request open-ended. Each claim takes at most B jobs and at most the remaining room. When a claim returns as many jobs as it asked for but did not cover the whole request (more notifications than one claim could take, or an open-ended request), another automatic request for the rest follows at once, so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. That follow-up waits for room and for a cooldown like any automatic request, and a due recovery runs before it claims. A claim that covered all of its notifications, such as one job for one notification, is not followed up. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. +- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Notifications add up: the first one starts an automatic request for one job, and each later notification adds one job to it while it waits (behind a running discovery, for a cooldown, or for room). Startup and periodic checks make the request open-ended. Each claim takes at most B jobs and at most the remaining room. When a claim returns as many jobs as it asked for but did not cover the whole request (more notifications than one claim could take, or an open-ended request), another automatic request for the rest follows at once, so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. That follow-up waits for room and for a cooldown like any automatic request, and a due recovery runs before it claims. A claim that covered all of its notifications, such as one job for one notification, is not followed up. A claim that returned fewer jobs than it asked for, while notifications are still uncovered, is followed up once after a random 10–50 ms delay: with several workers, the other rows are usually held by another worker's claim, which locks every eligible row it sees (`SKIP LOCKED`) until it commits, so a concurrent claim can even return nothing. After a claim that returned nothing, this happens only for more than one uncovered notification and only once in a row: a second empty claim in a row ends these follow-ups, so an empty queue is not polled, and a lone notification whose job another worker claimed is not retried. When a job from a claim that did not cover its request (for example a claim limited by its SQL group's concurrency) settles on this Client, it starts an open-ended automatic request, because its settlement can free a group slot; a group-limited backlog therefore drains as fast as its jobs finish, not at the group limit per `pullInterval`. Jobs from a claim that covered its notifications do not, so sparse traffic costs no extra claims. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. - **Default `fetch()` batch.** `fetch()` without `batchSize` passes this value unchanged. B is not the number of handlers that run at once. That is `actionConcurrencyLimit` per action, so with the defaults (B = 10, `actionConcurrencyLimit` = 100) at most ten automatically claimed jobs are outstanding. SQL group admission (`groupConcurrencyLimit` or `groups.concurrency`) is a separate limit across all workers. Jobs claimed by `fetch()` count toward B, and a `fetch()` batch can exceed B; automatic claiming then pauses until enough work settles. B limits claim admission only. It does not bound the rows that recovery examines, the backlog that manual calls create, or the total query rate. diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 9034da4..4978d46 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -249,7 +249,8 @@ Limits of this protection: Each Client with actions coordinates its own job discovery: - **One discovery at a time.** The startup pass, periodic checks, notifications and `client.fetch()` calls share one queue and are served one at a time in arrival order. Notifications and periodic checks that arrive while a discovery is running are merged into one pending request. -- **Safety in every mode.** With `syncPattern` `'push'`, `'hybrid'` or `'pull'`, the Client discovers work immediately after startup and then every `pullInterval`. Notifications only make discovery faster. Work whose notification was lost, work requeued by recovery, and work that becomes claimable after a group slot frees up or a job expires is found by the next periodic check. +- **Safety in every mode.** With `syncPattern` `'push'`, `'hybrid'` or `'pull'`, the Client discovers work immediately after startup and then every `pullInterval`. Notifications only make discovery faster. Work whose notification was lost, work requeued by recovery, and work that becomes claimable after a job expires or after another worker frees a group slot is found by the next periodic check. +- **Bursts and group-limited backlogs.** A claim that returns fewer than the notified jobs, typically because another worker's claim holds the other rows until it commits, is followed up once after a random 10–50 ms delay; two empty claims in a row end this. When a job settles that came from a claim that did not cover its request (for example one limited by its group's concurrency), this Client looks for work again, so a group-limited backlog drains as fast as its jobs finish instead of at the group limit per `pullInterval`. See [`batchSize`](/docs/client-api#batchsize). - **Automatic claim ceiling.** Automatic claims stop while this Client has `batchSize` claimed jobs outstanding (claimed, queued, running or finishing). See [`batchSize`](/docs/client-api#batchsize) for how this differs from `actionConcurrencyLimit` and SQL group limits. - **Recovery does not pause claiming.** When periodic recovery is due, it runs in the next discovery turn, also while this Client's jobs are running or the automatic claim ceiling is full, and that turn then claims as usual. Recovery and a claim never run at the same time in one Client. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs (see [Job Recovery](#job-recovery)). - **Failures.** After a failed discovery or recovery attempt, all discovery waits one `pullInterval`. Failed claims are never replayed. diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index c286e04..6eb8f4b 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -3,14 +3,14 @@ import type { Logger } from 'pino' import type { Job } from './adapters/adapter.js' import { type Lifecycle, isStopFailure } from './lifecycle.js' -export type DiscoveryTrigger = 'startup' | 'periodic' | 'hint' +export type DiscoveryTrigger = 'startup' | 'periodic' | 'hint' | 'settled' interface AutomaticRequest { kind: 'automatic' /** - * Jobs this request is for: one per hint, Infinity when startup or a periodic check - * asks for a backlog of unknown size, or what a full claim left uncovered. It claims - * min(B, demand, room). + * Jobs this request is for: one per hint, Infinity when startup, a periodic check or a + * settled job asks for a backlog of unknown size, or what a claim left uncovered. It + * claims min(B, demand, room). */ demand: number triggers: Set @@ -68,6 +68,11 @@ function monotonicMs(): number { const notAccepting = () => new Error('Lifecycle is not accepting work') +/** Delay of a follow-up after a short claim: 10–50 ms, random so peers do not align. */ +function shortClaimDelay(): number { + return 10 + Math.floor(Math.random() * 41) +} + /** * Client-local worker discovery coordinator (internal; not a public API). * @@ -80,6 +85,19 @@ const notAccepting = () => new Error('Lifecycle is not accepting work') * another automatic request for the rest of that demand, so a backlog keeps draining * without waiting for the periodic tick. A claim that covered all of its hints (for * example one job for one hint) is not followed up: later hints add their own demand. + * - A short claim (fewer jobs than its batch) while hinted demand remains usually means that + * peers' claims hold the other rows, not that the queue is empty: a claim locks every + * eligible row it sees (SKIP LOCKED) until it commits, so a concurrent claim can even + * return nothing. One follow-up for the rest of the demand is queued after a random + * 10–50 ms delay, once those claims have committed. After a claim that returned nothing, + * this happens only once in a row and only for more than one uncovered hint (a lone hint + * that a peer won is not retried); a second empty claim in a row ends it, so an empty + * queue is never polled. + * - A job from a claim that did not cover its demand requests discovery again when it + * settles locally (unbounded demand, coalesced; trigger `settled`): its settlement can free + * a slot of its SQL group (or local room), so a group-limited backlog drains at handler + * speed instead of at L jobs per pullInterval. Jobs of a claim that covered its demand + * (one job for one hint) do not, so sparse traffic costs no extra claims. * - Automatic claims use only the room left under a Client-wide ceiling of B outstanding * local claims (claimed, queued, running and finalizing work, plus reservations). Manual * calls keep their own batch and returned jobs and may exceed B. @@ -108,6 +126,14 @@ export class WorkerDiscovery { #local = new Set>() #tick: ReturnType | null = null #wake: ReturnType | null = null + /** An empty claim was already followed up; the next empty claim ends the follow-ups. */ + #emptyFollowedUp = false + /** The pending follow-up of short claims (see `#followShortClaim`). */ + #shortFollowUp: { + timer: ReturnType + demand: number + triggers: Set + } | null = null constructor(options: WorkerDiscoveryOptions) { this.#options = options @@ -153,8 +179,10 @@ export class WorkerDiscovery { this.#stopped = true if (this.#tick) clearTimeout(this.#tick) if (this.#wake) clearTimeout(this.#wake) + if (this.#shortFollowUp) clearTimeout(this.#shortFollowUp.timer) this.#tick = null this.#wake = null + this.#shortFollowUp = null const queued = this.#queue this.#queue = [] this.#automatic = null @@ -271,22 +299,37 @@ export class WorkerDiscovery { // Transfer the reservation into local accounting without a gap or double count. this.#reserved -= reserved reserved = 0 + const got = claimed.jobs.length + // A claim that did not cover its demand (a manual call: its batch) suggests more + // claimable work behind SQL group limits or local room: its jobs wake discovery when + // they settle. + const wake = got < (request.kind === 'manual' ? request.batch : request.demand) try { if (!this.#stopped && this.#options.lifecycle.accepting) { - for (const job of claimed.jobs) this.#track(claimed.dispatch(job)) + for (const job of claimed.jobs) this.#track(claimed.dispatch(job), wake) } } finally { claimed.release() } if (request.kind === 'manual') { request.resolve(claimed.jobs) - } else if (claimed.jobs.length >= batch && request.demand > batch && this.#open) { + } else if (got >= batch && request.demand > batch && this.#open) { // A full claim that did not cover the demand (B or room limited it, or the // backlog size is unknown) suggests more claimable work. The follow-up waits for // room, cooldown and due recovery like any automatic request. A claim that // covered all of its hints (one job for one hint) is not followed up. The // follow-up keeps the uncovered demand (unbounded stays unbounded). this.#mergeAutomatic(request.demand - batch, request.triggers) + } else if (Number.isFinite(request.demand) && request.demand > got) { + if (got > 0) { + this.#emptyFollowedUp = false + this.#followShortClaim(request.demand - got, request.triggers) + } else if (!this.#emptyFollowedUp && request.demand > 1) { + this.#emptyFollowedUp = true + this.#followShortClaim(request.demand, request.triggers) + } + } else if (got > 0) { + this.#emptyFollowedUp = false } } catch (error) { this.#cooldownUntil = monotonicMs() + this.#interval @@ -310,10 +353,40 @@ export class WorkerDiscovery { } } - #track(settlement: Promise): void { + /** + * A short (or empty) claim left hinted demand uncovered: peers' claims probably hold those + * rows. Ask again after a short random delay, once their transactions have committed. Only finite + * (hinted) demand is followed: unbounded demand has no evidence of more jobs, and its + * jobs' settlement wakes cover a group-limited backlog. Concurrent follow-ups merge. + */ + #followShortClaim(demand: number, triggers: Iterable): void { + if (!this.#open) return + if (this.#shortFollowUp) { + this.#shortFollowUp.demand += demand + for (const trigger of triggers) this.#shortFollowUp.triggers.add(trigger) + return + } + const followUp = { + demand, + triggers: new Set(triggers), + timer: setTimeout(() => { + this.#shortFollowUp = null + if (!this.#open) return + this.#mergeAutomatic(followUp.demand, followUp.triggers) + this.#pump() + }, shortClaimDelay()), + } + this.#shortFollowUp = followUp + } + + #track(settlement: Promise, wake: boolean): void { this.#local.add(settlement) void settlement.finally(() => { this.#local.delete(settlement) + // The settlement can free a slot of the job's SQL group: look for more work. + if (wake && this.#options.automatic && this.#open) { + this.#mergeAutomatic(Infinity, ['settled']) + } this.#pump() }) } diff --git a/packages/duron/test/discovery-throughput.test.ts b/packages/duron/test/discovery-throughput.test.ts new file mode 100644 index 0000000..640106e --- /dev/null +++ b/packages/duron/test/discovery-throughput.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it } from 'bun:test' + +import { defineAction } from '../src/action.js' +import type { Adapter } from '../src/adapters/adapter.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' + +// Discovery throughput without the periodic tick: every test uses a pullInterval far longer +// than the time the work needs, so only hints, follow-ups and settlement wakes can claim it. + +const PULL_INTERVAL = 5_000 + +// Observational: count Adapter.fetch calls and the jobs they returned. +function countFetches(adapter: Adapter) { + const real = adapter.fetch.bind(adapter) + const stats = { calls: 0, empty: 0, jobs: 0 } + adapter.fetch = async (options) => { + stats.calls++ + const jobs = await real(options) + stats.jobs += jobs.length + if (jobs.length === 0) stats.empty++ + return jobs + } + return stats +} + +async function until(check: () => boolean, ms: number) { + const end = performance.now() + ms + while (!check() && performance.now() < end) await Bun.sleep(10) +} + +const factories: AdapterFactory[] = [ + pgliteFactory, + ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), +] + +for (const factory of factories) { + describe(`Discovery throughput with ${factory.name}`, () => { + // A completed job frees a slot of its SQL group. Without a wake on settlement, a + // group-limited backlog drains at L jobs per pullInterval (200 / 3 * 5 s here). + for (const source of ['hints', 'backlog'] as const) { + it(`drains a group-limited ${source === 'hints' ? 'burst' : 'backlog'} at handler speed`, async () => { + const instance = await factory.create() + const jobs = 200 + let client: Client | null = null + let done = 0 + let running = 0 + let peak = 0 + const action = defineAction()({ + name: 'grouped', + groups: { groupKey: async () => 'limited', concurrency: async () => 3 }, + handler: async () => { + running++ + peak = Math.max(peak, running) + await Bun.sleep(20) + running-- + done++ + return {} + }, + }) + try { + const fetches = countFetches(instance.adapter) + client = new Client({ + database: instance.adapter, + actions: { grouped: action }, + syncPattern: 'hybrid', + pullInterval: PULL_INTERVAL, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + expect(await instance.adapter.start()).toBe(true) + if (source === 'backlog') { + for (let i = 0; i < jobs; i++) { + await instance.adapter.createJob({ + queue: action.name, + groupKey: 'limited', + input: {}, + timeoutMs: 60_000, + checksum: action.checksum, + concurrencyLimit: 3, + concurrencyStepLimit: 10, + description: null, + }) + } + } + expect(await client.start()).toBe(true) + const begun = performance.now() + if (source === 'hints') { + await Promise.all(Array.from({ length: jobs }, () => client!.runAction('grouped', {}))) + } + await until(() => done === jobs, 30_000) + const elapsed = performance.now() - begun + expect(done).toBe(jobs) + expect(peak).toBeLessThanOrEqual(3) + // At handler speed (about 67 rounds of 20 ms), not 67 periodic ticks. + expect(elapsed).toBeLessThan(15_000) + // Claim traffic stays about one claim per freed slot, not a busy loop... + expect(fetches.calls).toBeLessThan(jobs * 2) + // ...and stops once the queue is empty. + await Bun.sleep(200) + const settled = fetches.calls + await Bun.sleep(300) + expect(fetches.calls).toBe(settled) + } finally { + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 40_000) + } + }) +} + +// Several workers on one database: a claim that returns fewer jobs than requested because +// peers hold the rows (SKIP LOCKED) must not drop the rest of a burst until the periodic tick. +if (process.env['POSTGRES_TEST'] === 'true') { + describe('Discovery throughput with several postgres workers', () => { + // Short handlers: settlement wakes also find the rest of a burst. Long handlers (longer + // than half of pullInterval, with room for the whole burst): no job settles before the + // check, so only the follow-up of a short claim can find the rest in time. + for (const [handlerMs, batchSize] of [ + [20, 10], + [3_000, 100], + ] as const) { + it(`starts every job of repeated 300-job bursts on 4 workers well before pullInterval (${handlerMs} ms jobs)`, async () => { + const instance = await postgresFactory.create() + const adapters: Adapter[] = [instance.adapter] + for (let i = 1; i < 4; i++) { + adapters.push(new PostgresAdapter({ connection: instance.connectionUrl })) + } + const clients: Client[] = [] + let begun = 0 + let starts: number[] = [] + const action = defineAction()({ + name: 'burst', + groups: { concurrency: async () => 10_000 }, + handler: async () => { + starts.push(performance.now() - begun) + await Bun.sleep(handlerMs) + return {} + }, + }) + try { + for (const [index, adapter] of adapters.entries()) { + clients.push( + new Client({ + id: `burst-worker-${index}-${crypto.randomUUID()}`, + database: adapter, + actions: { burst: action }, + syncPattern: 'hybrid', + pullInterval: PULL_INTERVAL, + batchSize, + actionConcurrencyLimit: 300, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }), + ) + } + for (const client of clients) expect(await client.start()).toBe(true) + await Bun.sleep(200) + const latest: number[] = [] + for (let round = 0; round < 10; round++) { + starts = [] + begun = performance.now() + await Promise.all( + Array.from({ length: 300 }, (_, i) => + clients[i % clients.length]!.runAction('burst', {}), + ), + ) + await until(() => starts.length >= 300, PULL_INTERVAL * 2) + expect(starts.length).toBe(300) + latest.push(Math.round(Math.max(...starts))) + // The next burst starts on idle workers. + await Bun.sleep(handlerMs + 200) + } + // A part of a burst left for the periodic tick would start at about PULL_INTERVAL. + expect(latest.filter((ms) => ms >= PULL_INTERVAL / 2)).toEqual([]) + } finally { + for (const client of clients) await client.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 120_000) + } + }) +} diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index d982e52..d8f7ea2 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -566,9 +566,10 @@ for (const factory of factories) { fetch.releaseNext() await eventually(() => fetch.batches.length === 2, 'one follow-up') fetch.releaseAll() - await Bun.sleep(50) - // Both claims return empty (not full), so no further automatic claim follows. - expect(fetch.batches).toEqual([4, followUp]) + await Bun.sleep(200) + // Both claims return empty (not full). The empty hinted claim is retried once after + // 10–50 ms (peers' claims could have held the rows); its empty retry ends it. + expect(fetch.batches).toEqual([4, followUp, followUp]) expect(fetch.maxActive).toBe(1) } finally { fetch.releaseAll() @@ -579,6 +580,57 @@ for (const factory of factories) { ) } + it( + 'does not retry an empty claim for a lone hint, and stop cancels a pending retry (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + try { + const action = defineAction()({ name: 'hinted', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { hinted: action }, + syncPattern: 'push', + pullInterval: 60_000, + batchSize: 4, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await eventually(() => fetch.held === 1, 'startup pass is held') + fetch.releaseNext() + await eventually(() => fetch.active === 0, 'startup pass settles') + // A lone hint whose job is gone (for example a peer claimed it): no retry. + instance.adapter.emit('job-available', { jobId: 'lone' }) + await eventually(() => fetch.held === 1, 'the hinted claim is held') + fetch.releaseNext() + await eventually(() => fetch.active === 0, 'the hinted claim settles') + await Bun.sleep(150) + expect(fetch.batches).toEqual([4, 1]) + // One hint, then two merged hints: the claim for the two returns nothing and + // schedules one retry; stop cancels it before it runs. + instance.adapter.emit('job-available', { jobId: 'a' }) + await eventually(() => fetch.held === 1, 'the claim for one hint is held') + instance.adapter.emit('job-available', { jobId: 'b' }) + instance.adapter.emit('job-available', { jobId: 'c' }) + fetch.releaseNext() + await eventually(() => fetch.held === 1, 'the claim for two hints is held') + fetch.releaseNext() + await eventually(() => fetch.active === 0, 'the claim for two hints settles') + const stopping = client.stop() + await Bun.sleep(150) + expect(fetch.batches).toEqual([4, 1, 1, 2]) + fetch.releaseAll() + expect(await stopping).toBe(true) + } finally { + fetch.releaseAll() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + it( 'follows a full automatic claim with another one until a claim is not full (public-only)', async () => { @@ -637,10 +689,16 @@ for (const factory of factories) { await Bun.sleep(100) expect(ran).toBe(5) // Each full claim is followed by another one within the room left under B; the - // first claim that returns less than its batch ends the drain. + // first claim that returns less than its batch ends the follow-ups. After it, the + // settlement of a job from an uncovered claim may look once more (it can free a + // SQL group slot); with the backlog drained, such a claim finds nothing. expect(batches.every((batch) => batch >= 1 && batch <= 2)).toBe(true) - expect(claimed.slice(0, -1)).toEqual(batches.slice(0, -1)) - expect(claimed.at(-1)!).toBeLessThan(batches.at(-1)!) + const short = claimed.findIndex((n, i) => n < batches[i]!) + expect(short).toBeGreaterThan(0) + expect(claimed.slice(0, short)).toEqual(batches.slice(0, short)) + const after = claimed.slice(short + 1) + expect(after.every((n) => n === 0)).toBe(true) + expect(after.length).toBeLessThanOrEqual(5) expect(claimed.reduce((sum, n) => sum + n, 0)).toBe(5) } finally { await closeInstance(client, instance) From 2ef4fb3808eeb87103cfbbdda165e4db1359cdc6 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 19:41:53 -0300 Subject: [PATCH 084/100] fix(discovery): re-arm empty-claim retries per hint; keep waking while demand is uncovered R1: the empty-claim retry flag stayed set after a burst, so the next burst's empty claims were never retried. A new hint (a new created job) now resets it. Tracing the native 4-worker 3000 ms test showed a second cause: after the last hint, a worker's single retry can collide with a peer's next small claim, which locks every remaining eligible row (2 of 200 rounds still started jobs at ~3.17 s). Empty claims are now followed up at most twice in a row, the second time after 50-250 ms; a third empty claim ends it. With both: 20 of 20 runs (200 rounds) pass, max start 263 ms. R2: the settlement wake was per claim. When the claim that got the local jobs covered its own hints and the claims for the rest came back empty (group full), the backlog waited for the periodic tick. A Client-level #uncovered flag is set when an automatic claim gets less than its demand (except an unbounded claim that found nothing, which clears it, as does a covered claim); while it is set, every local settlement wakes discovery. Tests: discovery-throughput adds a limit 1 burst (200 ms jobs) and a limit 3 sequential creation (300 ms jobs), PGlite + native; each must finish within ideal + pullInterval / 2 (before: 7.4 s / 5.9 s; now ~3.2 s / ~1.8 s). worker-discovery adds 'a new hint allows the empty-claim retries again'; coalesce and retry expectations updated for the second retry. Mutants caught: no hint reset, no #uncovered, unbounded empty retries. Docs: client-api batchSize and multi-worker Worker Discovery describe the final rules (a slot freed by another worker is found by that worker or the periodic check). Comment at _claimQuery: candidate_jobs locks the whole eligible backlog (follow-up). --- packages/docs/content/docs/client-api.mdx | 2 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/duron/src/adapters/postgres/base.ts | 9 +++ packages/duron/src/worker-discovery.ts | 68 +++++++++++++------ .../duron/test/discovery-throughput.test.ts | 54 +++++++++++++++ packages/duron/test/worker-discovery.test.ts | 58 ++++++++++++++-- 6 files changed, 168 insertions(+), 25 deletions(-) diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 5fb0663..c7317d4 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -127,7 +127,7 @@ Periodic discovery is not reset or postponed by notifications or `fetch()` calls **Optional.** Defaults to `10`. Two meanings: -- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Notifications add up: the first one starts an automatic request for one job, and each later notification adds one job to it while it waits (behind a running discovery, for a cooldown, or for room). Startup and periodic checks make the request open-ended. Each claim takes at most B jobs and at most the remaining room. When a claim returns as many jobs as it asked for but did not cover the whole request (more notifications than one claim could take, or an open-ended request), another automatic request for the rest follows at once, so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. That follow-up waits for room and for a cooldown like any automatic request, and a due recovery runs before it claims. A claim that covered all of its notifications, such as one job for one notification, is not followed up. A claim that returned fewer jobs than it asked for, while notifications are still uncovered, is followed up once after a random 10–50 ms delay: with several workers, the other rows are usually held by another worker's claim, which locks every eligible row it sees (`SKIP LOCKED`) until it commits, so a concurrent claim can even return nothing. After a claim that returned nothing, this happens only for more than one uncovered notification and only once in a row: a second empty claim in a row ends these follow-ups, so an empty queue is not polled, and a lone notification whose job another worker claimed is not retried. When a job from a claim that did not cover its request (for example a claim limited by its SQL group's concurrency) settles on this Client, it starts an open-ended automatic request, because its settlement can free a group slot; a group-limited backlog therefore drains as fast as its jobs finish, not at the group limit per `pullInterval`. Jobs from a claim that covered its notifications do not, so sparse traffic costs no extra claims. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. +- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Notifications add up: the first one starts an automatic request for one job, and each later notification adds one job to it while it waits (behind a running discovery, for a cooldown, or for room). Startup and periodic checks make the request open-ended. Each claim takes at most B jobs and at most the remaining room. When a claim returns as many jobs as it asked for but did not cover the whole request (more notifications than one claim could take, or an open-ended request), another automatic request for the rest follows at once, so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. That follow-up waits for room and for a cooldown like any automatic request, and a due recovery runs before it claims. A claim that covered all of its notifications, such as one job for one notification, is not followed up. A claim that returned fewer jobs than it asked for, while notifications are still uncovered, is followed up once after a random 10–50 ms delay: with several workers, the other rows are usually held by another worker's claim, which locks every eligible row it sees (`SKIP LOCKED`) until it commits, so a concurrent claim can even return nothing. After a claim that returned nothing, this happens only for more than one uncovered notification and at most twice in a row (the second time after 50–250 ms): a third empty claim in a row ends these follow-ups, so an empty queue is not polled, and a lone notification whose job another worker claimed is not retried. A new notification or a claim that returns jobs allows them again. While this Client's last automatic claim left jobs uncovered (for example because their SQL group was full), every job that settles on this Client starts an open-ended automatic request, because its settlement can free a group slot; a job from a claim that did not cover its own request does so too. A backlog limited by a group that this Client's jobs fill therefore drains about as fast as those jobs finish, not at the group limit per `pullInterval`. A slot that another worker frees is found by that worker's own claims or by the next periodic check. A claim that covers its request, or an open-ended claim that finds nothing, ends this, so sparse traffic costs at most one extra claim, after a notification another worker won. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. - **Default `fetch()` batch.** `fetch()` without `batchSize` passes this value unchanged. B is not the number of handlers that run at once. That is `actionConcurrencyLimit` per action, so with the defaults (B = 10, `actionConcurrencyLimit` = 100) at most ten automatically claimed jobs are outstanding. SQL group admission (`groupConcurrencyLimit` or `groups.concurrency`) is a separate limit across all workers. Jobs claimed by `fetch()` count toward B, and a `fetch()` batch can exceed B; automatic claiming then pauses until enough work settles. B limits claim admission only. It does not bound the rows that recovery examines, the backlog that manual calls create, or the total query rate. diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 4978d46..3337405 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -250,7 +250,7 @@ Each Client with actions coordinates its own job discovery: - **One discovery at a time.** The startup pass, periodic checks, notifications and `client.fetch()` calls share one queue and are served one at a time in arrival order. Notifications and periodic checks that arrive while a discovery is running are merged into one pending request. - **Safety in every mode.** With `syncPattern` `'push'`, `'hybrid'` or `'pull'`, the Client discovers work immediately after startup and then every `pullInterval`. Notifications only make discovery faster. Work whose notification was lost, work requeued by recovery, and work that becomes claimable after a job expires or after another worker frees a group slot is found by the next periodic check. -- **Bursts and group-limited backlogs.** A claim that returns fewer than the notified jobs, typically because another worker's claim holds the other rows until it commits, is followed up once after a random 10–50 ms delay; two empty claims in a row end this. When a job settles that came from a claim that did not cover its request (for example one limited by its group's concurrency), this Client looks for work again, so a group-limited backlog drains as fast as its jobs finish instead of at the group limit per `pullInterval`. See [`batchSize`](/docs/client-api#batchsize). +- **Bursts and group-limited backlogs.** A claim that returns fewer than the notified jobs, typically because another worker's claim holds the other rows until it commits, is followed up after a random 10–50 ms delay; empty claims are followed up at most twice in a row. While this Client's claims leave jobs uncovered (for example because their group is full), each of its jobs that settles makes it look for work again, so a backlog limited by a group that this Client's jobs fill drains about as fast as they finish instead of at the group limit per `pullInterval`. A group slot freed by another worker is found by that worker or by the next periodic check. See [`batchSize`](/docs/client-api#batchsize). - **Automatic claim ceiling.** Automatic claims stop while this Client has `batchSize` claimed jobs outstanding (claimed, queued, running or finishing). See [`batchSize`](/docs/client-api#batchsize) for how this differs from `actionConcurrencyLimit` and SQL group limits. - **Recovery does not pause claiming.** When periodic recovery is due, it runs in the next discovery turn, also while this Client's jobs are running or the automatic claim ceiling is full, and that turn then claims as usual. Recovery and a claim never run at the same time in one Client. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs (see [Job Recovery](#job-recovery)). - **Failures.** After a failed discovery or recovery attempt, all discovery waits one `pullInterval`. Failed claims are never replayed. diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index a07a085..c5e319a 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -1452,6 +1452,15 @@ export abstract class PostgresBaseAdapter< } } + /** + * The claim statement. Note: `candidate_jobs` locks every eligible created row (FOR UPDATE + * SKIP LOCKED without a LIMIT; `ranked_jobs` needs the whole set), and the LIMIT applies only + * in `next_job`. So one claim, even of one job, locks the whole eligible backlog until it + * commits: concurrent claims of other workers return few or no jobs meanwhile (worker + * discovery follows such claims up), and each claim writes a row lock on every eligible + * row. Locking only the rows a claim can take, without head-of-line blocking by full + * groups, is a possible follow-up. + */ private _claimQuery(batch: number): SQL { return sql` WITH group_concurrency AS ( diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index 6eb8f4b..ff91e80 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -68,9 +68,15 @@ function monotonicMs(): number { const notAccepting = () => new Error('Lifecycle is not accepting work') -/** Delay of a follow-up after a short claim: 10–50 ms, random so peers do not align. */ -function shortClaimDelay(): number { - return 10 + Math.floor(Math.random() * 41) +/** Empty claims in a row that are followed up (see `WorkerDiscovery`). */ +const EMPTY_CLAIM_RETRIES = 2 + +/** + * Delay of a follow-up after a short claim, random so peers do not align: 10–50 ms, and + * five times as long for each empty claim already followed up in a row (50–250 ms). + */ +function shortClaimDelay(emptyRetries: number): number { + return (10 + Math.floor(Math.random() * 41)) * 5 ** emptyRetries } /** @@ -90,14 +96,19 @@ function shortClaimDelay(): number { * eligible row it sees (SKIP LOCKED) until it commits, so a concurrent claim can even * return nothing. One follow-up for the rest of the demand is queued after a random * 10–50 ms delay, once those claims have committed. After a claim that returned nothing, - * this happens only once in a row and only for more than one uncovered hint (a lone hint - * that a peer won is not retried); a second empty claim in a row ends it, so an empty - * queue is never polled. - * - A job from a claim that did not cover its demand requests discovery again when it - * settles locally (unbounded demand, coalesced; trigger `settled`): its settlement can free - * a slot of its SQL group (or local room), so a group-limited backlog drains at handler - * speed instead of at L jobs per pullInterval. Jobs of a claim that covered its demand - * (one job for one hint) do not, so sparse traffic costs no extra claims. + * this happens only for more than one uncovered hint (a lone hint that a peer won is not + * retried) and at most twice in a row, the second time after 50–250 ms (a peer's next + * small claim can lock the rest again); a third empty claim in a row ends it, so an empty + * queue is never polled. A claim that returns jobs, or a new hint, resets the count. + * - Demand becomes unbounded once a settlement or a periodic check merges into it; from then + * on only settlement wakes, not short-claim follow-ups, look for the rest. + * - A local job requests discovery again when it settles (unbounded demand, coalesced; + * trigger `settled`) if its own claim did not cover its demand, or while the last + * automatic claim left demand uncovered (`#uncovered`): its settlement can free a slot of + * its SQL group (or local room), so a backlog behind a group that this Client's jobs fill + * drains at handler speed instead of at L jobs per pullInterval. A covered claim, or an + * unbounded claim that found nothing, clears `#uncovered`, so sparse traffic costs at most + * one extra claim (after a hint that a peer won). * - Automatic claims use only the room left under a Client-wide ceiling of B outstanding * local claims (claimed, queued, running and finalizing work, plus reservations). Manual * calls keep their own batch and returned jobs and may exceed B. @@ -126,8 +137,18 @@ export class WorkerDiscovery { #local = new Set>() #tick: ReturnType | null = null #wake: ReturnType | null = null - /** An empty claim was already followed up; the next empty claim ends the follow-ups. */ - #emptyFollowedUp = false + /** + * Empty claims in a row already followed up; at EMPTY_CLAIM_RETRIES the next empty claim + * ends the follow-ups. A claim that returns jobs, or a new hint (a new created job), resets + * it. + */ + #emptyRetries = 0 + /** + * The last automatic claim that decided it left demand uncovered (fewer jobs than its + * demand). Cleared by a claim that covered its demand or an unbounded claim that returned + * nothing. While set, every local settlement wakes discovery (see `#track`). + */ + #uncovered = false /** The pending follow-up of short claims (see `#followShortClaim`). */ #shortFollowUp: { timer: ReturnType @@ -160,6 +181,8 @@ export class WorkerDiscovery { /** Merge automatic demand. Each hint adds one job; startup/periodic make it unbounded. */ request(trigger: DiscoveryTrigger): void { if (!this.#options.automatic || this.#stopped || !this.#options.lifecycle.accepting) return + // A hint is a new created job: its empty claim may be followed up again. + if (trigger === 'hint') this.#emptyRetries = 0 this.#mergeAutomatic(trigger === 'hint' ? 1 : Infinity, [trigger]) this.#pump() } @@ -304,6 +327,13 @@ export class WorkerDiscovery { // claimable work behind SQL group limits or local room: its jobs wake discovery when // they settle. const wake = got < (request.kind === 'manual' ? request.batch : request.demand) + if (request.kind === 'automatic') { + // Hinted jobs this claim did not get may wait behind a full SQL group, even when the + // claim that got the local jobs covered its own hints: then every local settlement + // must look again. A covered claim, or an unbounded claim that found nothing, clears + // it (a backlog of unknown size is gone). + this.#uncovered = got < request.demand && (got > 0 || Number.isFinite(request.demand)) + } try { if (!this.#stopped && this.#options.lifecycle.accepting) { for (const job of claimed.jobs) this.#track(claimed.dispatch(job), wake) @@ -322,14 +352,14 @@ export class WorkerDiscovery { this.#mergeAutomatic(request.demand - batch, request.triggers) } else if (Number.isFinite(request.demand) && request.demand > got) { if (got > 0) { - this.#emptyFollowedUp = false + this.#emptyRetries = 0 this.#followShortClaim(request.demand - got, request.triggers) - } else if (!this.#emptyFollowedUp && request.demand > 1) { - this.#emptyFollowedUp = true + } else if (this.#emptyRetries < EMPTY_CLAIM_RETRIES && request.demand > 1) { this.#followShortClaim(request.demand, request.triggers) + this.#emptyRetries++ } } else if (got > 0) { - this.#emptyFollowedUp = false + this.#emptyRetries = 0 } } catch (error) { this.#cooldownUntil = monotonicMs() + this.#interval @@ -374,7 +404,7 @@ export class WorkerDiscovery { if (!this.#open) return this.#mergeAutomatic(followUp.demand, followUp.triggers) this.#pump() - }, shortClaimDelay()), + }, shortClaimDelay(this.#emptyRetries)), } this.#shortFollowUp = followUp } @@ -384,7 +414,7 @@ export class WorkerDiscovery { void settlement.finally(() => { this.#local.delete(settlement) // The settlement can free a slot of the job's SQL group: look for more work. - if (wake && this.#options.automatic && this.#open) { + if ((wake || this.#uncovered) && this.#options.automatic && this.#open) { this.#mergeAutomatic(Infinity, ['settled']) } this.#pump() diff --git a/packages/duron/test/discovery-throughput.test.ts b/packages/duron/test/discovery-throughput.test.ts index 640106e..f680406 100644 --- a/packages/duron/test/discovery-throughput.test.ts +++ b/packages/duron/test/discovery-throughput.test.ts @@ -110,6 +110,60 @@ for (const factory of factories) { } }, 40_000) } + + // The claims that got jobs covered their own hints, and the claims for the other hints + // came back empty because the group was full: the settling jobs must still look again. + for (const [limit, creation, handlerMs] of [ + [1, 'burst', 200], + [3, 'sequential', 300], + ] as const) { + it(`drains a small group-limited ${creation} (limit ${limit}, ${handlerMs} ms jobs) without the periodic tick`, async () => { + const instance = await factory.create() + const jobs = 12 + let client: Client | null = null + let done = 0 + const action = defineAction()({ + name: 'small-group', + groups: { groupKey: async () => 'small', concurrency: async () => limit }, + handler: async () => { + await Bun.sleep(handlerMs) + done++ + return {} + }, + }) + try { + client = new Client({ + database: instance.adapter, + actions: { 'small-group': action }, + syncPattern: 'hybrid', + pullInterval: PULL_INTERVAL, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await Bun.sleep(100) + const begun = performance.now() + if (creation === 'burst') { + await Promise.all( + Array.from({ length: jobs }, () => client!.runAction('small-group', {})), + ) + } else { + for (let i = 0; i < jobs; i++) await client.runAction('small-group', {}) + } + await until(() => done === jobs, 30_000) + const elapsed = performance.now() - begun + expect(done).toBe(jobs) + // Handler speed is jobs / limit * handlerMs (2.4 s and 1.2 s); a wait for the + // periodic tick adds about PULL_INTERVAL. + const ideal = (jobs / limit) * handlerMs + expect(elapsed).toBeLessThan(ideal + PULL_INTERVAL / 2) + } finally { + await client?.stop().catch(() => undefined) + await instance.deleteDb() + } + }, 40_000) + } }) } diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index d8f7ea2..72ddf8c 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -566,10 +566,11 @@ for (const factory of factories) { fetch.releaseNext() await eventually(() => fetch.batches.length === 2, 'one follow-up') fetch.releaseAll() - await Bun.sleep(200) - // Both claims return empty (not full). The empty hinted claim is retried once after - // 10–50 ms (peers' claims could have held the rows); its empty retry ends it. - expect(fetch.batches).toEqual([4, followUp, followUp]) + await Bun.sleep(600) + // Both claims return empty (not full). The empty hinted claim is retried after + // 10–50 ms and once more after 50–250 ms (peers' claims could have held the rows); + // a third empty claim in a row ends it. + expect(fetch.batches).toEqual([4, followUp, followUp, followUp]) expect(fetch.maxActive).toBe(1) } finally { fetch.releaseAll() @@ -631,6 +632,55 @@ for (const factory of factories) { TEST_MS, ) + it( + 'a new hint allows the empty-claim retries again after a burst used them up (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + // One hint whose claim is held, then two more hints merged behind it; every claim is + // released in turn and returns nothing (the hinted jobs do not exist). + const burst = async (ids: [string, string, string], claims: number) => { + instance.adapter.emit('job-available', { jobId: ids[0] }) + await eventually(() => fetch.held === 1, 'the claim for one hint is held') + instance.adapter.emit('job-available', { jobId: ids[1] }) + instance.adapter.emit('job-available', { jobId: ids[2] }) + for (let i = 0; i < claims; i++) { + await eventually(() => fetch.held === 1, `claim ${i + 1} is held`) + fetch.releaseNext() + } + await eventually(() => fetch.active === 0, 'the burst settles') + await Bun.sleep(400) + } + try { + const action = defineAction()({ name: 'hinted', handler: async () => ({}) }) + client = new Client({ + database: instance.adapter, + actions: { hinted: action }, + syncPattern: 'push', + pullInterval: 60_000, + batchSize: 4, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await eventually(() => fetch.held === 1, 'startup pass is held') + fetch.releaseNext() + await eventually(() => fetch.active === 0, 'startup pass settles') + // The claim for two hints is empty: two retries, the third empty claim ends it. + await burst(['a', 'b', 'c'], 4) + expect(fetch.batches).toEqual([4, 1, 2, 2, 2]) + // A later burst gets its own retries. + await burst(['d', 'e', 'f'], 4) + expect(fetch.batches).toEqual([4, 1, 2, 2, 2, 1, 2, 2, 2]) + } finally { + fetch.releaseAll() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + it( 'follows a full automatic claim with another one until a claim is not full (public-only)', async () => { From e40d50d7f7efa17b87a7a447739e7c160e5a1de8 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Tue, 1 Dec 2026 20:17:43 -0300 Subject: [PATCH 085/100] test: settle past the empty-claim retry tail before the idle check (R2B recheck R3) --- packages/duron/test/discovery-throughput.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/duron/test/discovery-throughput.test.ts b/packages/duron/test/discovery-throughput.test.ts index f680406..05eca98 100644 --- a/packages/duron/test/discovery-throughput.test.ts +++ b/packages/duron/test/discovery-throughput.test.ts @@ -99,8 +99,9 @@ for (const factory of factories) { expect(elapsed).toBeLessThan(15_000) // Claim traffic stays about one claim per freed slot, not a busy loop... expect(fetches.calls).toBeLessThan(jobs * 2) - // ...and stops once the queue is empty. - await Bun.sleep(200) + // ...and stops once the queue is empty. The bounded tail of empty-claim retries ends + // within about 300 ms (10-50 ms, then 50-250 ms), so settle past it first. + await Bun.sleep(500) const settled = fetches.calls await Bun.sleep(300) expect(fetches.calls).toBe(settled) From 0d00131370e3869e545cd480c5208db7b101dbfd Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Wed, 2 Dec 2026 14:57:45 -0300 Subject: [PATCH 086/100] ci: run the test workflow for pull requests into any branch (stacked PRs) --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 86f4c29..8424274 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,8 +2,8 @@ name: Tests on: push: branches: [main] + # Every pull request, including stacked PRs that target another branch. pull_request: - branches: [main] # Bun 1.4.5 is the first stable release used here with `bun check` (the typecheck script). # Keep it pinned so a new Bun release cannot change CI results on its own. From 4021c4392c276c59b1a8d6aa4f961d2783fdcae3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=ADn=20Acosta?= Date: Wed, 2 Dec 2026 20:10:42 -0300 Subject: [PATCH 087/100] PR #9 follow-ups: claim locking, release on stop, faster tests, refactors (#10) * perf(claim): lock only claimed jobs and serialize claims with a claim lock - Claim query selects first and locks last: per eligible group its oldest free-slot jobs (no locks), then LIMIT batch FOR UPDATE SKIP LOCKED in global creation order. Full groups never block younger jobs of other groups. Group limits via hash aggregation instead of a table sort. 50k backlog: 140-173 ms / 2.8 MB WAL per claim -> 17-57 ms / 12-19 KB. - New empty claim_lock table (migration). Each claim takes LOCK TABLE claim_lock IN EXCLUSIVE MODE before its statement (no snapshot), so built-in claims run one at a time and do not abort each other with 40001. lock_timeout 1 s; 55P03 is an empty claim (debug log, no retry, no cooldown). SERIALIZABLE + 40001 retries stay as safety net. - Worker discovery no longer follows up a short claim that returned jobs (redundant with settlement wakes); empty-claim follow-ups stay. - Docs: claim admission, discovery, claim_lock migration note. * fix(claim): end a stalled claim_lock holder and document the claim lock (F1 review) - R1: the claim transaction sets SET LOCAL idle_in_transaction_session_timeout = '5s' (PostgreSQL adapter). A worker that stalls between LOCK and COMMIT is ended by the server (25P03), its claim rolls back, and the claim lock is free: a fleet-wide claim stall lasts ~5 s instead of until TCP keepalive. A normal claim is idle only for round trips; the timer does not run during statements or lock waits. PGlite skips it (one in-process session; the timeout stops the engine). Native test: a relay withholds the LOCK reply of one claim; other claims return empty, then claim at ~5 s; 25P03 seen; both settings stay LOCAL. Fails without the setting. - A1: 55P03 debug log no longer claims it is always the claim lock. - R2: adapters.mdx documents GRANT UPDATE on claim_lock for separate worker roles (42501 otherwise; verified on PG19). - A2: multi-worker.mdx documents the per-schema claim rate ceiling (~17-60 claims/s at a 50k backlog, hundreds/s on small backlogs). - A3: rolling upgrade with old and new workers is safe; can be slower. - A4: fix stale worker-discovery comment; held test pins that a short claim that returned jobs is not followed up and its settlement looks again (fails on 2764089). * feat(stop): shutdownTimeout option; graceful stop releases unfinished jobs - Client option shutdownTimeout (ms, integer 1..2147483647, default 5000) sets the budget of every stop phase (lifecycle) of the Client's adapter; stop errors now read "exceeded the shutdown timeout (N ms)". - BREAKING: stop() releases instead of cancelling. Running handlers are aborted; after the handler settles, a resolved handler completes its job, otherwise the job is released (Adapter.releaseJob: created, owner, start and expiry cleared, job-available notification). Steps keep their stored status like recovery (completed reused; active re-run, retries_count back to 0). Claimed-but-unstarted jobs (queued, or claim reply after stop) are released too. Explicit cancelJob still cancels; a job whose handler awaits stop() is cancelled so it does not stop the next worker. A handler that never settles within the budget stays active for recovery. - Default Adapter._releaseJob returns false (custom adapters unchanged). - Tests: shutdown-release (PGlite + native, multi-worker handoff), and budget-bound tests use a short shutdownTimeout (11 files 355 s -> 155 s). - Docs: shutdownTimeout, stop() release semantics + breaking note, lifecycle phases, custom adapters. * fix(stop): keep a job's outcome, liveness and step statuses on release (F2 review) - R1: release() does nothing for a job an earlier abort already ends (failed handler, timeout, cancel): it is failed/cancelled, not released, and its steps are written. An invalid output during stop fails the job. - R2: steps that a release left unwritten are written (cancelled/failed) before a job that still completes or fails, so no finished job keeps an active step. - R3: the Client keeps heartbeating during the admitted-work drain until its jobs ended (no beat after the drain phase), and a job is released only once its handler and step callbacks settled. Another worker's recovery no longer runs a job that still runs on a stopping worker, also with shutdownTimeout > heartbeatTimeout (native multi-worker test). - A1: a job dequeued just before stop is released, not cancelled. - A2: cancel() during stop cancels a released job at once, also while its handler never settles. - A3: releaseJob false/throw is logged as left to recovery (no "released" log), and the job span always ends. - A4: postgres.js end() timeout is min(5 s, shutdownTimeout). - A5: orphaned setJobSpan JSDoc. - Docs: shutdownTimeout and heartbeat during the drain, release never deletes steps vs recovery with an unknown checksum (rolling deploys), custom adapter behaviour change (cancel -> left active for recovery). * fix: database-clock finished_at, migrate lock, per-schema prune key, getTracer name - finished_at of jobs and steps (and archived steps' job_finished_at) from the database clock (now()) instead of the JavaScript clock. - migrate() runs in one transaction after pg_advisory_xact_lock( hashtextextended('duron:migrate:duron', 0)): concurrent cold starts no longer race on DDL (PGlite: same path). - Scheduled-prune advisory key derived from the schema: hashtextextended('duron:prune:', 0) instead of 42; docs with a rolling-upgrade note (old/new workers may prune concurrently, harmless). - TelemetryContext.getTracer(name) returns the application provider's tracer `name` (context-aware), not Duron's tracer. - Claim timeouts keep a lower operator lock_timeout / idle_in_transaction_session_timeout (read once at startup); comment nit. - Adapter._heldJobIds(options): protected accessor for custom _recoverJobs. - driverEndTimeout = min(5 s, 80% of shutdownTimeout) so the forced end fires inside the owned-close budget; N1 known-limit comment on release after a failed completion. * fix(migrate): run the locked migration transaction READ COMMITTED (F3 review) With default_transaction_isolation = repeatable read or serializable, the migration transaction took its snapshot at the advisory-lock SELECT, before the wait, so a later migrator did not see the migrations of the first one and applied them again (5/6 cold starts failed on PG19). Set isolationLevel 'read committed' explicitly. Test: PGlite probe of the transaction isolation and the concurrent cold-start test under a repeatable-read default. Docs: the migration transaction is READ COMMITTED; during a rolling upgrade two unlocked prune passes can rarely deadlock (40P01), one pass logs the error and the next tick retries. * test: run the suite in parallel processes and create test databases from templates - scripts/test-parallel.ts: one `bun test --timeout 10000 ` process per file, a pool of half the CPU cores, longest files first; files with wall-clock budgets run afterwards, one at a time. Per-file lines, full output of failed files, a per-file count table, exit 1 on any failure. `bun run test` and both CI jobs use it; `test:serial` keeps plain bun test. - Native: each test database is CREATE DATABASE ... TEMPLATE over SQL (no docker exec); base (pgcrypto) and migrated templates are built once per server under an advisory lock, keyed by a hash of the migrations folder and the Drizzle version. deleteDb drops over SQL. - PGlite: factory engines start from a per-process dumpDataDir snapshot (skips initdb). - Factories return a migrated database unless `fresh: true` or `migrateOnStart: false`; tests that observe the migrations use `fresh: true`. * test: serialize more wall-clock files, add a per-file timeout, drop stale templates (FAST review) - R1: local-cancellation.test (E5 100 ms margin), wait-context (350 ms budgets), worker-discovery (20 ms timer, 150 ms quiet window) and wait-cohorts (30 ms exact counts) run in the serial lane; AGENTS.md lists them. - A1: a per-file timeout (default 300000 ms, --file-timeout / DURON_TEST_FILE_TIMEOUT) kills a hung file and reports it by name with its output so far; the run continues. Pipes are read incrementally and released 2 s after exit, so a leaked grandchild that holds them cannot hang the runner. - A3: the runner drops templates of other migration keys before a native run (best effort, skipped while another run builds or copies them); a process whose template disappears (3D000) rebuilds it. - A4: the runner sets DURON_TEST_CONTAINER_READY=1 after preparing the container, so test processes skip the docker checks and the 1 s settle sleep. * test(claim-isolation): count only the claim's SERIALIZABLE setup migrate() now runs in a READ COMMITTED transaction (F3), so statements traced from start() include its SET TRANSACTION; the drain-boundary test counted it. * refactor: shared column lists, #op helpers, prune scheduler module, stop gate error Behaviour-neutral (F4): - columns.ts: JOB_COLUMNS / STEP_COLUMNS with columnNames/copiedColumns for the archive, recovery and time-travel copies; #archiveSteps helper; archive-columns test compares the lists with the schema. - Adapter #op(name, fn, { start, log }) and Client #op(fn) replace the repeated lifecycle/start/assert/log blocks (messages unchanged). - prune-scheduler.ts: PruneScheduler (state, tick, retire, re-establish) moved out of base.ts next to prune-lock.ts; base delegates via hooks. - base.ts: protected _transaction() helper replaces the monkey-patched this.db.transaction (same guards); lifecycle-sql hooks the helper. - prune-lock.ts: bootstrapPending/bootstrapSucceeded/established -> one #phase ('idle'|'bootstrapping'|'reserving'|'established'|'ended'). - StopGateError (one class, gate kind) for the stop-gate refusals; isStopFailure checks the type; messages and Error name unchanged. * fix: route prune faults through _retirePruning, brand StopGateError across copies - PruneScheduler acquisition and release faults call the host's retire, which goes through the protected _retirePruning hook again (as _pruneTick did), so an override receives them. Regression tests for both faults. - StopGateError carries a Symbol.for('duron.stopGate') brand on its prototype; isStopFailure checks the brand, so the error of another loaded copy of duron is recognized. instanceof still works. gate is non-enumerable, so a logged error has no extra field. - Document that subclasses must use this._transaction() to keep the stop gates (_transaction JSDoc, adapters.mdx). * test(shutdown-release): tolerate slow heartbeat writes in the long-drain test The test 'does not let another worker run a job while a stopping worker still runs it' failed once in a full native run with [run, run, step end, step end]. Cause: a test timing assumption, not a double run in Duron. The test used heartbeatInterval 100 ms and heartbeatTimeout 300 ms. Recovery treats a client whose last committed heartbeat is older than heartbeatTimeout as dead. On a loaded PostgreSQL the heartbeat upsert took 150 ms to 2.3 s, so B's recovery saw A's last_seen_at 321-929 ms old and requeued the job while A's step still ran. Instrumented reproductions (13 cases) all showed this. The beats during the drain keep the same cadence as the periodic beats before stop(): the stop adds no gap. A running (not stopping) worker with the same late heartbeat is recovered in the same way, which is the documented liveness contract. A second flake: the step slept 1.2 s from its start, so when b.start() took longer under load, the step ended before stop() and A completed the job ([run, step end]). Changes: - heartbeatTimeout 1000 ms (interval 100 ms): tolerates slow heartbeat writes. - The step waits for the abort, then runs 2 x heartbeatTimeout, so the drain starts with the stop and is longer than heartbeatTimeout plus B's recovery interval. - shutdownTimeout 10 s and waitForJob 10 s for headroom on a loaded machine. Red check: with the drain heartbeats disabled, the test still fails 3/3 with [run, run, step end]. * chore: group test files by feature, pg_isready readiness, How it works docs page - Tests: 76 -> 35 files, grouped by feature (lifecycle, prune-lock, prune-scheduler, wait, wait-timing, wait-native, claim, recover, local-cancellation, cancel-storage, stop, time-travel, archive, client). Each former file is a block with its own helpers under a banner; imports merged. Same test names and counts (PGlite 684 incl. 80 skip, native 1185: sorted name lists identical before/after). Two identifiers renamed to avoid new shadowing. - Fast runner SERIAL patterns updated (stop*, claim.test, wait-timing); every formerly serial test stays serial. AGENTS.md updated; oxlint override turns off consistent-function-scoping for test files. - test/docker.ts: waitForContainer polls pg_isready (TCP inside the container) instead of waiting for a log line. - Docs: short summaries for waitReadTimeout, pullInterval, batchSize, recoverJobsOnStart, recoverJobsInterval, shutdownTimeout and stop(); the guarantees catalogue (discovery/batchSize, recovery, wait reads, notification hints, shutdown, archive retention) moves to a new "How it works" page linked from them. * chore: F5 review nits (define B, dedupe shutdown text, stale comments, docker exec timeout) * ci: run the test workflow for pull requests into any branch (stacked PRs) * test(prune-lock): give the owned-close test room to close sessions on a loaded database The test holds database cleanup until its budget ends while owned close must still finish inside the same budget; with 300 ms (driver end 240 ms) closing the sessions on a loaded PostgreSQL 19 overran (local CI run). Uses 1 s; 5/5 native runs pass. * test(recover): delete the worker scripts when each test ends The worker scripts went to /tmp/duron-worker-*.ts and a 5 s timer deleted them. When the test process ended first (for example a filtered run) or the worker did not start, the files stayed. Each worker now gets a mkdtemp directory that afterEach deletes, also when the test fails. * fix(stop): write skipped step statuses in the job's final transaction During a graceful stop, a handler that still resolved had its aborted steps written as cancelled/failed (StepManager.writeSkipped) before completeJob. When completeJob then failed, the job was released with those steps already cancelled, and its next run failed on them ("Cannot recover a cancelled step"). completeJob and failJob now take an optional `steps` list (StepFinalization: stepId, status cancelled|failed, error). The built-in PostgreSQL/PGlite _completeJob/_failJob write them in the transaction that ends the job, after the job row lock and only for still-active steps, so a job that does not end keeps its steps unchanged. StepManager.takeSkipped() replaces writeSkipped(). Custom adapters keep the old behaviour: the protected getter _finishesStepsWithJob defaults to false, and then the Adapter writes each step with _cancelJobStep/_failJobStep first and calls _completeJob/_failJob without steps. Documented in adapters.mdx. The known-limit comment is removed. * fix(lifecycle): log stop-gate refusals as a plain Error again Since the stop-gate brand (F4), a logged refusal had pino `type` 'StopGateError' (from constructor.name) instead of 'Error'. `new StopGateError(gate)` now returns a plain Error (prototype Error.prototype, name 'Error', stack from the caller) with the same gate message, and non-enumerable own `gate` and Symbol.for('duron.stopGate') brand. isStopFailure still detects it by the brand, also as a cause. `instanceof StopGateError` still works: a static Symbol.hasInstance checks the brand, so it now also matches the error of another loaded copy. Before: {"err":{"type":"StopGateError","message":"Adapter is not accepting work",...}} After: {"err":{"type":"Error","message":"Adapter is not accepting work",...}} * docs: subclasses overriding _completeJob/_failJob must apply options.steps; JSDoc placement (leftovers review A1, A3) --- .github/workflows/test.yml | 7 +- .oxlintrc.json | 13 +- AGENTS.md | 24 +- packages/docs/content/docs/adapters.mdx | 91 +- packages/docs/content/docs/client-api.mdx | 62 +- packages/docs/content/docs/how-it-works.mdx | 146 + packages/docs/content/docs/meta.json | 1 + packages/docs/content/docs/multi-worker.mdx | 56 +- packages/docs/content/docs/telemetry.mdx | 2 +- .../migration.sql | 3 + .../snapshot.json | 32 + packages/duron/package.json | 3 +- packages/duron/scripts/test-parallel.ts | 326 ++ packages/duron/src/action-job.ts | 183 +- packages/duron/src/action-manager.ts | 58 +- packages/duron/src/adapters/adapter.ts | 587 ++- packages/duron/src/adapters/postgres/base.ts | 910 +++-- .../duron/src/adapters/postgres/columns.ts | 74 + .../duron/src/adapters/postgres/pglite.ts | 21 +- .../duron/src/adapters/postgres/postgres.ts | 21 +- .../duron/src/adapters/postgres/prune-key.ts | 8 + .../duron/src/adapters/postgres/prune-lock.ts | 50 +- .../src/adapters/postgres/prune-scheduler.ts | 296 ++ .../src/adapters/postgres/schema.default.ts | 2 + .../duron/src/adapters/postgres/schema.ts | 10 + packages/duron/src/adapters/schemas.ts | 34 +- packages/duron/src/client.ts | 185 +- packages/duron/src/lifecycle.ts | 141 +- packages/duron/src/local-cancellation.ts | 5 + packages/duron/src/step-manager.ts | 90 +- packages/duron/src/worker-discovery.ts | 89 +- packages/duron/test/adapter.test.ts | 93 +- packages/duron/test/adapters.ts | 107 +- packages/duron/test/archive.test.ts | 1021 +++--- .../duron/test/cancel-storage-shared.test.ts | 153 - packages/duron/test/cancel-storage.test.ts | 1851 +++++----- packages/duron/test/claim-isolation.test.ts | 462 ++- packages/duron/test/claim-pglite.test.ts | 492 --- packages/duron/test/claim-selection.test.ts | 143 - packages/duron/test/claim.test.ts | 787 ++++ .../duron/test/client-adapter-binding.test.ts | 164 - packages/duron/test/client.test.ts | 2298 ++++++------ .../duron/test/discovery-throughput.test.ts | 22 +- packages/duron/test/docker.ts | 283 +- packages/duron/test/finished-at-clock.test.ts | 88 + .../duron/test/lifecycle-background.test.ts | 144 - packages/duron/test/lifecycle-budgets.test.ts | 172 - .../duron/test/lifecycle-close-retry.test.ts | 112 - packages/duron/test/lifecycle-errors.test.ts | 185 - .../test/lifecycle-handler-entry.test.ts | 125 - .../duron/test/lifecycle-listeners.test.ts | 282 -- packages/duron/test/lifecycle-sql.test.ts | 209 -- packages/duron/test/lifecycle-startup.test.ts | 156 - packages/duron/test/lifecycle.test.ts | 3191 ++++++++++++----- .../test/local-cancellation-registry.test.ts | 183 - .../duron/test/local-cancellation.test.ts | 2865 ++++++++------- .../duron/test/migrate-concurrency.test.ts | 96 + packages/duron/test/notifications.test.ts | 8 +- packages/duron/test/otel-integration.test.ts | 5 + packages/duron/test/prune-backoff.test.ts | 127 - packages/duron/test/prune-batches.test.ts | 140 - packages/duron/test/prune-bootstrap.test.ts | 420 --- packages/duron/test/prune-cadence.test.ts | 202 -- packages/duron/test/prune-lock.test.ts | 2123 +++++++++++ packages/duron/test/prune-loss.test.ts | 165 - packages/duron/test/prune-ownership.test.ts | 761 ---- .../duron/test/prune-pglite-faults.test.ts | 107 - packages/duron/test/prune-reestablish.test.ts | 415 --- packages/duron/test/prune-replies.test.ts | 142 - packages/duron/test/prune-scheduler.test.ts | 1426 ++++++-- packages/duron/test/prune-scope.test.ts | 175 - packages/duron/test/prune-transport.test.ts | 194 - packages/duron/test/recover-own-jobs.test.ts | 285 -- packages/duron/test/recover-snapshot.test.ts | 3 + packages/duron/test/recover.test.ts | 1150 ++++-- packages/duron/test/setup.ts | 2 +- packages/duron/test/shutdown-release.test.ts | 779 ++++ packages/duron/test/stop-drain-scope.test.ts | 211 -- packages/duron/test/stop-in-handler.test.ts | 158 - packages/duron/test/stop.test.ts | 373 ++ .../test/time-travel-archive-lock.test.ts | 73 - packages/duron/test/time-travel.test.ts | 2087 +++++------ packages/duron/test/wait-cadence.test.ts | 262 -- packages/duron/test/wait-cancellation.test.ts | 87 - packages/duron/test/wait-capacity.test.ts | 132 - packages/duron/test/wait-cohorts.test.ts | 327 -- packages/duron/test/wait-context.test.ts | 272 -- packages/duron/test/wait-lifecycle.test.ts | 97 - .../duron/test/wait-native-fixture.test.ts | 1463 -------- packages/duron/test/wait-native-fixture.ts | 3 +- packages/duron/test/wait-native.test.ts | 2007 +++++++++-- packages/duron/test/wait-options.test.ts | 35 - packages/duron/test/wait-pglite.test.ts | 88 - packages/duron/test/wait-pool.test.ts | 99 - packages/duron/test/wait-read-errors.test.ts | 96 - .../duron/test/wait-reconciliation.test.ts | 129 - packages/duron/test/wait-results.test.ts | 102 - packages/duron/test/wait-timing.test.ts | 977 +++++ packages/duron/test/wait-transport.test.ts | 145 - packages/duron/test/wait.test.ts | 935 +++++ packages/duron/test/worker-discovery.test.ts | 62 +- packages/duron/tsconfig.json | 2 +- 102 files changed, 20881 insertions(+), 17184 deletions(-) create mode 100644 packages/docs/content/docs/how-it-works.mdx create mode 100644 packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/migration.sql create mode 100644 packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/snapshot.json create mode 100644 packages/duron/scripts/test-parallel.ts create mode 100644 packages/duron/src/adapters/postgres/columns.ts create mode 100644 packages/duron/src/adapters/postgres/prune-key.ts create mode 100644 packages/duron/src/adapters/postgres/prune-scheduler.ts delete mode 100644 packages/duron/test/cancel-storage-shared.test.ts delete mode 100644 packages/duron/test/claim-pglite.test.ts delete mode 100644 packages/duron/test/claim-selection.test.ts create mode 100644 packages/duron/test/claim.test.ts delete mode 100644 packages/duron/test/client-adapter-binding.test.ts create mode 100644 packages/duron/test/finished-at-clock.test.ts delete mode 100644 packages/duron/test/lifecycle-background.test.ts delete mode 100644 packages/duron/test/lifecycle-budgets.test.ts delete mode 100644 packages/duron/test/lifecycle-close-retry.test.ts delete mode 100644 packages/duron/test/lifecycle-errors.test.ts delete mode 100644 packages/duron/test/lifecycle-handler-entry.test.ts delete mode 100644 packages/duron/test/lifecycle-listeners.test.ts delete mode 100644 packages/duron/test/lifecycle-sql.test.ts delete mode 100644 packages/duron/test/lifecycle-startup.test.ts delete mode 100644 packages/duron/test/local-cancellation-registry.test.ts create mode 100644 packages/duron/test/migrate-concurrency.test.ts delete mode 100644 packages/duron/test/prune-backoff.test.ts delete mode 100644 packages/duron/test/prune-batches.test.ts delete mode 100644 packages/duron/test/prune-bootstrap.test.ts delete mode 100644 packages/duron/test/prune-cadence.test.ts create mode 100644 packages/duron/test/prune-lock.test.ts delete mode 100644 packages/duron/test/prune-loss.test.ts delete mode 100644 packages/duron/test/prune-ownership.test.ts delete mode 100644 packages/duron/test/prune-pglite-faults.test.ts delete mode 100644 packages/duron/test/prune-reestablish.test.ts delete mode 100644 packages/duron/test/prune-replies.test.ts delete mode 100644 packages/duron/test/prune-scope.test.ts delete mode 100644 packages/duron/test/prune-transport.test.ts delete mode 100644 packages/duron/test/recover-own-jobs.test.ts create mode 100644 packages/duron/test/shutdown-release.test.ts delete mode 100644 packages/duron/test/stop-drain-scope.test.ts delete mode 100644 packages/duron/test/stop-in-handler.test.ts create mode 100644 packages/duron/test/stop.test.ts delete mode 100644 packages/duron/test/time-travel-archive-lock.test.ts delete mode 100644 packages/duron/test/wait-cadence.test.ts delete mode 100644 packages/duron/test/wait-cancellation.test.ts delete mode 100644 packages/duron/test/wait-capacity.test.ts delete mode 100644 packages/duron/test/wait-cohorts.test.ts delete mode 100644 packages/duron/test/wait-context.test.ts delete mode 100644 packages/duron/test/wait-lifecycle.test.ts delete mode 100644 packages/duron/test/wait-native-fixture.test.ts delete mode 100644 packages/duron/test/wait-options.test.ts delete mode 100644 packages/duron/test/wait-pglite.test.ts delete mode 100644 packages/duron/test/wait-pool.test.ts delete mode 100644 packages/duron/test/wait-read-errors.test.ts delete mode 100644 packages/duron/test/wait-reconciliation.test.ts delete mode 100644 packages/duron/test/wait-results.test.ts create mode 100644 packages/duron/test/wait-timing.test.ts delete mode 100644 packages/duron/test/wait-transport.test.ts create mode 100644 packages/duron/test/wait.test.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8424274..d4f492d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,13 +30,14 @@ jobs: # typecheck uses `bun check`; the published `dist` is emitted by tsc, so build it too. - name: Build run: bun run build + # scripts/test-parallel.ts: files in parallel processes, timing-sensitive files serially. - name: Run tests - run: bun test --timeout 10000 + run: bun run test # The native PostgreSQL suite (POSTGRES_TEST=true) on every supported server major. # test/docker.ts provisions the server itself: it runs DURON_TEST_POSTGRES_IMAGE as the # container duron-postgres-test- on port 5440 and creates one database per test - # with `docker exec` (createdb/psql/dropdb). The runner's Docker daemon is enough, so no + # over SQL from a template database. The runner's Docker daemon is enough, so no # `services:` container is used (docker.ts would refuse one that holds port 5440). native: timeout-minutes: 60 @@ -61,7 +62,7 @@ jobs: run: docker pull "$DURON_TEST_POSTGRES_IMAGE" # Every PostgreSQL test runs only with POSTGRES_TEST; the test job above is PGlite only. - name: Run native tests - run: bun test --timeout 10000 + run: bun run test - name: PostgreSQL container logs if: failure() run: docker logs "duron-postgres-test-${DURON_TEST_POSTGRES_IMAGE//[^a-zA-Z0-9_.-]/-}" 2>&1 | tail -200 diff --git a/.oxlintrc.json b/.oxlintrc.json index 5d37302..c117200 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -11,7 +11,12 @@ "suspicious": "warn" }, "rules": { - "import/no-unassigned-import": ["error", { "allow": ["./app.css", "**/*.css"] }], + "import/no-unassigned-import": [ + "error", + { + "allow": ["./app.css", "**/*.css"] + } + ], "no-underscore-dangle": "off" }, "overrides": [ @@ -20,6 +25,12 @@ "rules": { "no-shadow": "off" } + }, + { + "files": ["packages/duron/test/*.test.ts"], + "rules": { + "unicorn/consistent-function-scoping": "off" + } } ], "ignorePatterns": ["dist", "build", "node_modules", ".wrangler", "**/*.gen.ts", "**/env.d.ts"] diff --git a/AGENTS.md b/AGENTS.md index e0be5f4..b8fc230 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ bun run lint # oxlint check bun run lint:fix # oxlint fix bun run fmt:check # oxfmt check bun run fmt # oxfmt fix -bun test --timeout 10000 # runs packages/duron tests (same as `bun run test`) +bun run test # packages/duron tests in parallel processes (scripts/test-parallel.ts) # Build bun run build # all packages @@ -61,9 +61,19 @@ bun run build:docs # docs only - Framework: `bun:test` - Tests live in `packages/duron/test/*.test.ts` - Run single file: `bun test --timeout 10000 specific.test.ts` -- Default per-test timeout: pass `--timeout 10000` (the `test` script and CI do). Bun ignores a `timeout` key in `bunfig.toml` (oven-sh/bun#7789), so a plain `bun test` uses 5000 ms. -- Core tests run with `bun test --timeout 10000` (no `--concurrent`: many suites share native resources and time-sensitive lifecycle budgets, and fail under cross-file concurrency) -- A plain `bun test --timeout 10000` runs PGlite only and needs no Docker. PostgreSQL tests run only with `POSTGRES_TEST=true`; every file that uses PostgreSQL gates it on that variable. +- Default per-test timeout: pass `--timeout 10000` (the runner and CI do). Bun ignores a `timeout` key in `bunfig.toml` (oven-sh/bun#7789), so a plain `bun test` uses 5000 ms. +- Full suite: `bun run test` (root or `packages/duron`) runs `packages/duron/scripts/test-parallel.ts`. CI uses it too. + - Each test file runs in its own `bun test --timeout 10000 ` process. Files without wall-clock budgets run in a pool of `--jobs N` processes (default: half the CPU cores; `DURON_TEST_JOBS` overrides). + - Files with wall-clock budgets (the `SERIAL` list in the script: `lifecycle*`, `prune-*`, `stop*`, `shutdown-*`, `wait-native*`, `wait-timing`, `discovery-throughput`, `claim-isolation`, `claim.test`, `cross-mechanism`, `step-abort-settlement`, `local-cancellation.test`, `worker-discovery`) run after the pool, one at a time, with no other test process. Add a file there when it asserts elapsed time or observes timers/cadences under a bound, and put a timing-sensitive test only in a file of that list. +- Test files are grouped by feature (for example `lifecycle.test.ts`, `prune-lock.test.ts`, `prune-scheduler.test.ts`, `wait.test.ts`, `wait-timing.test.ts`). Each former file is one `{ ... }` block with its own helpers, under a `// ===` banner with its old name; the imports are shared at the top. Keep a new group's helpers inside its block (the lint override for `packages/duron/test/*.test.ts` turns off `unicorn/consistent-function-scoping` for this reason). + - Output: one line per finished file (pass/skip/fail counts, time); then the complete output of each failed file, a per-file count table and the totals. Exit status 1 when a file fails (non-zero `bun test` exit, a failed test, no summary, or longer than the file timeout: 300000 ms, `--file-timeout` or `DURON_TEST_FILE_TIMEOUT`; a timed-out file is killed and reported by name, and the run continues). Every file's log is kept in `DURON_TEST_LOG_DIR` (default: a new temporary directory; the path is printed). + - Filters: `bun run test -- wait-` (in `packages/duron`) runs the files whose path contains a filter. +- `bun test --timeout 10000` (root, or `bun run test:serial` in `packages/duron`) still runs every file in one process, one file after another. It is slower; use it for one file or to compare. +- PGlite tests need no Docker. PostgreSQL tests run only with `POSTGRES_TEST=true`; every file that uses PostgreSQL gates it on that variable. +- Test databases (`test/adapters.ts`, `test/docker.ts`): + - `pgliteFactory` / `postgresFactory` give a database with all migrations already applied; `migrateOnStart` only checks them. With `fresh: true` or `migrateOnStart: false` the database is empty (as a new one). Use `fresh: true` in a test that observes the migrations themselves. + - PGlite: each process dumps one migrated and one empty engine once (`dumpDataDir`); every factory engine starts from a dump (`loadDataDir`), which skips `initdb` (about 450 ms of the 500 ms of a new engine). + - PostgreSQL: each test database is `CREATE DATABASE "" TEMPLATE "