Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/38573-merged-list-row-binding.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/metadata-protocol': patch
---

fix(metadata-protocol): the merged metadata list files a stored row's copy under the row's package column, never under the package its body names

Clause-②: no
Metadata-protocol: none

`getMetaItems` (`GET /api/v1/meta/:type`) lays the stored rows over the items the `metadata` service lists. On a hosted kernel that service holds a copy of each stored row it read, and its `list` answers that copy's body, so a body whose `_packageId` named another package than the row's package column put the copy in that package's slot: the row was listed twice (once under its column, once under the body's package), a list scoped to the body's package (`?package=`) served it as that package's item, and a row with no package column was listed as the body's package's. A skill bound to one app could be listed as another app's skill.

The merge now reads the service's items through `listPackageBindings` when the service offers it, and files each item a stored row holds under that row's column, as the stored rows themselves are served: a row bound to one package is listed once, under it, and a row with an empty column is listed under no package. An item no stored row holds keeps the package its registration files it under. A `metadata` service without `listPackageBindings` is read as before. The binding read is kept on the footing the service keeps `list` on: one answer per type, served again while the service's change counter (`revision`) stands and for no longer than the service memoizes `list`, so a read inside an open transaction (a flow re-sync during a package move) does not wait on the stored rows each time.
120 changes: 120 additions & 0 deletions packages/metadata-protocol/src/listed-package-bindings.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#38573] `listedPackageBoundItems`: the merged list read's binding read keeps
* the service's `list` footing. Before, the merge asked `listPackageBindings`
* on every call, uncached, and on the dogfood stack a package move's flow
* re-sync waited up to 281 ms for it inside the move's transaction, so the
* moved flow was armed after the move answered (`package-move-in.dogfood`,
* A3: 404 at the package's address).
*/
import { describe, expect, it, vi, type Mock } from 'vitest';
import type { MetadataPackageBinding } from '@objectstack/spec/contracts';
import { DEGRADED_LIST_BOUND_MS, LIST_BOUND_MS, listedPackageBoundItems } from './listed-package-bindings.js';

const ROW_PKG = 'com.example.policy';
const BODY_PKG = 'com.example.crm';

function service(opts: { revision?: number; degraded?: boolean; bindings?: boolean } = {}) {
const items: MetadataPackageBinding[] = [
{ name: 'differs', data: { name: 'differs', _packageId: BODY_PKG }, packageId: ROW_PKG, source: 'row' },
{ name: 'legacy', data: { name: 'legacy', _packageId: BODY_PKG }, packageId: null, source: 'row' },
{ name: 'shipped', data: { name: 'shipped', _packageId: BODY_PKG }, packageId: BODY_PKG, source: 'registration' },
];
const svc: Record<string, unknown> = {
list: vi.fn(async () => items.map((b) => b.data)),
...(opts.revision !== undefined ? { revision: opts.revision } : {}),
};
if (opts.bindings !== false) {
svc.listPackageBindings = vi.fn(async () => ({ items, degraded: opts.degraded ?? false, errors: [] }));
}
return svc as unknown as {
list: Mock<(type: string) => Promise<unknown[]>>;
listPackageBindings: Mock<(type: string) => Promise<{ items: MetadataPackageBinding[]; degraded: boolean; errors: string[] }>>;
revision?: number;
};
}

const filed = (items: unknown[]) => (items as Array<{ name: string; _packageId?: string }>).map((i) => `${i.name}|${i._packageId ?? '(none)'}`);

describe('[#38573] listedPackageBoundItems', () => {
it("files a row's copy under its column, a legacy row under none, and a registration as registered", async () => {
expect(filed(await listedPackageBoundItems(service({ revision: 1 }), 'skill'))).toEqual([
`differs|${ROW_PKG}`, 'legacy|(none)', `shipped|${BODY_PKG}`,
]);
});

it("reads the bindings once while the service's revision stands and the list bound has not passed (BEFORE: once per call)", async () => {
const svc = service({ revision: 7 });
let now = 1_000;
for (let i = 0; i < 3; i++) await listedPackageBoundItems(svc, 'skill', () => now);
now += LIST_BOUND_MS - 1;
expect(filed(await listedPackageBoundItems(svc, 'skill', () => now))).toEqual([
`differs|${ROW_PKG}`, 'legacy|(none)', `shipped|${BODY_PKG}`,
]);
expect(svc.listPackageBindings).toHaveBeenCalledTimes(1);
expect(svc.list).not.toHaveBeenCalled();
});

it('reads again once the revision moves, per type', async () => {
const svc = service({ revision: 1 });
await listedPackageBoundItems(svc, 'skill');
await listedPackageBoundItems(svc, 'agent');
svc.revision = 2;
await listedPackageBoundItems(svc, 'skill');
expect(svc.listPackageBindings.mock.calls.map((c) => c[0])).toEqual(['skill', 'agent', 'skill']);
});

it("reads again once the service's list bound passes: 30 s, 2 s for a degraded answer", async () => {
let now = 0;
const healthy = service({ revision: 1 });
await listedPackageBoundItems(healthy, 'skill', () => now);
now = LIST_BOUND_MS;
await listedPackageBoundItems(healthy, 'skill', () => now);
expect(healthy.listPackageBindings).toHaveBeenCalledTimes(2);

now = 0;
const degraded = service({ revision: 1, degraded: true });
await listedPackageBoundItems(degraded, 'skill', () => now);
now = DEGRADED_LIST_BOUND_MS - 1;
await listedPackageBoundItems(degraded, 'skill', () => now);
now = DEGRADED_LIST_BOUND_MS;
await listedPackageBoundItems(degraded, 'skill', () => now);
expect(degraded.listPackageBindings).toHaveBeenCalledTimes(2);
});

it('keeps no answer the revision moved under while it was read', async () => {
const svc = service({ revision: 1 });
const read = svc.listPackageBindings.getMockImplementation()!;
svc.listPackageBindings.mockImplementationOnce(async (type: string) => {
svc.revision = 2;
return read(type);
});
await listedPackageBoundItems(svc, 'skill');
await listedPackageBoundItems(svc, 'skill');
expect(svc.listPackageBindings).toHaveBeenCalledTimes(2);
});

it('keeps no failed read: the next call reads again', async () => {
const svc = service({ revision: 1 });
svc.listPackageBindings.mockRejectedValueOnce(new Error('sys_metadata unreachable'));
await expect(listedPackageBoundItems(svc, 'skill')).rejects.toThrow('sys_metadata unreachable');
expect(filed(await listedPackageBoundItems(svc, 'skill'))).toContain(`differs|${ROW_PKG}`);
expect(svc.listPackageBindings).toHaveBeenCalledTimes(2);
});

it('a service with no revision is read every time: no counter is guessed', async () => {
const svc = service();
await listedPackageBoundItems(svc, 'skill');
await listedPackageBoundItems(svc, 'skill');
expect(svc.listPackageBindings).toHaveBeenCalledTimes(2);
});

it("a service with no listPackageBindings answers its list bodies as they are", async () => {
const svc = service({ revision: 1, bindings: false });
expect(filed(await listedPackageBoundItems(svc, 'skill'))).toEqual([
`differs|${BODY_PKG}`, `legacy|${BODY_PKG}`, `shipped|${BODY_PKG}`,
]);
expect(svc.list).toHaveBeenCalledTimes(1);
});
});
87 changes: 87 additions & 0 deletions packages/metadata-protocol/src/listed-package-bindings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#38573, #37039] The metadata service's items for the merged list read,
* each filed under the package it is bound to: a stored row's copy under the
* row's package column ({@link withRowBinding}), ⛔ never under the
* `_packageId` its body carries; an item no stored row holds as its
* registration files it.
*
* ## Why it is memoized here
*
* `IMetadataService.list` is memoized by the service (`MetadataManager`: a
* short-TTL answer, retracted on every change it learns of), and the merged
* list read is on every caller's path, the flow engine's re-sync after a
* metadata write among them. `listPackageBindings` is not: each call walks
* the loaders again and reads the stored rows' columns, which inside an open
* transaction waits for the transaction's lock (measured: up to 281 ms on the
* SQLite dogfood stack during a package move, against 0.1 ms for `list`), and
* the flow engine then armed a moved flow after the move had answered. So the
* binding read keeps the list's footing: one answer per `(service, type)`,
* served again while the service's change counter (`revision`, ADR-0156 D2:
* moved by every path that changes what `list` answers) stands where it
* stood, and only for as long as the service memoizes `list` itself
* ({@link LIST_BOUND_MS}; {@link DEGRADED_LIST_BOUND_MS} for a partial answer).
*
* A service without a numeric `revision` is read every time, as before: ⛔ no
* counter is guessed (ADR-0156 D2). A read the counter moved under is
* answered to its callers and kept by no one. A service without
* `listPackageBindings` cannot tell a row's binding from a body's (its
* contract): its `list` bodies are answered as they are.
*/

import type { MetadataPackageBinding } from '@objectstack/spec/contracts';
import { withRowBinding } from './protocol-package-bindings.js';

/** The service's healthy `list` memo bound (`MetadataManager.LIST_CACHE_TTL_MS`). */
export const LIST_BOUND_MS = 30_000;
/** The service's bound for a `list` answer a lost loader left partial (`DEGRADED_LIST_CACHE_TTL_MS`). */
export const DEGRADED_LIST_BOUND_MS = 2_000;

interface BindingService {
list(type: string): Promise<unknown[]> | unknown[];
listPackageBindings?(type: string): Promise<{ items: MetadataPackageBinding[]; degraded: boolean; errors: string[] }>;
revision?: unknown;
}

interface Kept {
revision: number;
at: number;
read: Promise<{ items: unknown[]; degraded: boolean }>;
}

const kept = new WeakMap<object, Map<string, Kept>>();

function bound(service: BindingService, type: string): Promise<{ items: unknown[]; degraded: boolean }> {
return service.listPackageBindings!(type).then(({ items, degraded }) => ({
items: items.map(({ data, packageId, source }) => (source === 'row' ? withRowBinding(data, packageId) : data)),
degraded,
}));
}

/** The service's items for `type`, each under its binding; see the module header. */
export async function listedPackageBoundItems(service: BindingService, type: string, now: () => number = Date.now): Promise<unknown[]> {
if (typeof service.listPackageBindings !== 'function') return service.list(type);
const revision = service.revision;
if (typeof revision !== 'number') return (await bound(service, type)).items;
let byType = kept.get(service);
if (byType === undefined) kept.set(service, byType = new Map());
const held = byType.get(type);
if (held !== undefined && held.revision === revision) {
const answer = await held.read;
const age = now() - held.at;
if (age < (answer.degraded ? DEGRADED_LIST_BOUND_MS : LIST_BOUND_MS)) return answer.items;
}
const entry: Kept = { revision, at: now(), read: bound(service, type) };
byType.set(type, entry);
try {
const answer = await entry.read;
// A change the counter recorded while the read ran: the answer is the
// callers', and the next read starts again.
if (service.revision !== revision && byType.get(type) === entry) byType.delete(type);
return answer.items;
} catch (error) {
if (byType.get(type) === entry) byType.delete(type);
throw error;
}
}
11 changes: 10 additions & 1 deletion packages/metadata-protocol/src/protocol-meta-list-reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { storedEntryRow } from './protocol-stored-overlay-types.js';
import { viewIdentityPatch } from './protocol-view-normalization.js';
import { isServedOverrideRowOf, type ServedOverrideRow } from './served-override.js';
import { installedManifestsOfEngine } from './installed-manifests.js';
import { listedPackageBoundItems } from './listed-package-bindings.js';
import { listedChangedAt, storedEntryChangedAt, storedRowChangedAt, takeListedRowChangedAt, withListedRowChangedAt } from './listed-row-changed-at.js';
import { packagelessRowWithheld, withServedObjectDecorations } from './protocol-meta-item-face.js';
import {
Expand Down Expand Up @@ -747,7 +748,15 @@ export async function readFlattenedMetaItems(host: Pick<ProtocolHost, 'artifactL
const services = host.getServicesRegistry?.();
const metadataService = services?.get('metadata');
if (metadataService && typeof metadataService.list === 'function') {
let runtimeItems = await metadataService.list(request.type);
// [#38573, #37039] A stored row's copy the service holds (a hosted
// kernel's primed `MetadataManager`) is filed under its row's
// package column, as the stored rows above are ({@link withRowBinding}),
// ⛔ never under the `_packageId` its body carries: that stamp put
// the copy in another package's slot (the row listed twice, and
// under the stamp's package in a list scoped to it) and a legacy
// row with no column under the stamp's package. Read on the
// service's `list` footing ({@link listedPackageBoundItems}).
let runtimeItems = await listedPackageBoundItems(metadataService, request.type);
// [#23645] The service's copy of a stored object row is not the
// base this merge lays the stored rows over: the rows above
// already serve every live one, and a copy of a deleted one
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@
* altered an identity it promised not to. Measured in the PR body.
*/
import { describe, expect, it } from 'vitest';
// Clocked windows measure behaviour, never loading: the list reaches `@objectstack/lint`
// through a dynamic import, so its first load is paid here, during collection.
import '@objectstack/lint';
import { ObjectStackProtocolImplementation } from './protocol.js';
import { assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core';

Expand Down Expand Up @@ -288,3 +291,87 @@ describe('[#7654] the /meta list serves one row per name after a runtime PUT', (
});
});
});

/**
* [#38573, #37039, #28673] On a hosted kernel the `metadata` service is a
* primed `MetadataManager`: its `list` answers the BODY of each stored row it
* read, and a body may carry a `_packageId` stamp naming another package than
* the row's package column (or one while the column is empty: a legacy row).
* The stored rows themselves are served with their column's binding
* (`withRowBinding`), so a copy of the same row re-entering under its body's
* stamp lands in another package's slot: the list served the row twice (once
* under its column, once under its stamp), the list scoped to the stamp's
* package served it as that package's item, and a legacy row stood in for the
* stamp's package. `listPackageBindings` answers each item with its row's
* column, and the merge files a stored row's copy by it.
*/
describe('[#38573] the merged list files a stored row by its package column, never its body stamp', () => {
const ROW_PKG = 'com.example.policy';
const BODY_PKG = 'com.example.crm';

interface Binding { name: string; data: unknown; packageId: string | null; source: 'row' | 'registration' }

/** A primed `metadata` service: `list` answers bodies, `listPackageBindings` the bindings. */
function primedProtocol(engine: any, byType: Record<string, Binding[]>, opts: { withBindings?: boolean } = {}) {
const p = new ObjectStackProtocolImplementation(engine);
const service: Record<string, unknown> = {
list: async (type: string) => (byType[type] ?? []).map((b) => b.data),
};
if (opts.withBindings !== false) {
service.listPackageBindings = async (type: string) => ({ items: byType[type] ?? [], degraded: false, errors: [] });
}
(p as any).getServicesRegistry = () => new Map<string, any>([['metadata', service]]);
return p;
}

const names = (items: any[]): string[] => items.map((i) => `${i.name}|${i._packageId ?? '(none)'}`).sort();

for (const type of ['skill', 'agent'] as const) {
describe(`type \`${type}\``, () => {
const body = (name: string) => ({ name, label: name, _packageId: BODY_PKG });
const engine = () => makeEngine({
rows: [
row({ type, name: 'differs', package_id: ROW_PKG, metadata: body('differs') }),
row({ type, name: 'legacy', metadata: body('legacy') }),
],
});
const service = {
[type]: [
{ name: 'differs', data: body('differs'), packageId: ROW_PKG, source: 'row' as const },
{ name: 'legacy', data: body('legacy'), packageId: null, source: 'row' as const },
],
};

it("lists a row bound to P with a body stamped Q once, under P (BEFORE: under P and under Q)", async () => {
const res: any = await primedProtocol(engine(), service).getMetaItems({ type });
expect(names(res.items)).toEqual([`differs|${ROW_PKG}`, 'legacy|(none)']);
});

it("the list scoped to the body's package holds neither row (BEFORE: both, as its items)", async () => {
const res: any = await primedProtocol(engine(), service).getMetaItems({ type, packageId: BODY_PKG });
expect(names(res.items)).toEqual([]);
});

it("the list scoped to the row's package holds its row once", async () => {
const res: any = await primedProtocol(engine(), service).getMetaItems({ type, packageId: ROW_PKG });
expect(names(res.items).filter((n) => n.startsWith('differs|'))).toEqual([`differs|${ROW_PKG}`]);
});
});
}

it('an item no stored row holds is listed under the package its registration files it under', async () => {
const res: any = await primedProtocol(makeEngine(), {
skill: [{ name: 'shipped', data: { name: 'shipped', _packageId: ROW_PKG }, packageId: ROW_PKG, source: 'registration' }],
}).getMetaItems({ type: 'skill' });
expect(names(res.items)).toEqual([`shipped|${ROW_PKG}`]);
});

it("CONTROL: a service with no listPackageBindings cannot tell a row's binding from a body's, and the list reads its bodies as before", async () => {
const res: any = await primedProtocol(makeEngine({
rows: [row({ type: 'skill', name: 'differs', package_id: ROW_PKG, metadata: { name: 'differs', _packageId: BODY_PKG } })],
}), {
skill: [{ name: 'differs', data: { name: 'differs', _packageId: BODY_PKG }, packageId: ROW_PKG, source: 'row' }],
}, { withBindings: false }).getMetaItems({ type: 'skill' });
expect(names(res.items)).toEqual([`differs|${BODY_PKG}`, `differs|${ROW_PKG}`]);
});
});
Loading