Skip to content

Commit 50d6da8

Browse files
fix(objectql): a package registered again stops serving an object extension its new manifest dropped (#36325)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbCxiFE11rsKwyNffJZKYqJs)_ Fixes #35609 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:开发者在本地开发热重载时删掉扩展包给别人对象加字段的声明、或升级/重装一个不再加这些字段的扩展包后,这些字段会立刻从对象上消失,不再需要重启。 - 为什么做:修复「扩展包升级后旧字段还挂在对象上」的数据配置错误,替做扩展包升级和本地开发热重载的构建者解决。 - 出错会怎样:最坏情况是某个包重新注册时误撤了它仍声明的扩展字段,字段在界面和接口上暂时消失;已存数据不受影响,回滚此改动或重启即可恢复。 - 要你做什么:无。 ## What changes `SchemaRegistry.replacingPackageBody` (the wrapper around every `ObjectQL.registerApp` body registration, which since #33050 withdraws the items a new body no longer ships) now does the same for object extensions: - Before the body registers, it notes the package's current `extend` layer of each object. After it registers, a layer that is a new contributor is one this body wrote (the extend splice always replaces the package's layer with a new contributor). - The layers the previous body wrote, for objects the new body no longer extends, are withdrawn through `withdrawObjectExtension`, the existing per-object withdrawal the `object_extension` item delete uses (uninstall's package-wide walk is not reused: it also removes owned objects). Only the very layer the previous body wrote is withdrawn, so a layer another door registered under the package id since (the `object_extension` item door) is kept. - `withdrawObjectExtension` now records the object's layers in an open registration run before it removes one (`noteObjectEntry`), so a refusal later in the run (a later artifact member, the run-end follow door) puts the extension back. Outside a run this is a no-op, so the item-delete caller is unchanged. - The record (`packageBodyExtensions`) is put back on refusal and forgotten by `uninstallPackage`, beside `packageBodyItems`. Everything an extension contributes rides on its one contributor layer (fields, `fieldPatches`, label texts, validations, indexes), so all of it leaves together. Stored data is untouched: the column keeps its values and schema sync drops nothing; the field is no longer served. ## Measure first (the card's steps), on main `c30ce97cd7` | Path | Re-registers without uninstalling? | Dropped extension's field still served on main? | What said anything | |:--|:--|:--|:--| | Bare `registerApp` (card repro) | yes | yes: field, validation and index all served, `com.t.mod:extend` layer kept | nothing | | `os dev` reload: `metadata:reloaded` → `ObjectQLPlugin.refreshReloadedPackages` → `registerApp` | yes (refresh, never uninstall) | yes | nothing: no warn, schema sync adds only | | `os dev` reload, full standalone composition (`createStandaloneStack`, the artifact door's `_reloadAndAnnounce`) | yes | NOT MEASURED on this composition: neither the first run nor the hand-over round got the shared verify lock (the round queued about 80 minutes behind two dogfood batteries). The probe is written (a two-package composed artifact, the extension dropped by the door's own reload, plus a CONTROL reload) and is held by the seat; it reaches the same `metadata:reloaded` hook measured in the row above | nothing | | install-local upgrade 1.0.0 → 1.0.1 dropping the extension (`manifest.register`, no uninstall) | yes | yes: `crm_line` served and `find` returned `cb_account` | the dry run's plan DID say so: `plan.fields.removed` names `crm_line.cb_account`, `environment.columns` `reasons: ['removed'], rows: 1`; removed fields need no confirmation (`schemaUpgradeVerdict`: reported, refused by nothing), so the upgrade answered 200 and then kept serving the field the plan said was removed | | install-local re-install of the same id and version without the extension | yes | yes | nothing | Stored column, both before and after the fix: `crm_line.cb_account` keeps its column and its value `ACME` (schema sync drops no column). After the fix every row above reads "no": the object serves `name` only, `find` no longer returns `cb_account`, the column still holds `ACME`, and the dry run's plan is unchanged (it already named the field as removed; now the runtime agrees with it). ## Tests - `packages/objectql/src/reregister-extension-withdraw-35609.test.ts` (new): re-register without the extension (fields, validation and index gone, owner kept); CONTROL rename; another package's extension of the same target untouched; same body again keeps it; an extension registered under the id outside a body kept; a refusal later in the run puts it back (and the record with it); the reload door drops it, CONTROL reload keeps it. - `packages/cloud-connection/src/marketplace-install-local-reregister-extension-withdraw-35609.test.ts` (new): real kernel, SQL driver, real schema sync, the install-local door: upgrade dropping the extension (plan names the field, object no longer serves it, column keeps its value), same-version re-install, CONTROL upgrade keeping it. <details><summary>Readings (ablation: the four fixed objectql files put back to main, then restored byte-identical to HEAD)</summary> One locked run, `unfixed-vs-fixed` legs over the same two commands. The objectql and cloud-connection suites both resolve `@objectstack/objectql` to `packages/objectql/src` (stack frames read `../objectql/src/...`), so no dist rebuild was involved; the on-disk proof is the marker count (`packageBodyExtensions` in `registry-items.ts`: 0 in the unfixed leg, 9 in the fixed leg) and the restore was proven by an empty `git diff HEAD` and matching `git hash-object` = `HEAD:path` for each file. - UNFIXED (main's four files): `reregister-extension-withdraw-35609.test.ts` 5 failed / 3 passed (the controls pass), `package-refused-upgrade-keeps-installed` and `manifest-service-artifact-refusal-restores` green: `Tests 5 failed | 76 passed (81)`. Install-local readings: `served after upgrade [ 'cb_account', 'name' ]`, `find` returns `"cb_account":"ACME"`, re-install without the extension `[ 'cb_account', 'name' ]`. - FIXED (HEAD): `Test Files 3 passed (3) · Tests 81 passed (81)`; install-local `served after upgrade [ 'name' ]`, `find` row has no `cb_account`, `column after upgrade {"hasColumn":true,"values":["ACME"]}`, re-install without the extension `[ 'name' ]`. - `pnpm --filter @objectstack/objectql test` at the fix (objectql src as on head `555ef3e2c7`): `Test Files 627 passed (627) · Tests 14240 passed (14240)`. - `pnpm --filter @objectstack/objectql typecheck`: exit 0 (`tsc --noEmit`, then `check:test-typecheck: OK`, debt held). </details> ## Acceptance notes - Clause-②: no. Nothing is refused: a body registered again is never refused over an extension it drops; the dropped layer is withdrawn. - Owned objects a re-registered body no longer ships are still kept until a restart; `ingestReloadedObjects`' docblock calls that deliberate ("same lifecycle as their tables"). Not touched here. - `ObjectQLPlugin.refreshReloadedPackages`' docblock still says items removed from the artifact stay registered until restart; that has been out of date since the item withdrawal landed and is now out of date for extensions too. Not edited (outside this card's file surface). Carried by #36328. - Inferred, not exercised: a withdrawal (this one, an uninstall, an `object_extension` item delete) is not asked the run-end record-currency follow door, which judges registered layers only. A withdrawn extension carrying a currency code field another package's amount follows would leave that pair unjudged until the follower re-registers. Same gap for the two existing withdrawal doors; not filed. Carried by #36328. - Inferred edge: if a withdrawn layer was the object's last contributor (an extension with no owner, already an ADR-0029 violation), the entry is closed and a refusal later in the run restores the contributor list without reopening the entry. Unreachable through a valid registration. - Serial constraint: #36236 (shares `registry.ts`, and places extension items in the fold) has since landed on `main` as `d33bf5a2`. `overlap-check` against `origin/main` `d8599c2ca2` reads clean, and GitHub reports the PR mergeable. This PR's CI ran on the merge with `99fbaa6d`, before #36236 landed, so the joint tree is first tested in the merge queue. Read, not run: a placement rides on its extension's contributor layer and is applied in the fold, so a withdrawn layer takes its placements with it. `registry-object-registration.ts` is not touched. - Prior rulings: `check-prior-rulings --card 35609` over the four files read; no conflict. The closest precedents are the item withdrawal this extends (same wrapper, same restore discipline), ADR-0144 D2/D6 (the run-end follow door, unchanged), ruling A on #35228 (one extension per target per package, unchanged) and ruling 6624345766 (facade form: `registry.ts` gains only a state field, docblocks and host wiring; `check:facade-delegation-only` green). Since main grew `registry.ts`, the file also sits under its facade line ceiling (6426, ruling 6897467376): the long #35609 prose lives in the facet docblock in `registry-items.ts`, and the ceiling is not raised. ## Verification <details><summary>Merge-queue red at 555ef3e, fixed at 368b000 (repo:objectstack#7)</summary> - What failed: the merge queue dequeued this PR (merge-group run 45007098161, job 137160994478, `Lint · repo & tooling gates`). `check-facade-delegation-only --self-test` case N6 printed: `the committed registry is red: is 6441 lines, over its line ceiling of 6426 by 15`. The PR was green on its own head. Main had grown `registry.ts` to 6409 lines, and this PR's +32 went over the ceiling. - Fix (`53d2506ddb`, `368b000bed`): merged `origin/main` `4e55e4eb72` (a merge, no rebase, no force-push). Then I did what the rule says to do: "a file in facade form does not grow". The detailed extension-withdrawal prose moved from the facade docblocks to the facet docblock on `ItemsFacet.replacingPackageBody` (`registry-items.ts`). The facade keeps a short contract paragraph, and the field doc is one line. The ceiling row is untouched, so the check is not weakened. - Comment-only proof: both files were transpiled with `removeComments`, before and after `368b000bed`. Each pair is byte-identical (`registry.ts` sha256 prefix `b87e53ad1efa` both sides, `registry-items.ts` `afb1b850be15` both sides). A control leg with one injected token compared different (cmp exit 1). - `pnpm check:facade-delegation-only`: exit 0. `N6 the committed registry is well-formed against this checkout` passes, and the check prints `packages/objectql/src/registry.ts: 6421 lines, ceiling 6426 (5 left; ruling 6897467376)`. - `dispatch-gates --commands` at `368b000bed`: 73 derived. 71 exit 0. `check:dual-build-cjs-loads` and `check:type-check-debt` exit 3 (PREREQUISITE NOT MET: no full `dist/`), so NOT MEASURED locally and carried by CI's Build Core and debt-ledger lanes. `--ran` with exit codes: 73 derived, 71 run, 2 NOT-MEASURED, 0 unrun. Gate derivation read a tree 7 commits behind the newest `origin/main` `ff60149900`. None of this PR's files moved there, so I did not merge again. - `overlap-check --branch`: `VERDICT clean exit 0` against `origin/main` `ff60149900`. - NOT MEASURED locally: the `@objectstack/objectql` test suite and typecheck at the merged head. Reason: the shared verify lock. Three 9-minute tries all ended in queue-timeout behind a dogfood battery (holder pid 13599, more than 39 minutes). This is a declared narrowing. The fix commit compiles to identical JS (proof above), and CI's Test Core and Type Check lanes run both on the merge. The objectql dependency closure did build under the lock (`VERDICT command-exit 0`). </details> <details><summary>Local gates at 555ef3e</summary> - `dispatch-gates --commands`: 73 commands derived; all run. 70 exit 0. `check:query-options-erasure` went red (test surface 236 to 237) on a cast in the new cloud-connection pin; fixed in `555ef3e2c7` and re-run green (236). `check:dual-build-cjs-loads` and `check:type-check-debt` exited 3 (PREREQUISITE NOT MET: no full `dist/`, and the closure build never got the shared lock): NOT MEASURED locally, CI's `Lint & Repo Gates` carries both. - Re-run on the final head after the last edit: `cross-package-test-inputs`, `test-source-alias`, `nul-bytes`, `refd-timer-probe`, `tier-file-adoption`, `issue-citations`, `doc-authoring`, `facade-delegation-only`: all exit 0. - `dispatch-gates --ran`: 73 derived, 73 run, 0 unrun. - `overlap-check --branch=HEAD`: clean against origin/main and #36236. - Not run locally, declared to CI: `test:repo`, the full cloud-connection suite (only the new file was run), and the Build Core / Type Check workspace lanes. CI has since run all of them at this head (round below). - Dogfood battery: not owed (no `!`, no narrowing arm). </details> <details><summary>Hand-over round (repo:objectstack#7) at the same head 555ef3e: the local gaps closed</summary> No commit in this round; the head declared final stays `555ef3e2c7`. CI ran this head on the merge with `99fbaa6d` (`b97f554d`), and every gate-carrying check-run concluded `success`. - Cloud-connection new file, rerun after the cast removal: `Test Core` at this head, `@objectstack/cloud-connection:test` printed `src/marketplace-install-local-reregister-extension-withdraw-35609.test.ts (3 tests)` passed. The objectql file printed `src/reregister-extension-withdraw-35609.test.ts (8 tests)` passed. All 10 `Test Core` shards: success. - Cloud-connection typecheck: `Type Check · workspace` ran `@objectstack/cloud-connection:typecheck`; `Tasks: 124 successful, 124 total`; success. - `check:dual-build-cjs-loads`: `Build Core` step "Every published require entry point actually loads": success. - `check:type-check-debt`: `Type Check · debt ledger` step "Re-measure the type-check DEBT / TEST_DEBT ledger": success, lane verdict success. - Derived gates re-run locally at `555ef3e2c7`, against `origin/main` `c448c615`: `dispatch-gates --commands` derived 73 commands. 68 exited 0. Five exited 3, PREREQUISITE NOT MET (no built `dist/`; the closure build never got the lock). CI carries all five at this head with success: `dts-closure` (Build Core "Sweep the built closure for vanished declarations"), `dual-build-cjs-loads`, `lean-entry-closure` (Build Core "The lean engine entry loads no forbidden or unlisted package"), `sourcemap-no-sources-content` (Build Core "No published source map embeds source text") and `type-check-debt` (above). `dispatch-gates --ran` with the exit codes recorded: 73 derived, 68 run, 5 NOT-MEASURED (derived from exit 3), 0 unrun. - Still NOT MEASURED: the full `createStandaloneStack` reload probe. Reason: the shared verify lock. This round queued about 80 minutes behind two dogfood batteries (holder pid 5424 over 67 minutes), and retaking the same slot after each exit 99 put the call back behind newer arrivals. No CI job runs this probe. </details> Two-minute check: `pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/reregister-extension-withdraw-35609.test.ts` prints 8 passed; revert `registry-items.ts` to `origin/main` and the same command prints 5 failed. Read first, by risk: `packages/objectql/src/registry-items.ts` (`replacingPackageBody`, the identity test that decides which layers the body wrote), `packages/objectql/src/registry-platform-global.ts` (`withdrawObjectExtension` now notes the run), `packages/objectql/src/registry.ts` (host wiring and the record). Written by repo:objectstack#4 · os-project-manager · session_01FEkQ5miLqNucRZevceHwNh (PM-dispatched dev run); continued after the hand-over by repo:objectstack#7 · zhuangjianguo · session_01QsR2jTeURPvEm465RcoYEC. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jTeURPvEm465RcoYEC <!-- signed: repo:objectstack#7 · zhuangjianguo · session_01QsR2jTeURPvEm465RcoYEC --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e9da898 commit 50d6da8

7 files changed

Lines changed: 545 additions & 6 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a package registered again stops serving an object extension its new manifest no longer declares
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
When a package was registered again without uninstalling it first (an `os dev` artifact reload, or an upgrade or re-install through the marketplace install-local door) and its new manifest no longer carried an `objectExtensions` entry for an object the previous registration extended, the old extension stayed registered. Its fields, validations and indexes kept being served on that object until the process restarted. A package's previous extension of an object was replaced only when the new manifest named that same object again.
11+
12+
A re-registered package body now withdraws each extension its previous body registered for an object the new body no longer extends, through the same per-object withdrawal the `object_extension` item delete uses. The object then serves exactly the extensions the package's current manifest declares. Another package's extension of the same object is untouched, and so is an extension registered under the package id outside a body (the `object_extension` item door's layer). A refusal later in the same registration run puts the withdrawn extension back with the rest of the installed version.
13+
14+
Stored data is not touched: the column the dropped field used keeps its values, and schema sync drops no column. The field is simply no longer served. The install-local dry run already listed the dropped field under `plan.fields.removed`; that answer is unchanged.
Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#35609] The install-local door: an upgrade or a re-install of a package
5+
* whose new version no longer extends an object serves that object without
6+
* the dropped extension's fields, with no restart.
7+
*
8+
* The door registers the new version through the `manifest` service without
9+
* uninstalling the installed one first (an upgrade and a re-install of the
10+
* same id are both a hot re-register). Before the fix the registry withdrew a
11+
* package's previous extension of a target only when the new registration
12+
* named that target again, so a dropped extension kept serving its fields.
13+
*
14+
* Real here: an `ObjectKernel` with a SQL driver and `ObjectQLPlugin` (the
15+
* `manifest` service over the real `SchemaRegistry`, and the real schema
16+
* sync), the base package registered at boot as code. The door's side readers
17+
* (binder, translations, seeds) are recorders, as in the hot-resync suite.
18+
*
19+
* What it pins, per door: the served object; the dry run's plan names the
20+
* dropped field; the stored column and its value are untouched (the field is
21+
* no longer served, nothing is dropped); and the CONTROL, a version that keeps
22+
* the extension, keeps the field.
23+
*/
24+
25+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
26+
import { mkdtempSync, rmSync } from 'node:fs';
27+
import { join } from 'node:path';
28+
import { tmpdir } from 'node:os';
29+
// The first load of the runtime's dist paid at module top, never inside a
30+
// clocked `it` (`scripts/check-test-source-alias.mjs`): the plugin reaches the
31+
// same module through a dynamic `import()` for its handler binder.
32+
import '@objectstack/runtime';
33+
import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core';
34+
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
35+
import { SqlDriver } from '@objectstack/driver-sql';
36+
import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js';
37+
import { installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js';
38+
39+
type Handler = (c: any) => Promise<any>;
40+
41+
const CORE = 'com.acme.core';
42+
const MOD = 'com.acme.mod';
43+
const SYSTEM = { context: { isSystem: true } } as const;
44+
45+
const core = {
46+
id: CORE,
47+
name: 'Core',
48+
namespace: 'crm',
49+
version: '1.0.0',
50+
type: 'app',
51+
objects: [{ name: 'crm_line', label: 'Line', fields: { name: { type: 'text', label: 'Name' } } }],
52+
};
53+
54+
/** The module's install body at `version`, extending `crm_line` with `cb_account` unless `extends` is false. */
55+
const mod = (version: string, opts: { extends: boolean }) => ({
56+
manifest: {
57+
id: MOD,
58+
name: 'Mod',
59+
namespace: 'crmmod',
60+
version,
61+
type: 'module',
62+
dependencies: { [CORE]: '^1.0.0' },
63+
objectExtensions: opts.extends
64+
? [{ extend: 'crm_line', fields: { cb_account: { type: 'text', label: 'Account' } } }]
65+
: [],
66+
},
67+
});
68+
69+
function makeRawApp() {
70+
const routes = new Map<string, Handler>();
71+
return {
72+
routes,
73+
get: (p: string, h: Handler) => routes.set(`GET ${p}`, h),
74+
post: (p: string, h: Handler) => routes.set(`POST ${p}`, h),
75+
delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h),
76+
};
77+
}
78+
79+
function makeC(body: any) {
80+
return {
81+
req: {
82+
url: 'http://localhost:3000/api/v1/marketplace/install-local',
83+
raw: new Request('http://localhost:3000/x'),
84+
json: async () => body,
85+
param: () => undefined,
86+
},
87+
json: vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })),
88+
};
89+
}
90+
91+
let dir: string;
92+
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-35609-')); });
93+
afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks(); });
94+
95+
async function bootDoor() {
96+
const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never);
97+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
98+
let kernelCtx: PluginContext | undefined;
99+
await kernel.use({
100+
name: 'test.35609.driver',
101+
type: 'standard',
102+
version: '1.0.0',
103+
async init(ctx: PluginContext) { ctx.registerService('driver.default', driver); },
104+
} as Plugin);
105+
await kernel.use(new ObjectQLPlugin());
106+
await kernel.use({
107+
name: 'test.35609.core',
108+
type: 'standard',
109+
version: '1.0.0',
110+
dependencies: ['com.objectstack.engine.objectql'],
111+
async init(ctx: PluginContext) {
112+
kernelCtx = ctx;
113+
await ctx.getService<{ register(m: unknown): unknown }>('manifest').register(core);
114+
},
115+
} as Plugin);
116+
await kernel.bootstrap();
117+
const ql = kernel.getService<ObjectQL>('objectql');
118+
ql.registry.logLevel = 'silent';
119+
120+
const rawApp = makeRawApp();
121+
const hooks = new Map<string, any>();
122+
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
123+
const services: Record<string, unknown> = {
124+
manifest: kernel.getService('manifest'),
125+
auth: installerAuthService(),
126+
objectql: withInstallerGrants({
127+
convertPackageBodyForward: (body: unknown) => ql.convertPackageBodyForward(body),
128+
registry: ql.registry,
129+
get manifests() { return (ql as unknown as { manifests: Map<string, unknown> }).manifests; },
130+
syncSchemas: () => ql.syncSchemas(),
131+
find: (...a: Parameters<ObjectQL['find']>) => ql.find(...a),
132+
count: (...a: Parameters<ObjectQL['count']>) => ql.count(...a),
133+
}),
134+
};
135+
const ctx: any = {
136+
hook: (e: string, h: any) => hooks.set(e, h),
137+
trigger: (event: string, payload: unknown) => kernelCtx!.trigger(event, payload),
138+
getService: (name: string) => {
139+
if (name === 'http-server') return { getRawApp: () => rawApp };
140+
if (!(name in services)) throw new Error(`no ${name}`);
141+
return services[name];
142+
},
143+
logger,
144+
};
145+
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir });
146+
const p = plugin as unknown as Record<string, unknown>;
147+
p.bindArtifactHandlers = async () => undefined;
148+
p.applySideEffects = async () => ({ translationsLoaded: 0, seeded: { mode: 'none' } });
149+
await plugin.start(ctx);
150+
await hooks.get('kernel:ready')?.();
151+
152+
const post = async (body: unknown) => rawApp.routes.get('POST /api/v1/marketplace/install-local')!(makeC(body));
153+
const servedFields = (): string[] => Object.keys((ql.registry.getObject('crm_line') as any)?.fields ?? {})
154+
.filter((f) => f === 'name' || f.startsWith('cb_')).sort();
155+
const knex = (driver as unknown as { knex: any }).knex;
156+
const column = async () => {
157+
const rows = await knex('crm_line').select('*');
158+
return { hasColumn: await knex.schema.hasColumn('crm_line', 'cb_account'), values: rows.map((r: any) => r.cb_account) };
159+
};
160+
return { kernel, ql, post, servedFields, column, logger };
161+
}
162+
163+
async function settle(k: { kernel: ObjectKernel }) {
164+
await Promise.race([k.kernel.shutdown(), new Promise<void>((r) => setTimeout(r, 10_000))]);
165+
}
166+
167+
describe('[#35609] install-local: a version that no longer extends an object serves it without the extension', () => {
168+
it('an upgrade that drops the extension: the plan names the field, the object no longer serves it, the column keeps its value', async () => {
169+
const k = await bootDoor();
170+
try {
171+
expect((await k.post(mod('1.0.0', { extends: true }))).payload?.data?.hotLoaded).toBe(true);
172+
expect(k.servedFields()).toEqual(['cb_account', 'name']);
173+
await k.ql.insert('crm_line', { id: 'l1', name: 'one', cb_account: 'ACME', organization_id: 'org_a' }, SYSTEM);
174+
175+
// The dry run already said so (unchanged by this fix): the field is removed, its column holds a row.
176+
const dry = await k.post({ ...mod('1.0.1', { extends: false }), dryRun: true });
177+
expect(dry.status).toBe(200);
178+
expect(dry.payload.data.plan.fields.removed).toEqual([expect.objectContaining({ object: 'crm_line', field: 'cb_account' })]);
179+
expect(dry.payload.data.environment.columns).toEqual([expect.objectContaining({ object: 'crm_line', field: 'cb_account', reasons: ['removed'], rows: 1 })]);
180+
181+
const upgraded = await k.post(mod('1.0.1', { extends: false }));
182+
expect(upgraded.status, JSON.stringify(upgraded.payload)).toBe(200);
183+
expect(upgraded.payload.data.hotLoaded).toBe(true);
184+
185+
expect(k.servedFields()).toEqual(['name']);
186+
const [row] = (await k.ql.find('crm_line', { where: {}, ...SYSTEM })) as Array<Record<string, unknown>>;
187+
expect(row).toMatchObject({ id: 'l1', name: 'one' });
188+
expect(row).not.toHaveProperty('cb_account');
189+
// Stored data is untouched: nothing drops the column.
190+
expect(await k.column()).toEqual({ hasColumn: true, values: ['ACME'] });
191+
} finally {
192+
await settle(k);
193+
}
194+
}, 60_000);
195+
196+
it('a re-install of the same version without the extension withdraws it too', async () => {
197+
const k = await bootDoor();
198+
try {
199+
await k.post(mod('1.0.0', { extends: true }));
200+
expect(k.servedFields()).toEqual(['cb_account', 'name']);
201+
const res = await k.post(mod('1.0.0', { extends: false }));
202+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
203+
expect(k.servedFields()).toEqual(['name']);
204+
} finally {
205+
await settle(k);
206+
}
207+
}, 60_000);
208+
209+
it('CONTROL: an upgrade that keeps the extension keeps its field', async () => {
210+
const k = await bootDoor();
211+
try {
212+
await k.post(mod('1.0.0', { extends: true }));
213+
const res = await k.post(mod('1.0.1', { extends: true }));
214+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
215+
expect(k.servedFields()).toEqual(['cb_account', 'name']);
216+
} finally {
217+
await settle(k);
218+
}
219+
}, 60_000);
220+
});

‎packages/objectql/src/registry-items.ts‎

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
collectBundle, entriesOfMember, isStoredActionRow, overlaySlotEntriesOf, packageBodySlot, packagelessActionOwnerKey,
4444
packagelessActionSlotEntriesOf, packagelessActionSlotKey,
4545
} from './registry-top-level.js';
46+
import type { ObjectContributor } from './registry-top-level.js';
4647
import type { SchemaRegistry } from './registry.js';
4748

4849
/**
@@ -58,20 +59,39 @@ export interface ItemsHost {
5859
invalidateAll: SchemaRegistry['invalidateAll'];
5960
log: SchemaRegistry['log'];
6061
readonly metadata: SchemaRegistry['metadata'];
62+
readonly objectContributors: SchemaRegistry['objectContributors'];
6163
noteBareNameClaim: SchemaRegistry['noteBareNameClaim'];
6264
noteItem: SchemaRegistry['noteItem'];
6365
noteItemOrder: SchemaRegistry['noteItemOrder'];
6466
noteSecurityCatalogClaim: SchemaRegistry['noteSecurityCatalogClaim'];
6567
openPackageBody: SchemaRegistry['openPackageBody'];
6668
orderedOverlayTier: SchemaRegistry['orderedOverlayTier'];
69+
readonly packageBodyExtensions: SchemaRegistry['packageBodyExtensions'];
6770
readonly packageBodyItems: SchemaRegistry['packageBodyItems'];
6871
readonly restorePoint: SchemaRegistry['restorePoint'];
6972
readonly securityCatalogClaims: SchemaRegistry['securityCatalogClaims'];
7073
unregisterPicklistExtensionsByPackage: SchemaRegistry['unregisterPicklistExtensionsByPackage'];
74+
withdrawObjectExtension: SchemaRegistry['withdrawObjectExtension'];
7175
withdrawPackageBodyItemsNotShipped: SchemaRegistry['withdrawPackageBodyItemsNotShipped'];
7276
withdrawPackageClaimsNotDeclared: SchemaRegistry['withdrawPackageClaimsNotDeclared'];
7377
}
7478

79+
/**
80+
* [#35609] Each object `packageId` holds an `extend` layer of, by key: the
81+
* layer itself, so a caller can tell a layer it saw from one written since.
82+
*/
83+
function packageExtensionLayers(
84+
objectContributors: ReadonlyMap<string, readonly ObjectContributor[]>,
85+
packageId: string,
86+
): Map<string, ObjectContributor> {
87+
const layers = new Map<string, ObjectContributor>();
88+
for (const [fqn, contributors] of objectContributors) {
89+
const layer = contributors.find((c) => c.ownership === 'extend' && c.packageId === packageId);
90+
if (layer) layers.set(fqn, layer);
91+
}
92+
return layers;
93+
}
94+
7595
/** The bodies of the "Generic metadata items and package bodies" section of `SchemaRegistry`: a stateless facet, called by the class's stubs. */
7696
export class ItemsFacet {
7797
/**
@@ -202,23 +222,71 @@ export class ItemsFacet {
202222
return { removed, orphanedOverlays };
203223
}
204224

205-
/** The body of `SchemaRegistry#replacingPackageBody`; the method's docblock there is its contract. */
206-
static replacingPackageBody<T>(this: Pick<ItemsHost, 'openPackageBody' | 'packageBodyItems' | 'restorePoint' | 'withdrawPackageBodyItemsNotShipped' | 'withdrawPackageClaimsNotDeclared'>, packageId: string | undefined, manifest: ObjectStackManifest, register: () => T): T {
225+
/**
226+
* The body of `SchemaRegistry#replacingPackageBody`; the method's docblock there is its contract.
227+
*
228+
* [#35609] The extension half in detail: `packageBodyExtensions` holds, per package id, the
229+
* extension layers its last body wrote, by object key — the layer object itself, so a layer
230+
* another door has since put in the package's slot of that object (the `object_extension`
231+
* item door) is told apart and kept. A dropped target's layer leaves through `withdrawObjectExtension`, the per-target
232+
* withdrawal the `object_extension` item delete uses, so the target serves exactly the
233+
* extensions the current manifest declares. Before this, the extend splice replaced the
234+
* package's layer only for a target the new body named again, and a dropped extension kept
235+
* its fields served until a restart. Schema sync drops no column. The withdrawal is recorded
236+
* in the open run, so a refusal later in it puts the layer back. The map is forgotten by
237+
* `uninstallPackage`.
238+
*/
239+
static replacingPackageBody<T>(this: Pick<ItemsHost, 'log' | 'objectContributors' | 'openPackageBody' | 'packageBodyExtensions' | 'packageBodyItems' | 'restorePoint' | 'withdrawObjectExtension' | 'withdrawPackageBodyItemsNotShipped' | 'withdrawPackageClaimsNotDeclared'>, packageId: string | undefined, manifest: ObjectStackManifest, register: () => T): T {
207240
if (!packageId) return register();
208241
const open = this.openPackageBody;
209242
const body = { packageId, written: new Set<string>() };
243+
// [#35609] The package's extension layers before the body registers. The
244+
// extend splice replaces a package's layer of a target with a NEW
245+
// contributor, so a layer still the same object afterwards is one this
246+
// body did not write.
247+
const extensionsBefore = packageExtensionLayers(this.objectContributors, packageId);
210248
this.openPackageBody = body;
211249
let result: T;
212250
try {
213251
result = register();
214252
} finally {
215253
this.openPackageBody = open;
216254
}
255+
const extended = new Map<string, ObjectContributor>();
256+
for (const [fqn, layer] of packageExtensionLayers(this.objectContributors, packageId)) {
257+
if (extensionsBefore.get(fqn) !== layer) extended.set(fqn, layer);
258+
}
217259
const previous = this.packageBodyItems.get(packageId);
218260
if (previous !== undefined) {
219261
this.withdrawPackageBodyItemsNotShipped(packageId, previous, body.written);
220262
this.withdrawPackageClaimsNotDeclared(packageId, manifest);
221263
}
264+
// [#35609] …and the extension layers the previous body wrote of a target
265+
// this one does not extend, through the per-target withdrawal the
266+
// `object_extension` item delete uses. Only the layer that body wrote:
267+
// one another door has since put in the package's slot is not the body's.
268+
const previousExtensions = this.packageBodyExtensions.get(packageId);
269+
if (previousExtensions !== undefined) {
270+
const withdrawn: string[] = [];
271+
for (const [fqn, layer] of previousExtensions) {
272+
if (extended.has(fqn) || !this.objectContributors.get(fqn)?.includes(layer)) continue;
273+
if (this.withdrawObjectExtension(fqn, packageId)) withdrawn.push(fqn);
274+
}
275+
if (withdrawn.length > 0) {
276+
this.log(
277+
`[Registry] Withdrew ${withdrawn.length} object extension(s) package ${packageId}'s new body no longer declares: ${withdrawn.join(', ')}`,
278+
);
279+
}
280+
}
281+
this.restorePoint?.note(`packageBodyExtensions\u0000${packageId}`, () => {
282+
const had = this.packageBodyExtensions.has(packageId);
283+
const saved = this.packageBodyExtensions.get(packageId);
284+
return () => {
285+
if (had && saved !== undefined) this.packageBodyExtensions.set(packageId, saved);
286+
else this.packageBodyExtensions.delete(packageId);
287+
};
288+
});
289+
this.packageBodyExtensions.set(packageId, extended);
222290
this.restorePoint?.note(`packageBody\u0000${packageId}`, () => {
223291
const had = this.packageBodyItems.has(packageId);
224292
const saved = this.packageBodyItems.get(packageId);

0 commit comments

Comments
 (0)