From fc99b1246a9a837d01cae672026637aa950d4a0c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 23:16:35 +0000 Subject: [PATCH 1/2] fix(runtime): key a packaged job by its package coordinate and keep the catalogue's scoped key across a restart jobKeyFor now takes the job's package coordinate (package id, job name). Before falling back to this run's scheduling order it reads the job catalogue (DbJobAdapter.readArming, optional and adapter-local) for the coordinate's own package-scoped key: held active, it stays the job's key, so a restart that schedules the packages in another order no longer hands one package's bare key and run history to another package's job. The first holder still keeps the bare key and a second its :. Claude-Session: https://claude.ai/code/session_01ADHkmNp8ARUNvemy119dY1 Co-authored-by: Claude --- .../31679-job-key-package-coordinate.md | 12 ++ .../src/app-artifact-handlers.jobs.test.ts | 157 ++++++++++++++++++ packages/runtime/src/app-artifact-handlers.ts | 148 +++++++++++++---- 3 files changed, 286 insertions(+), 31 deletions(-) create mode 100644 .changeset/31679-job-key-package-coordinate.md diff --git a/.changeset/31679-job-key-package-coordinate.md b/.changeset/31679-job-key-package-coordinate.md new file mode 100644 index 00000000000..0d1a3811c4e --- /dev/null +++ b/.changeset/31679-job-key-package-coordinate.md @@ -0,0 +1,12 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): a packaged job keeps the job-service key its catalogue holds for it across a restart (ADR-0150 D4) + +Clause-②: no +Metadata-protocol: none + +Who is affected: a runtime where two installed packages declare a job of the same name, on the database-backed job service (`sys_job` / `sys_job_run`). Nothing else moves: a runtime where no two packages share a job name schedules every job under its authored name, as before. + +A job's identity is its package coordinate, the package id and the job name. The first package to hold a job name keeps the authored name on the job service, and a second package keeps the package-scoped `:`, as before. What changes is a restart. Before, the bare name went to whichever package the boot scheduled first, so a restart that rehydrated the packages in another order than they were installed in handed the first package's catalogue row and run history to the second package's job, and moved the first job under a new name. Now a package whose `:` the job catalogue still holds active (scheduled by an earlier run and never cancelled) is scheduled under it again, whatever the order. A job stored under its bare name before this release is scheduled under it again and fires as before. Nothing is refused and no author action is needed. diff --git a/packages/runtime/src/app-artifact-handlers.jobs.test.ts b/packages/runtime/src/app-artifact-handlers.jobs.test.ts index 3e09c18d955..4786d088d32 100644 --- a/packages/runtime/src/app-artifact-handlers.jobs.test.ts +++ b/packages/runtime/src/app-artifact-handlers.jobs.test.ts @@ -538,6 +538,163 @@ describe('#21602: two packages declaring the same job name — each job keeps it }); }); +describe('ADR-0150 E7: a job\'s package coordinate keeps the key the job catalogue holds for it, across a restart', () => { + const OTHER = 'com.example.other'; + const markedJob = (name: string, marker: string) => ({ + name, + schedule: INTERVAL, + body: { ...WRITE_BODY, source: `await ctx.api.object('${TICK}').insert({ name: '${marker}' });` }, + }); + + /** + * One `sys_job` catalogue that outlives a process, read the way + * `DbJobAdapter.readArming` reads it — `schedule` writes the row active, + * `cancel` clears `active`, and a process that stops leaves every row as it + * was — and one job service per process (a restart is a new kernel, so + * nothing of the previous process's in-memory record survives). + */ + function catalogue(opts: { readFails?: boolean } = {}) { + const rows = new Map(); + const engine = recordingEngine(); + const boot = () => { + const scheduled = new Map Promise>(); + const cleanups = new Map Promise>(); + const svc = { + schedule: async (name: string, _schedule: unknown, run: (c: any) => Promise) => { + scheduled.set(name, run); + rows.set(name, { active: true }); + }, + cancel: async (name: string) => { + scheduled.delete(name); + const row = rows.get(name); + if (row) row.active = false; + }, + trigger: async () => undefined, + readArming: async (name: string) => { + if (opts.readFails) throw new Error('sys_job unreadable'); + const row = rows.get(name); + return row ? { active: row.active, schedule: null, lastAliveAt: null } : null; + }, + }; + const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }; + const ctx = { + logger, + getService: (name: string) => { + if (name === 'job') return svc; + if (name === 'protocol') return { registerUninstallCleanup: (n: string, f: any) => cleanups.set(n, f) }; + throw new Error(`no ${name}`); + }, + } as unknown as PluginContext; + return { + logger, + keys: () => [...scheduled.keys()].sort(), + schedule: (packageId: string, marker: string) => + scheduleAppArtifactJobs(ctx, { ...pkg([markedJob('shared_tick', marker)]), id: packageId }, { appId: packageId, ql: engine.ql as any, source: 'Test' }), + uninstall: (packageId: string) => cleanups.get(PACKAGE_JOBS_UNINSTALL_CLEANUP)!({ packageId }), + /** Fire whatever this process holds under `key` once; the marker its body wrote. */ + fire: async (key: string) => { + const before = engine.writes.length; + await scheduled.get(key)!({ jobId: key }); + return engine.writes.slice(before).map((w) => (w.data as { name: string }).name); + }, + }; + }; + return { rows, boot }; + } + + it('a job stored under its bare key before the upgrade is scheduled under it again, and fires', async () => { + const store = catalogue(); + // The catalogue as an earlier release left it: the job's row under its authored name. + store.rows.set('shared_tick', { active: true }); + + const after = store.boot(); + const out = await after.schedule(APP_ID, 'mine'); + + expect(out.bodies).toEqual(['shared_tick']); + expect(after.keys()).toEqual(['shared_tick']); + expect(await after.fire('shared_tick')).toEqual(['mine']); + }); + + it('a restart in the install order schedules every job under the key it had (control)', async () => { + const store = catalogue(); + const first = store.boot(); + await first.schedule(APP_ID, 'mine'); + await first.schedule(OTHER, 'theirs'); + + const second = store.boot(); + await second.schedule(APP_ID, 'mine'); + await second.schedule(OTHER, 'theirs'); + + expect(second.keys()).toEqual([`${OTHER}:shared_tick`, 'shared_tick']); + expect(await second.fire('shared_tick')).toEqual(['mine']); + expect(await second.fire(`${OTHER}:shared_tick`)).toEqual(['theirs']); + }); + + it('a restart that schedules the second package FIRST still hands it its own scoped key — never the first package\'s bare one', async () => { + const store = catalogue(); + const first = store.boot(); + await first.schedule(APP_ID, 'mine'); + await first.schedule(OTHER, 'theirs'); + + const second = store.boot(); + await second.schedule(OTHER, 'theirs'); + await second.schedule(APP_ID, 'mine'); + + expect(second.keys()).toEqual([`${OTHER}:shared_tick`, 'shared_tick']); + // Each catalogue row keeps running its OWN package's body. + expect(await second.fire('shared_tick')).toEqual(['mine']); + expect(await second.fire(`${OTHER}:shared_tick`)).toEqual(['theirs']); + // Said once, naming the key and where it came from. + const said = second.logger.info.mock.calls.filter((c) => String(c[0]).includes('keeps its package-scoped identity')); + expect(said).toHaveLength(1); + expect(said[0][1]).toEqual({ appId: OTHER, job: 'shared_tick', scheduledAs: `${OTHER}:shared_tick` }); + }); + + it('a scoped holder whose bare holder was uninstalled keeps its scoped key across a restart, as it does in-process', async () => { + const store = catalogue(); + const first = store.boot(); + await first.schedule(APP_ID, 'mine'); + await first.schedule(OTHER, 'theirs'); + await first.uninstall(APP_ID); + expect(first.keys()).toEqual([`${OTHER}:shared_tick`]); + + const second = store.boot(); + await second.schedule(OTHER, 'theirs'); + + expect(second.keys()).toEqual([`${OTHER}:shared_tick`]); + expect(await second.fire(`${OTHER}:shared_tick`)).toEqual(['theirs']); + }); + + it('a scoped key the catalogue holds CANCELLED keeps nothing: the package, alone after a restart, takes its authored name', async () => { + const store = catalogue(); + const first = store.boot(); + await first.schedule(APP_ID, 'mine'); + await first.schedule(OTHER, 'theirs'); + await first.uninstall(OTHER); + await first.uninstall(APP_ID); + + const second = store.boot(); + await second.schedule(OTHER, 'theirs'); + + expect(second.keys()).toEqual(['shared_tick']); + expect(second.logger.info.mock.calls.some((c) => String(c[0]).includes('keeps its package-scoped identity'))).toBe(false); + }); + + it('a catalogue read that fails schedules the job anyway, by this run\'s order, and says so at warn', async () => { + const store = catalogue({ readFails: true }); + const boot = store.boot(); + + const out = await boot.schedule(OTHER, 'theirs'); + + expect(out.bodies).toEqual(['shared_tick']); + expect(out.failed).toEqual([]); + expect(boot.keys()).toEqual(['shared_tick']); + const warned = boot.logger.warn.mock.calls.filter((c) => String(c[0]).includes('could not read the job catalogue')); + expect(warned).toHaveLength(1); + expect(warned[0][1]).toMatchObject({ appId: OTHER, job: 'shared_tick' }); + }); +}); + describe('#21489: the sandbox job origin', () => { it("a job body with no timeoutMs gets the runner's JOB default — not the hook's, not the action's", async () => { const runner = new QuickJSScriptRunner({ jobTimeoutMs: 30, hookTimeoutMs: 5_000, actionTimeoutMs: 5_000 }); diff --git a/packages/runtime/src/app-artifact-handlers.ts b/packages/runtime/src/app-artifact-handlers.ts index f980f08feb0..1fb1fd13059 100644 --- a/packages/runtime/src/app-artifact-handlers.ts +++ b/packages/runtime/src/app-artifact-handlers.ts @@ -98,13 +98,16 @@ * `{ isSystem: true, tenantId: }`, or `{ isSystem: true }` for a * job that declares none ({@link jobExecutionContext}). * - * A job's identity is the package's and the job's name together, as the - * metadata registry keys it (`:`), so two packages may each - * declare a job of the same name and both run (#21602). The job service keys by - * one string, so a job is scheduled under its authored name unless another - * package already holds that name on the service, and then under the registry's - * package-scoped key ({@link jobKeyFor}). A runtime where no two packages share - * a job name schedules every job under its authored name, exactly as before. + * A job's identity is its package coordinate — the package's id and the job's + * name together, as the metadata registry keys it (`:`; + * ADR-0150 D2/D4) — so two packages may each declare a job of the same name and + * both run (#21602). The job service keys by one string, so a job is scheduled + * under its authored name unless another package already holds that name on + * the service, and then under the registry's package-scoped key + * ({@link jobKeyFor}). A key the job catalogue already holds for that + * coordinate stays the job's key across a restart, whatever order the boot + * schedules packages in. A runtime where no two packages share a job name + * schedules every job under its authored name, exactly as before. * * ## A hook with no `body`, on a door that carries no runtime module (#21585) * @@ -726,10 +729,12 @@ export interface AppArtifactJobScheduling { * job the same `timeoutMs` also bounds the sandbox run — the one limit * `JobSchema.timeoutMs` states. * - * Each job is scheduled under the key {@link jobKeyFor} gives it (#21602): its - * authored name, or — when another package already holds that name on the job - * service — the registry's package-scoped `:`, so the two coexist - * rather than the later one replacing the earlier. The key is the job SERVICE's + * Each job is scheduled under the key {@link jobKeyFor} gives its package + * coordinate (#21602, ADR-0150 D4): its authored name, or — when another + * package already holds that name on the job service, or the job catalogue + * still holds this job under it — the registry's package-scoped + * `:`, so the two coexist rather than the later one replacing the + * earlier, and neither key moves to the other package on a restart. The key is the job SERVICE's * name for the job (the `sys_job` / `sys_job_run` name an operator reads); the * job's own code and every count this function returns keep the authored name. * @@ -983,9 +988,10 @@ export async function scheduleAppArtifactJobs( form = 'handler'; } - // [#21602] The job service's name for this job: the authored name, or - // the package-scoped key when another package already holds it. - const { key, heldBy } = jobKeyFor(jobService, appId, jobName); + // [#21602, ADR-0150 D4] The job service's name for this job's package + // coordinate: the authored name, or the package-scoped key when another + // package already holds it or the job catalogue keeps this job under it. + const { key, heldBy, catalogued } = await jobKeyFor(jobService, { packageId: appId, name: jobName }, logger, tag); try { await jobService.schedule( key, @@ -1008,6 +1014,12 @@ export async function scheduleAppArtifactJobs( + `scheduled under its package-scoped identity '${key}', the name it carries in the job catalogue and run history`, { appId, job: jobName, scheduledAs: key, heldBy }, ); + } else if (catalogued) { + logger.info( + `${tag} job '${jobName}' keeps its package-scoped identity '${key}': the job catalogue holds it active under that name ` + + 'from an earlier run of this package, so its catalogue row and run history stay where they are', + { appId, job: jobName, scheduledAs: key }, + ); } } catch (err: any) { out.failed.push(jobName); @@ -1103,31 +1115,105 @@ function otherHolderOf(svc: IJobService, appId: string, key: string): string | u } /** - * The key `appId`'s job `jobName` is scheduled under on `svc` (#21602). + * A job's identity under package addressing (ADR-0150 D2/D4): the package that + * declares it and its authored name. The package is the app id the job is + * scheduled under, which both doors derive the way the registry derives the + * package id (`manifest.id`, else `manifest.name`; `artifactPackageId`). + */ +interface JobCoordinate { + readonly packageId: string; + readonly name: string; +} + +/** The registry's package-scoped key for a coordinate, `:`. */ +function packageScopedJobKey(coordinate: JobCoordinate): string { + return `${coordinate.packageId}:${coordinate.name}`; +} + +/** + * The job catalogue reading `DbJobAdapter.readArming` gives — OPTIONAL and + * adapter-local, NOT part of `IJobService` (the schedule trigger reads it the + * same way). A job service without it keeps no catalogue across a restart, so + * there is no stored key to keep. + */ +interface JobCatalogueReader { + readArming?(name: string): Promise<{ readonly active: boolean } | null>; +} + +/** + * Does the job catalogue hold `coordinate` ACTIVE under its package-scoped key + * — scheduled by an earlier run of this package and never cancelled? A + * cancel (a replace that drops the job, the package's uninstall) clears + * `active`; a runtime that stops does not. Only the package-scoped key is + * read: it names its package, so the reading is about THIS job and no other. + * The bare key names none, and is never read as anyone's. * - * The job's identity is `(appId, jobName)` — the metadata registry keys a - * packaged item `:` — but the job service keys by one string - * and REPLACES a job of the same name, so two packages' same-named jobs need two - * strings. In order: + * A read that fails is no reading: the job takes the in-process answer, as a + * job service without a catalogue does, and that is said at `warn` — the job + * still runs, and only its catalogue name may move. + */ +async function catalogueHoldsScopedKey(svc: IJobService, coordinate: JobCoordinate, logger: Logger, tag: string): Promise { + const reader = svc as IJobService & JobCatalogueReader; + if (typeof reader.readArming !== 'function') return false; + const key = packageScopedJobKey(coordinate); + try { + return (await reader.readArming(key))?.active === true; + } catch (err) { + logger.warn( + `${tag} could not read the job catalogue for '${key}' — job '${coordinate.name}' is keyed by this run's scheduling order, ` + + 'so on a runtime where another package declares the same job name its catalogue row and run history may move to the other name', + { appId: coordinate.packageId, job: coordinate.name, error: err instanceof Error ? err.message : String(err) }, + ); + return false; + } +} + +/** + * The key `coordinate`'s job is scheduled under on `svc` (#21602, ADR-0150 D4). + * + * The job's identity is its package coordinate `(packageId, name)` — the + * metadata registry keys a packaged item `:` — but the job + * service keys by one string and REPLACES a job of the same name, so two + * packages' same-named jobs need two strings. In order: * - * 1. the key this app already holds the job under — a reinstall replaces its - * own job and keeps its catalogue row and run history; - * 2. else the authored name, when no other package holds it — so a runtime + * 1. the key this package already holds the job under in this process — a + * reinstall replaces its own job and keeps its catalogue row and run + * history; + * 2. else the package-scoped key, when the job catalogue holds it active + * ({@link catalogueHoldsScopedKey}) — an earlier run scheduled this job + * under it, so a restart that schedules the packages in another order + * never hands this job's name to another package's job, nor this job the + * name another package's catalogue row and run history carry; + * 3. else the authored name, when no other package holds it — so a runtime * in which no two packages share a job name schedules every job under its * authored name, unchanged; - * 3. else the registry's package-scoped key `:`, which no + * 4. else the registry's package-scoped key `:`, which no * authored name can equal (`JobSchema.name` is snake_case, so it never - * carries the `:`) and no other app ever derives. + * carries the `:`) and no other package ever derives. + * + * `heldBy` names the package that holds the authored name when (4) applies: + * the package that scheduled it first in this process. `catalogued` says (2) + * applied. * - * `heldBy` names the package that holds the authored name when (3) applies: - * the package that scheduled it first in this process — on a restart, the - * first package the boot schedules. + * ⛔ Nothing here resolves a bare name to a package: a job is scheduled by its + * own package, so its coordinate is known, and the bare key only ever goes to + * a package that asks for its own job. The catalogue is read for the asking + * package's own scoped key only, never to guess who holds a bare one. */ -function jobKeyFor(svc: IJobService, appId: string, jobName: string): { key: string; heldBy?: string } { - const mine = scheduledByApp(svc).get(appId)?.get(jobName); +async function jobKeyFor( + svc: IJobService, + coordinate: JobCoordinate, + logger: Logger, + tag: string, +): Promise<{ key: string; heldBy?: string; catalogued?: true }> { + const mine = scheduledByApp(svc).get(coordinate.packageId)?.get(coordinate.name); if (mine !== undefined) return { key: mine }; - const heldBy = otherHolderOf(svc, appId, jobName); - return heldBy === undefined ? { key: jobName } : { key: `${appId}:${jobName}`, heldBy }; + // The catalogue read is awaited BEFORE the in-process holder is asked, so + // the window between that answer and `claimJobKey` is no wider than before. + const catalogued = await catalogueHoldsScopedKey(svc, coordinate, logger, tag); + const heldBy = otherHolderOf(svc, coordinate.packageId, coordinate.name); + if (catalogued) return { key: packageScopedJobKey(coordinate), ...(heldBy === undefined ? { catalogued } : { heldBy }) }; + return heldBy === undefined ? { key: coordinate.name } : { key: packageScopedJobKey(coordinate), heldBy }; } /** From ffa24bd0eb22f067c8176b70b12f6b2889a929cb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 00:05:16 +0000 Subject: [PATCH 2/2] test(runtime): pay the metadata load at collection in the job binder suite Claude-Session: https://claude.ai/code/session_01ADHkmNp8ARUNvemy119dY1 Co-authored-by: Claude --- packages/runtime/src/app-artifact-handlers.jobs.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/runtime/src/app-artifact-handlers.jobs.test.ts b/packages/runtime/src/app-artifact-handlers.jobs.test.ts index 4786d088d32..a86affde74a 100644 --- a/packages/runtime/src/app-artifact-handlers.jobs.test.ts +++ b/packages/runtime/src/app-artifact-handlers.jobs.test.ts @@ -30,6 +30,9 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid at collection, not inside a clocked case: `AppPlugin` (imported below) +// loads `@objectstack/metadata` dynamically (check:test-source-alias). +import '@objectstack/metadata'; import type { PluginContext } from '@objectstack/core'; import { scheduleAppArtifactJobs, collectJobsWithoutBody, PACKAGE_JOBS_UNINSTALL_CLEANUP } from './app-artifact-handlers.js'; import { jobBodyRunnerFactory } from './sandbox/body-runner.js';