Skip to content

Commit 783a569

Browse files
fix(rest): the knowledge_source save reads a scoped knowledge factory in the request's environment (#38325)
Fixes #38211 Clause-②: yes (widening) — `@objectstack/rest`'s exported `RestServer` constructor takes an optional trailing `classifiedKernelServiceProvider`, which makes `ClassifiedKernelServiceLookup` reachable Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:宿主按环境注册知识服务时,经 REST 保存知识源不再一律报"这个部署没装知识服务":该环境有实例就正常保存,没有实例就说明是该环境没有实例,和内部调度入口的说法一字不差;平台自带的知识服务路径不变。 - 为什么做:属于知识库与检索(AI 知识源)这条线,是上一轮"按范围落空时单独说明原因"在 REST 入口的收尾。 - 出错会怎样:只影响自己按环境注册知识服务的宿主(少见),最坏是保存被拒或报错措辞不对,可以直接撤回。 - 要你做什么:无。 ## What changes **Measured first (the card's What 1).** A real `ObjectKernel` with a `ServiceLifecycle.SCOPED` `knowledge` factory, the real `RestApiPlugin` on it (scoping on), `PUT /api/v1/environments/env_alpha/meta/knowledge_source/faq` through `RestServer`, on base `f19350b410`: | Registration | Status | Sentence | |:---|:---|:---| | factory serving `env_beta` only (the miss) | `503 SERVICE_UNAVAILABLE` | "The knowledge source 'faq' was not saved: this deployment runs no knowledge service, so nothing would load, index or search it. Add requires: ['knowledge'] to the stack ..." | | factory serving `env_alpha` (should be admitted) | `503 SERVICE_UNAVAILABLE` | the same no-service sentence; the service was never asked and nothing was saved | | plain instance | `200` | saved | So the premise holds, and the defect is wider than the card says: the single-kernel provider read the slot with `ctx.getService`, which cannot build a factory and names no scope, so every author's save on a host with a scoped factory was refused, including in an environment the factory serves. On the hosted shape (a kernel manager in front of environment kernels) the provider read the environment kernel without a scope id, and the same save was refused `503` as "could not be judged (the knowledge service could not be resolved: Scope ID required for scoped service 'knowledge')". That reading comes from the ablation run below. **The fix (`@objectstack/rest`).** - `RestApiPlugin` builds `classifiedKernelServiceProvider`. It takes the legs of `environmentScopedProvider`: the request environment's kernel, or this plugin's own kernel for no id or `platform`. The read differs in two ways. It hands the environment id to `getServiceAsync` as the scope id, and a plain instance ignores that id. The own-kernel leg also reads through `getServiceAsync` (as `objectQLOnOwnKernel` does), so a factory can be built. The provider answers the three non-fault outcomes that the runtime dispatcher's `classifyService` answers: `resolved`, `never-registered`, and `no-instance-in-scope`. Any other rejection is raised again. A `LiteKernel`-shaped host keeps the quiet probe. The plugin still never falls back to its own occupant for an environment whose kernel carries none. - `RestServer.resolveKnowledgeService` reads that provider when it is given one. It maps `no-instance-in-scope` to `knowledgeServiceNotInScope(scopeId)` from `@objectstack/metadata-core`, as `resolveKnowledgeServiceForSave` does in the runtime. So `authoredKnowledgeSourceRefusal` answers the scope sentence on both transports. A server built without the provider (hand-built, or a test double) reads `kernelServiceProvider` exactly as before. - No other seam changes. `kernelServiceProvider` and every `environmentScopedProvider` slot are untouched. **File surface.** The claim named `rest-server.ts`, its tests and a changeset. The fix also edits `rest-api-plugin.ts`, the composition root that builds the provider. A `RestServer` has no handle on the kernel, so it cannot make a scoped read by itself. ## Tests `packages/rest/src/rest-environment-scoped-providers.test.ts` gains a new top-level describe in the shared real-kernel harness for these provider seams: `[ADR-0161 K4] the knowledge_source save reads a scoped knowledge factory in the request's environment`. Every case boots real `ObjectKernel`s and the real `createRestApiPlugin()`. The identity is the real resolution plus the save door's two capabilities. - Single kernel, factory serving another environment: `503 SERVICE_UNAVAILABLE`, first sentence `The knowledge source 'faq' was not saved: the knowledge service registered on this deployment serves no instance for environment 'env_alpha'`. The whole message equals what `authoredKnowledgeSourceRefusal` answers for `knowledgeServiceNotInScope('env_alpha')`, which is the value the dispatcher's doors hand it for the same miss. So both transports give one sentence for one miss. The message has no "runs no knowledge service". The service is not asked, and nothing is saved. - CONTROL: the factory serving this environment admits the save, and a plain instance admits it on both mounts. - CONTROL: nothing registered keeps the no-service sentence. - A request that names no environment, against a scoped registration, gets `503` with the "could not be judged" sentence (the registry's own `Scope ID required`). - Hosted: each environment kernel's own scoped factory is read in that environment. The miss gets the scope sentence for `env_beta`, and the served environment is admitted and saved. <details><summary>Readings</summary> Head `3620e2bb898` unless marked otherwise. - The new describe and the slot-lookup ledger, `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/rest-api-plugin-slot-lookups.test.ts src/rest-environment-scoped-providers.test.ts`: `Test Files 2 passed (2)`, `Tests 164 passed (164)`. The lock printed `VERDICT command-exit 0`. - `pnpm --filter @objectstack/rest typecheck` passed, including `check:test-typecheck: OK — @objectstack/rest's test layer compiles under packages/rest/tsconfig.test.json`. - The whole package at `e78a8cd8d21` (one commit earlier), `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2`: `Test Files 1 failed | 439 passed (440)`, `Tests 1 failed | 9306 passed | 376 skipped`. The one red was `rest-api-plugin-slot-lookups.test.ts > accounts for every positional argument from the first provider to the last`, the positional-argument ledger asking for the new argument 24. `3620e2bb898` adds its `NON_PROVIDERS_IN_SPAN` row and a case that pins the lookup, and that file is green above. The last commit touches only that test file. - Ablation at `d6197a14ace` (the fix commit), through `scripts/ablation-replace.mjs`. The mutation removed the `classifiedKernelServiceProvider` argument from the `RestServer` construction, and the anchor went x1 to x0. Result: `Tests 4 failed | 1 passed`. Every new case went red except the nothing-registered control, which should be unchanged. The hosted miss read the old `could not be judged (... Scope ID required for scoped service 'knowledge')`. The restore matched the HEAD blob, and `git diff HEAD` was empty. </details> ## Acceptance notes - **Hosted, factory on the HOST kernel.** The dispatcher's `classifyService` reads the host kernel first, with the scope id, and then the request kernel. REST still reads only the request environment's kernel, by the environment-scoped seam rule: no fall back to the plugin's own occupant. So on a hosted shape where the scoped `knowledge` factory sits on the host kernel and not on the environment kernels, the dispatcher can admit a save that REST answers with the no-service sentence. This PR does not change which kernels REST reads. Nothing here registers `knowledge` on a host kernel in that shape. Carrier: none. Noted, not filed. ## Verification Read first, by risk: 1. `packages/rest/src/rest-api-plugin.ts`: `classifiedKernelServiceProvider`, the three-way `read` and the own-kernel leg. This is the only place the scope id is passed. 2. `packages/rest/src/rest-server.ts`: `resolveKnowledgeService`. The new branch and the unchanged fallback for a server built without the provider. Two-minute check: `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/rest-environment-scoped-providers.test.ts -t 'scoped knowledge factory'` should print five passing tests. <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` was run on `3620e2bb898` and derived 73 families. Each was run on that head with its exit code captured before any pipe. `--ran` reconciliation: `73 derived famil(ies) accounted for — 71 run, 2 NOT-MEASURED (2 DERIVED from a recorded exit 3)`. - 71 exited 0. - NOT MEASURED: `pnpm check:type-check-debt`. Its re-measure builds under the shared verify lock and exited 3 waiting on it. A second run was stopped rather than queued. CI runs it. - NOT MEASURED: `pnpm check:dual-build-cjs-loads`. PREREQUISITE NOT MET: it needs a whole-workspace `pnpm build`, and only the rest closure was built here. CI runs it. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5f741ed commit 783a569

5 files changed

Lines changed: 341 additions & 8 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/rest': patch
3+
---
4+
5+
fix(rest): the `knowledge_source` save reads a scoped knowledge factory in the request's environment, and answers its miss as the dispatcher does
6+
7+
Clause-②: yes (widening) — `@objectstack/rest`'s exported `RestServer` constructor takes an optional trailing `classifiedKernelServiceProvider`, which makes `ClassifiedKernelServiceLookup` reachable
8+
Metadata-protocol: none
9+
10+
- **What was wrong.** On a host that registers `knowledge` as a scoped factory, `PUT /meta/knowledge_source/:name` over REST read the service without the request's environment as its scope. On a single kernel the lookup could not build a factory at all, so every author's save was refused `503 SERVICE_UNAVAILABLE` with "this deployment runs no knowledge service", including a save in an environment the factory serves. On a host that fronts environment kernels, the same save was refused `503` because the service "could not be judged (Scope ID required for scoped service 'knowledge')". The runtime dispatcher's `/meta` save already named the environment for a real miss.
11+
- **What changes.** `RestApiPlugin` reads `knowledge` in the request's environment, using the environment id as the scope id. A plain instance ignores the scope id, so the platform's `KnowledgeServicePlugin` path is unchanged. A factory that serves the environment is now asked, and the save is admitted. A factory that serves no instance there is refused `503 SERVICE_UNAVAILABLE` with the same sentence the dispatcher answers, which names the environment and does not point to the stack's `requires`. A deployment with nothing registered under `knowledge` keeps the no-service sentence. A request that names no environment, made against a scoped registration, is refused `503` as a lookup that could not be made: the registry rejects a scoped read that names no scope, and the dispatcher's lookup keeps that rejection loud as well.
12+
- **Who is affected.** Only a host that registers its own scoped `knowledge` factory. No action is needed.

‎packages/rest/src/rest-api-plugin-slot-lookups.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,11 @@ const NON_PROVIDERS_IN_SPAN = [
214214
label: 'environmentMembership',
215215
why: '`{ enforced: boolean }` — the host\'s environment-membership switch, a value resolved at boot, not a slot provider; pinned in `rest-environment-membership-door.test.ts`',
216216
},
217+
{
218+
index: 24,
219+
label: 'classifiedKernelServiceProvider',
220+
why: '`(name, environmentId?) => Promise<ClassifiedKernelServiceLookup>` — the same BY-NAME lookup made in the request\'s environment, with its two quiet misses told apart, for the `knowledge_source` save (ADR-0161 K4); names no slot of its own; pinned by its own case below and on real kernels in `rest-environment-scoped-providers.test.ts`',
221+
},
217222
] as const;
218223

219224
/**
@@ -416,6 +421,19 @@ describe('[#4251 B4] rest-api-plugin slot lookups', () => {
416421
await expect(byName('nope-not-registered')).resolves.toBeUndefined();
417422
});
418423

424+
it('answers the classified by-name lookup on the kernel of the environment asked for (ADR-0161 K4)', async () => {
425+
const services = allServices();
426+
const { args } = await boot(services);
427+
const km = services['kernel-manager'] as ReturnType<typeof envKernelManager>;
428+
const classified = args[24] as (name: string, environmentId?: string) => Promise<unknown>;
429+
430+
expect(typeof classified, 'classifiedKernelServiceProvider must be wired at argument 24').toBe('function');
431+
await expect(classified('approvals', 'env_1')).resolves.toEqual({ outcome: 'resolved', value: km.occupantOf('env_1', 'approvals') });
432+
await expect(classified('approvals')).resolves.toEqual({ outcome: 'resolved', value: services.approvals });
433+
await expect(classified('approvals', 'platform')).resolves.toEqual({ outcome: 'resolved', value: services.approvals });
434+
await expect(classified('nope-not-registered')).resolves.toEqual({ outcome: 'never-registered' });
435+
});
436+
419437
it('asks for exactly the slots it declares, and no others', async () => {
420438
const services = allServices();
421439
const { args, asked } = await boot(services);

‎packages/rest/src/rest-api-plugin.ts‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { Plugin, PluginContext, IHttpServer, isServiceNotRegisteredError, resolveEnvironmentMembershipEnforcement } from '@objectstack/core';
44
import { RestServer, RestKernelManager, RestProtocol, RestRequestEnvResolver, RestEnvRegistry } from './rest-server.js';
5+
import type { ClassifiedKernelServiceLookup } from './rest-server.js';
56
import { RestServerConfig } from '@objectstack/spec/api';
67
import { mountAndRecordDirectRoutes } from './direct-mount-composition.js';
78
import type { ResolvedSettingValue } from '@objectstack/spec/system';
@@ -576,6 +577,68 @@ export function createRestApiPlugin(config: RestApiPluginConfig = {}): Plugin {
576577
const kernelServiceProvider = (name: string, environmentId?: string): Promise<unknown> =>
577578
environmentScopedProvider<unknown>(name)(environmentId);
578579

580+
// [ADR-0161 K4, guard two] The same by-name lookup, made IN the
581+
// request's environment and with its two quiet misses told apart,
582+
// for the one door whose answer differs between them: the
583+
// `knowledge_source` save, whose "this deployment runs no knowledge
584+
// service" is false where a host registers `knowledge` as a scoped
585+
// factory. The runtime dispatcher's save doors read the same
586+
// three outcomes (`HttpDispatcher#classifyService`), so both
587+
// transports answer one miss with one sentence.
588+
//
589+
// The legs are `environmentScopedProvider`'s, with the environment
590+
// id handed to the read as its scope id (a plain instance ignores
591+
// it), and the own-kernel leg read through `getServiceAsync`, as
592+
// `objectQLOnOwnKernel` reads it: `ctx.getService` cannot construct
593+
// a factory, so it folded a scoped registration into "nothing is
594+
// registered" whatever the scope. ⛔ No fall back to this plugin's
595+
// occupant for an environment whose kernel carries none.
596+
//
597+
// - a value → `resolved`;
598+
// - the branded "never registered" rejection → `never-registered`;
599+
// - a registration that produced no instance → `no-instance-in-scope`
600+
// when the read named a scope, else `never-registered`;
601+
// - any other rejection (a factory that threw, a scoped
602+
// registration read with no scope) → re-raised: the door
603+
// answers it as a lookup that could not be made.
604+
const classifiedKernelServiceProvider = async (
605+
name: string,
606+
environmentId?: string,
607+
): Promise<ClassifiedKernelServiceLookup> => {
608+
const read = async (get: () => Promise<unknown>): Promise<ClassifiedKernelServiceLookup> => {
609+
let svc: unknown;
610+
try {
611+
svc = await get();
612+
} catch (err) {
613+
if (isServiceNotRegisteredError(err)) return { outcome: 'never-registered' };
614+
throw err;
615+
}
616+
if (svc != null) return { outcome: 'resolved', value: svc };
617+
return environmentId === undefined
618+
? { outcome: 'never-registered' }
619+
: { outcome: 'no-instance-in-scope', scopeId: environmentId };
620+
};
621+
// A kernel this lookup reads in a scope. `RestKernelManager`
622+
// declares the one-argument read the other seams make; the
623+
// kernels a host's manager hands out (`ObjectKernel`) take the
624+
// scope id as the second.
625+
type ScopedRead = { getServiceAsync(name: string, scopeId?: string): Promise<unknown> };
626+
if (kernelManager && environmentId && environmentId !== 'platform') {
627+
const kernel = (await kernelManager.getOrCreate(environmentId)) as ScopedRead;
628+
return read(() => kernel.getServiceAsync(name, environmentId));
629+
}
630+
const own = (typeof ctx.getKernel === 'function' ? ctx.getKernel() : undefined) as Partial<ScopedRead> | undefined;
631+
if (own && typeof own.getServiceAsync === 'function') {
632+
return read(() => own.getServiceAsync!(name, environmentId));
633+
}
634+
// A `KernelBase`-shaped host (`LiteKernel`) has no service
635+
// factories, so "not registered" is the only miss it has.
636+
try {
637+
const svc = ctx.getService<unknown>(name);
638+
return svc != null ? { outcome: 'resolved', value: svc } : { outcome: 'never-registered' };
639+
} catch { return { outcome: 'never-registered' }; }
640+
};
641+
579642
if (!server) {
580643
ctx.logger.warn(`RestApiPlugin: HTTP Server service '${serverService}' not found. REST routes skipped.`);
581644
return;
@@ -615,7 +678,7 @@ export function createRestApiPlugin(config: RestApiPluginConfig = {}): Plugin {
615678
enforceProjectMembership: config.enforceProjectMembership,
616679
enableProjectScoping: config.api?.api?.enableProjectScoping,
617680
}),
618-
});
681+
}, classifiedKernelServiceProvider);
619682
restServer.registerRoutes();
620683

621684
ctx.logger.info('REST API successfully registered');

0 commit comments

Comments
 (0)