From a781b7a4b61a8b5fd9387e71b1093de7e8bf1a9c Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:14:27 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix(core):=20=E5=8C=BA=E5=88=86=20Job=20?= =?UTF-8?q?=E9=A2=86=E5=8F=96=E7=AB=9E=E4=BA=89=E4=B8=8E=E6=8C=81=E4=B9=85?= =?UTF-8?q?=E5=8C=96=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changeset/clear-job-write-outcomes.md | 5 + packages/core/src/job/job.ts | 6 +- packages/core/src/job/manager.ts | 31 ++++-- tests/e2e/peer-database.spec.ts | 137 +++++++++++++++++++++++++ 4 files changed, 166 insertions(+), 13 deletions(-) create mode 100644 .changeset/clear-job-write-outcomes.md diff --git a/.changeset/clear-job-write-outcomes.md b/.changeset/clear-job-write-outcomes.md new file mode 100644 index 00000000..4bbf32de --- /dev/null +++ b/.changeset/clear-job-write-outcomes.md @@ -0,0 +1,5 @@ +--- +'@inkcre/core': patch +--- + +区分 Job 持久化失败和条件更新未命中。任务执行结束后只尝试写入一次终态,保留关闭请求出错前的执行结果。 diff --git a/packages/core/src/job/job.ts b/packages/core/src/job/job.ts index e1e059fa..cfeeb60c 100644 --- a/packages/core/src/job/job.ts +++ b/packages/core/src/job/job.ts @@ -27,7 +27,9 @@ export class JobType extends Z.class({ static dbApi = new DBAPIClient<'job_types', JobType>('job_types', JobType) static async get(id: JobTypeRef): Promise { - return JobType.parse((await this.dbApi.from().select().eq('id', id).single()).data) + return JobType.parse( + (await this.dbApi.from().select().eq('id', id).single().throwOnError()).data + ) } static async getAll(): Promise { @@ -71,7 +73,7 @@ export class Job extends Z.class({ .order('created_at', { ascending: false }) .limit(options.limit ?? 20) if (options.status) query = query.eq('status', options.status) - return ((await query).data ?? []).map((item) => Job.parse(item)) + return ((await query.throwOnError()).data ?? []).map((item) => Job.parse(item)) } static async getBySource(source: number, limit = 20): Promise { diff --git a/packages/core/src/job/manager.ts b/packages/core/src/job/manager.ts index d86ce9b0..59e091aa 100644 --- a/packages/core/src/job/manager.ts +++ b/packages/core/src/job/manager.ts @@ -8,7 +8,12 @@ import { type Context, } from '../obsrv/telemetry' import { z } from 'zod' -import { Job, JobStatus, JobType, type JobRef, type JobTypeRef } from './job' +import { Job, JobStatus, JobType, type JobRef, type JobStatusValue, type JobTypeRef } from './job' + +type TerminalJobStatus = Exclude< + JobStatusValue, + typeof JobStatus.PENDING | typeof JobStatus.RUNNING +> export interface JobHandler { parameters: Parameters @@ -70,6 +75,7 @@ export class JobManager { }) .select() .single() + .throwOnError() const job = Job.parse(result.data) span?.setAttribute('inkcre.job.id', job.id) emitJobEvent('job.submitted', job.id, active) @@ -94,17 +100,19 @@ export class JobManager { .eq('status', JobStatus.PENDING) .select() .maybeSingle() + .throwOnError() return result.data ? Job.parse(result.data) : null } - private static async close(job: Job, status: string): Promise { + private static async close(job: Job, status: TerminalJobStatus): Promise { const result = await Job.dbApi .update({ status, state: job.state }) .eq('id', job.id) .eq('status', JobStatus.RUNNING) .select('id') + .throwOnError() const closed = (result.data?.length ?? 0) > 0 - if (closed) job.status = status as Job['status'] + if (closed) job.status = status return closed } @@ -207,26 +215,26 @@ export class JobManager { () => controller.abort(JobStatus.TIMED_OUT), claimed.timeout_seconds * 1000 ) + let status: TerminalJobStatus = JobStatus.FINISHED try { // An abort signal is only a request. Await actual handler settlement; // Promise.race would report closure while side effects were still running. await handler.handle(claimed, parameters, controller.signal) - await this.close( - claimed, - controller.signal.aborted ? String(controller.signal.reason) : JobStatus.FINISHED - ) } catch (error) { claimed.state = { ...claimed.state, error: error instanceof Error ? error.message : String(error), } - await this.close( - claimed, - controller.signal.aborted ? String(controller.signal.reason) : JobStatus.FAILED - ) + status = JobStatus.FAILED } finally { clearTimeout(timeout) } + if (controller.signal.aborted) { + status = + controller.signal.reason === JobStatus.TIMED_OUT ? JobStatus.TIMED_OUT : JobStatus.ABORTED + } + // A lost close response may follow a commit. Propagate the error without writing a second outcome. + await this.close(claimed, status) } static async checkAbortRequests(): Promise { @@ -237,6 +245,7 @@ export class JobManager { .select('id') .in('id', [...active.keys()]) .eq('abort_requested', true) + .throwOnError() for (const job of result.data ?? []) { active.get(job.id)?.controller.abort(JobStatus.ABORTED) } diff --git a/tests/e2e/peer-database.spec.ts b/tests/e2e/peer-database.spec.ts index 036bf9e4..96bdd400 100644 --- a/tests/e2e/peer-database.spec.ts +++ b/tests/e2e/peer-database.spec.ts @@ -780,6 +780,143 @@ test('disabling participation drains a dispatched claim before saving configurat } }) +test('Job execution distinguishes a denied claim, a competing claim, and a lost close reply', async ({ + page, +}) => { + const authorization = `Bearer ${await token()}` + const headers = { Authorization: authorization, 'Content-Type': 'application/json' } + const type = `e2e.job-outcomes.${crypto.randomUUID()}` + const createdType = await fetch(`${postgrestUrl}job_types`, { + method: 'POST', + headers, + body: JSON.stringify({ + id: type, + description: 'Job transport outcomes', + parameters_schema: {}, + default_timeout_seconds: 3600, + }), + }) + expect(createdType.status).toBe(201) + try { + await page.goto('/sources') + await expect(page.getByRole('main')).toBeVisible() + await expect( + page.getByText( + 'Connecting this Web Peer; database pages are available, local jobs are not running yet.' + ) + ).toHaveCount(0) + + await page.evaluate(async (type) => { + type Sdk = typeof import('../../packages/core/src/index') + const globals = globalThis as typeof globalThis & { + __FEDERATION__: { + __INSTANCES__: Array<{ + options: { name: string } + loadShare(name: string): Promise<() => Sdk> + }> + } + runJobForTransportTest(id: number): Promise<{ accepted?: boolean; error?: string }> + } + const host = globals.__FEDERATION__.__INSTANCES__.find( + (instance) => instance.options.name === 'host' + )! + const { JobManager, MetaConfigSchema } = (await host.loadShare('@inkcre/core'))() + JobManager.startWorker(3_600_000) + JobManager.registerHandler(type, { + parameters: MetaConfigSchema, + canHandle: () => true, + handle: async (job) => { + job.state = { handlerCompleted: true } + }, + }) + globals.runJobForTransportTest = async (id) => { + try { + return { accepted: await JobManager.run(id) } + } catch (error) { + return { error: error instanceof Error ? error.message : String(error) } + } + } + }, type) + + for (const scenario of ['denied', 'competing', 'lost-reply'] as const) { + const created = await fetch(`${postgrestUrl}jobs`, { + method: 'POST', + headers: { ...headers, Prefer: 'return=representation' }, + body: JSON.stringify({ type, parameters: {}, timeout_seconds: 3600 }), + }) + expect(created.status).toBe(201) + const [{ id }] = (await created.json()) as Array<{ id: number }> + const jobUrl = `${postgrestUrl}jobs?id=eq.${id}` + const writes: string[] = [] + const routePattern = '**/jobs?**' + await page.route(routePattern, async (route) => { + const request = route.request() + if ( + request.method() !== 'PATCH' || + new URL(request.url()).searchParams.get('id') !== `eq.${id}` + ) { + await route.continue() + return + } + const { status } = request.postDataJSON() as { status: string } + writes.push(status) + if (scenario === 'denied') { + const response = await route.fetch({ + headers: { ...request.headers(), authorization: 'Bearer invalid-fixture' }, + }) + expect(response.status()).toBe(401) + await route.fulfill({ response }) + } else if (scenario === 'competing') { + const winner = await fetch(jobUrl, { + method: 'PATCH', + headers, + body: JSON.stringify({ status: 'running' }), + }) + expect(winner.ok).toBe(true) + await route.continue() + } else if (status === 'finished') { + const committed = await route.fetch() + expect(committed.ok()).toBe(true) + await route.abort('failed') + } else { + await route.continue() + } + }) + try { + const result = await page.evaluate((id) => { + const globals = globalThis as typeof globalThis & { + runJobForTransportTest(id: number): Promise<{ accepted?: boolean; error?: string }> + } + return globals.runJobForTransportTest(id) + }, id) + const read = await fetch(`${jobUrl}&select=status,state`, { headers }) + expect(read.ok).toBe(true) + const persisted = await read.json() + if (scenario === 'denied') { + expect(result.error).toBeTruthy() + expect(result.accepted).toBeUndefined() + expect(writes).toEqual(['running']) + expect(persisted).toEqual([{ status: 'pending', state: {} }]) + } else if (scenario === 'competing') { + expect(result).toEqual({ accepted: false }) + expect(writes).toEqual(['running']) + expect(persisted).toEqual([{ status: 'running', state: {} }]) + } else { + expect(result.error).toBeTruthy() + expect(result.accepted).toBeUndefined() + expect(writes).toEqual(['running', 'finished']) + expect(persisted).toEqual([{ status: 'finished', state: { handlerCompleted: true } }]) + } + } finally { + await page.unroute(routePattern) + await fetch(jobUrl, { method: 'DELETE', headers }) + } + } + } finally { + await fetch(`${postgrestUrl}job_types?id=eq.${type}`, { method: 'DELETE', headers }) + } +}) + test('Registry confirmation selects one Peer and offline enablement preserves other native pins', async ({ page, }) => { From 54b345a6a17d604ef9f9d1393a287f4358c762bc Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:22:57 +0800 Subject: [PATCH 2/3] =?UTF-8?q?test(core):=20=E6=9B=B4=E6=96=B0=E5=8F=96?= =?UTF-8?q?=E6=B6=88=E6=B5=8B=E8=AF=95=E4=B8=AD=E7=9A=84=20PostgREST=20?= =?UTF-8?q?=E5=93=8D=E5=BA=94=E6=A1=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/tests/job-cancellation.test.mjs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scripts/tests/job-cancellation.test.mjs b/scripts/tests/job-cancellation.test.mjs index 3e1640a1..f5e5d7d8 100644 --- a/scripts/tests/job-cancellation.test.mjs +++ b/scripts/tests/job-cancellation.test.mjs @@ -27,12 +27,16 @@ function database(t, job, abortWhenClaimed) { select() { if (fields.status === JobStatus.RUNNING) return { - maybeSingle: async () => ({ - data: { ...job, status: JobStatus.RUNNING, abort_requested: abortWhenClaimed }, - }), + maybeSingle() { + return { + throwOnError: async () => ({ + data: { ...job, status: JobStatus.RUNNING, abort_requested: abortWhenClaimed }, + }), + } + }, } updates.push(fields.status) - return Promise.resolve({ data: [{ id: job.id }] }) + return { throwOnError: async () => ({ data: [{ id: job.id }] }) } }, })) return updates From 6c7d3c7ca9559a8ba9ff021b8763ec24093348bc Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sun, 29 Nov 2026 01:47:53 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(core):=20=E6=98=BE=E5=BC=8F=E6=8A=A5?= =?UTF-8?q?=E5=91=8A=20Job=20=E7=BB=88=E6=80=81=E6=9D=A1=E4=BB=B6=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changeset/clear-job-write-outcomes.md | 2 +- packages/core/src/job/manager.ts | 8 ++++---- scripts/tests/job-cancellation.test.mjs | 16 +++++++++++++++- tests/e2e/peer-database.spec.ts | 24 +++++++++++++++++++++--- 4 files changed, 41 insertions(+), 9 deletions(-) diff --git a/.changeset/clear-job-write-outcomes.md b/.changeset/clear-job-write-outcomes.md index 4bbf32de..eec425a4 100644 --- a/.changeset/clear-job-write-outcomes.md +++ b/.changeset/clear-job-write-outcomes.md @@ -2,4 +2,4 @@ '@inkcre/core': patch --- -区分 Job 持久化失败和条件更新未命中。任务执行结束后只尝试写入一次终态,保留关闭请求出错前的执行结果。 +区分 Job 领取竞争、终态写入冲突和请求出错。执行结束后只尝试写入一次终态,收到数据库更新确认后才报告成功。 diff --git a/packages/core/src/job/manager.ts b/packages/core/src/job/manager.ts index 59e091aa..245e4a4f 100644 --- a/packages/core/src/job/manager.ts +++ b/packages/core/src/job/manager.ts @@ -104,16 +104,16 @@ export class JobManager { return result.data ? Job.parse(result.data) : null } - private static async close(job: Job, status: TerminalJobStatus): Promise { + private static async close(job: Job, status: TerminalJobStatus): Promise { const result = await Job.dbApi .update({ status, state: job.state }) .eq('id', job.id) .eq('status', JobStatus.RUNNING) .select('id') .throwOnError() - const closed = (result.data?.length ?? 0) > 0 - if (closed) job.status = status - return closed + if (!result.data?.length) + throw new Error(`Job ${job.id} no longer matches a running row while writing ${status}`) + job.status = status } static run(id: JobRef): Promise { diff --git a/scripts/tests/job-cancellation.test.mjs b/scripts/tests/job-cancellation.test.mjs index 37ee9246..ffe3a5af 100644 --- a/scripts/tests/job-cancellation.test.mjs +++ b/scripts/tests/job-cancellation.test.mjs @@ -35,6 +35,14 @@ for (const scenario of [ handled: false, updates: ['running'], }, + { + name: 'a terminal write that matches no row does not report success', + cancelled: true, + eligible: false, + onClose: { status: 'timed_out' }, + closeConflict: true, + updates: ['running', 'aborted'], + }, ]) { void test(scenario.name, async (t) => { const prior = { ...configStore.metaConfig } @@ -59,6 +67,7 @@ for (const scenario of [ if (init.method === 'GET') return Response.json([job]) const fields = JSON.parse(init.body) if (fields.status === 'running') Object.assign(job, scenario.onClaim) + else Object.assign(job, scenario.onClose) const id = url.searchParams.get('id') const status = url.searchParams.get('status') updates.push({ method: init.method, id, status, next: fields.status }) @@ -75,7 +84,12 @@ for (const scenario of [ const handle = t.mock.fn(async () => {}) JobManager.registerHandler(job.type, { parameters: MetaConfigSchema, canHandle, handle }) try { - assert.equal(await JobManager.run(job.id), scenario.handled) + if (scenario.closeConflict) { + await assert.rejects(JobManager.run(job.id), /Job 81 no longer matches a running row/) + assert.equal(job.status, 'timed_out') + } else { + assert.equal(await JobManager.run(job.id), scenario.handled) + } assert.equal(canHandle.mock.callCount(), scenario.cancelled ? 0 : 1) assert.equal(handle.mock.callCount(), 0) assert.deepEqual( diff --git a/tests/e2e/peer-database.spec.ts b/tests/e2e/peer-database.spec.ts index fccb503d..2a4f8350 100644 --- a/tests/e2e/peer-database.spec.ts +++ b/tests/e2e/peer-database.spec.ts @@ -716,7 +716,7 @@ test('disabling participation drains a dispatched claim before saving configurat } }) -test('Job execution distinguishes a denied claim, a competing claim, and a lost close reply', async ({ +test('Job execution distinguishes denied or competing claims, a conflicting close, and a lost close reply', async ({ page, }) => { const authorization = `Bearer ${await token()}` @@ -774,7 +774,7 @@ test('Job execution distinguishes a denied claim, a competing claim, and a lost } }, type) - for (const scenario of ['denied', 'competing', 'lost-reply'] as const) { + for (const scenario of ['denied', 'competing', 'close-conflict', 'lost-reply'] as const) { const created = await fetch(`${postgrestUrl}jobs`, { method: 'POST', headers: { ...headers, Prefer: 'return=representation' }, @@ -810,7 +810,19 @@ test('Job execution distinguishes a denied claim, a competing claim, and a lost }) expect(winner.ok).toBe(true) await route.continue() - } else if (status === 'finished') { + } else if (scenario === 'close-conflict' && status === 'finished') { + const winner = await fetch(`${jobUrl}&status=eq.running`, { + method: 'PATCH', + headers: { ...headers, Prefer: 'return=representation' }, + body: JSON.stringify({ status: 'timed_out' }), + }) + expect(winner.ok).toBe(true) + expect(await winner.json()).toMatchObject([{ status: 'timed_out' }]) + const conflict = await route.fetch() + expect(conflict.status()).toBe(200) + expect(await conflict.json()).toEqual([]) + await route.fulfill({ response: conflict }) + } else if (scenario === 'lost-reply' && status === 'finished') { const committed = await route.fetch() expect(committed.ok()).toBe(true) await route.abort('failed') @@ -837,6 +849,12 @@ test('Job execution distinguishes a denied claim, a competing claim, and a lost expect(result).toEqual({ accepted: false }) expect(writes).toEqual(['running']) expect(persisted).toEqual([{ status: 'running', state: {} }]) + } else if (scenario === 'close-conflict') { + expect(result).toEqual({ + error: `Job ${id} no longer matches a running row while writing finished`, + }) + expect(writes).toEqual(['running', 'finished']) + expect(persisted).toEqual([{ status: 'timed_out', state: {} }]) } else { expect(result.error).toBeTruthy() expect(result.accepted).toBeUndefined()