Skip to content

Commit e72f2aa

Browse files
feat(spec,objectql,service-analytics): IObjectQLEngine.fixedReadLeafClassOf, wired into the analytics native path (ADR-0155 D4) (#35954)
Fixes #35946 Clause-②: yes Metadata-protocol: none Stacked on #35945 (ADR-0155 step 5). This pull request's base is `claude/project-thread-thptm0`, at `74cac04849` since the round-1 rebase, so its diff is only this card's change. GitHub retargets it to `main` when #35945 merges. Round 1 (head `e117d86d44`) answers the L2 record 7053241461: S1, N1 and N2. ## 维护者速读 - 用户能看到什么变化:用户无感。分析服务在走原生 SQL 之前,先问数据引擎这条共享过滤条件能不能直接编译。引擎说可以,就走原生路径;否则交给引擎路径。 - 为什么做:属于“共享记录权限下沉到引擎”这条工作线(ADR-0155 第 5 步的收尾)。按你选的方案 A,在引擎接口上加一个可选方法,供分析服务提问。 - 出错会怎样:只影响带共享过滤条件的分析查询走哪条路径。引擎没回答、回答不合约定或出错时,一律交给引擎路径,结果始终正确,最多是变慢;可以直接撤回。 - 要你做什么:无。 ## What changes - **Contract** (`packages/spec/src/contracts/objectql-engine.ts`). A new OPTIONAL member `IObjectQLEngine.fixedReadLeafClassOf(leaf)`, typed `(leaf: FixedReadLeaf) => EngineFixedReadLeafClass | null`. It is the engine seam's ADR-0155 D4 class recognition for a `SharedRecordIds` leaf. It answers `'other-datasource'` or `'registration-by-name'` with what names it, and **`null` when neither class applies**. It throws `TypeError` on a value that is not a fixed-read leaf (`fixedInnerReadOf`), and its one consumer reads a throw as a decline. Because "neither" is `null` and never `undefined`, `engine.fixedReadLeafClassOf?.(leaf)` carries the consumer's whole three-state answer: a class means decline, `null` means compile, and `undefined` from an engine without the member means it cannot say, so decline. The answer type `EngineFixedReadLeafClass` restates objectql's `FixedReadLeafClass`. Its docblock says `ObjectQL implements IObjectQLEngine` checks one direction only: the seam's answer must be assignable to the contract's type. The header's list of members optional by ruling now names it (ruling 7051956587). - **Engine** (`packages/objectql/src/engine.ts`). `ObjectQL.fixedReadLeafClassOf(leaf)` is a one-line forward to `fixedReadLeafClassAnswerOf(this, leaf)`. `IObjectQLEngine` is imported from `@objectstack/spec/contracts` instead of through `@objectstack/core`'s re-export, and that import line also names `EngineFixedReadLeafClass`. The reason was measured. objectql is CommonJS and core is ESM. Through core, the contract's branded `FixedReadLeaf` resolved to spec's `.d.mts` chunk, while engine.ts's own import resolved to the `.d.ts` chunk. The tsup DTS build then failed the `implements` check with TS2416. - **New file `packages/objectql/src/fixed-read-leaf-engine-answer.ts`**. `fixedReadLeafClassAnswerOf(engine, leaf)` returns `fixedReadLeafClassOfEngine(engine, leaf) ?? null`. It is the seam's own recognition, with "neither" spelled `null`. It lives outside engine.ts because the facade gate allows only a one-line forwarding call there, and `?? null` is an operator. `fixed-read-leaf-seam.ts`, which is #35945's file, is untouched. - **Analytics plugin** (`packages/services/service-analytics/src/plugin.ts`). It wires `AnalyticsServiceConfig.fixedReadLeafClassOf`, which #35945 left unwired. It resolves the engine from the `"data"` service on each call, as it does for `hasObjectMiddleware`, and returns `svc.fixedReadLeafClassOf?.(leaf)` as the engine gave it. This plain optional call is **fail-closed by construction**. When there is no engine or `getService` throws, the hook answers `undefined`. An engine without the member also answers `undefined`, and the plugin says so once at `warn`. `NativeSQLStrategy` declines every answer except `null`, so it also declines a class, a throw, and a member that does not keep the contract (one that answers `undefined` for neither). `DataEngineLike`'s `Pick` now includes the member. Neither D4 class is restated in analytics. - **Facade ceiling** (`scripts/facade-delegation-registry.json`, the engine.ts row). Before: `baseLines 6754 @ 63db724, maxLines 6854, ruling 6897467376`. After: `baseLines 6853 @ 170ca48 (origin/main, measured), maxLines 6857, ruling 7051956587`. engine.ts goes from 6853 to 6856 lines, and round 1 added no line to it. The raise is **3**, inside the ruled 3–5. #35773 has since merged to `main` (+1 net). A merge-tree of this head with `origin/main` 7de1bad gives engine.ts 6857 lines, which is at the ceiling with 0 left. The row needs no change for that merge. - **Generated files**: `packages/spec/api-surface/contracts.json` and `packages/spec/export-origins/contracts.json` (the new type export). - **Changeset**: `.changeset/35946-fixed-read-leaf-engine-member.md`, `patch` for `@objectstack/spec`, `@objectstack/objectql` and `@objectstack/service-analytics`. It states the round-1 semantics. ## Why Maintainer ruling A on #35946 (comment 7051956587) has analytics ask the engine seam's D4 recognition through an optional `IObjectQLEngine` member, with no new package dependency on objectql. ADR-0155 D4 says the recognition lives once, in the seam, and that the analytics native compiler "restates none". Without the wiring, once step 6 (#33787) starts writing the leaf, every sharing-scoped analytics query would leave native SQL. Round 1 (S1) makes "neither" `null`, so that an absent member and an answered "neither" can no longer be confused. ## Tests The pin is a `describe` named `[#35946] AnalyticsServicePlugin asks the data engine's fixedReadLeafClassOf`. It sits in the leaf's existing live-SQLite harness `fixed-read-leaf-native-compile.test.ts`, because a new pin for a component with a shared harness goes into that file. The `"data"` engine is a plain object over the live engine's members, so the pin tests the plugin's structural wiring and the engine's own answers. - **(a)** Member present, object in neither class. `engine.fixedReadLeafClassOf(leaf)` is `null`. The raw-SQL seam runs once, the statement carries `IN (SELECT "record_id" FROM "sys_record_share"`, and the rows equal the case set's expected rows. - **(b)** Member present, object in a D4 class (a `beforeFind` hook registered for `sys_record_share`). The engine answers `{ class: 'registration-by-name', table: 'sys_record_share' }`. The raw-SQL seam is never called, and the engine's seam refuses with `INTERNAL_ERROR` / 500. - **(c)** Member absent. The raw-SQL seam is never called, the engine path answers the expected rows, and the plugin warns once. - **(d)** A member that answers `undefined` instead of the contract's `null`. The raw-SQL seam is never called, the engine path answers the expected rows, and nothing warns. Ablations, round 1, at `99ebe34bbd`, all through `scripts/ablation-replace.mjs`. The service-analytics vitest config aliases `@objectstack/objectql` to its source, so no `dist/` sits in the path. Every restore was verified as blob == HEAD with `git diff HEAD` empty. The rebase onto `74cac04849` touched none of the mutated files, and the pins were re-run green after it. ```text A1 wiring removed (the plugin config's fixedReadLeafClassOf line commented out) blob cfbe857 -> af53e0d322c9 x (a) AssertionError: expected "vi.fn()" to be called 1 times, but got 0 times x (c) AssertionError: expected [] to have a length of 1 but got +0 Tests 2 failed | 2 passed | 31 skipped (35) A2 fail-open mutant: return svc.fixedReadLeafClassOf?.(leaf); -> return svc.fixedReadLeafClassOf?.(leaf) ?? null; blob cfbe857 -> 58076b1ce810 x (c) AssertionError: expected "vi.fn()" to not be called at all, but actually been called 2 times (line 384) x (d) AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times (line 393) Tests 2 failed | 2 passed | 31 skipped (35) A3 the engine's null mapping removed (fixed-read-leaf-engine-answer.ts: "?? null" dropped) blob f10e025 -> b6a1d16c5757 x (a) AssertionError: expected undefined to be null Tests 1 failed | 3 passed | 31 skipped (35) ``` A2 is the ruling's original spelling. On the shipped plain `?.()`, pins (c) and (d) prove the wiring fails closed. Round 0's fail-open record (comment 7052875195) used the same mutant against the round-0 code. Package runs, all under `scripts/pm/os-verify-lock.sh`: - The pin file passed 35 of 35 at `99ebe34bbd`, and again at `e117d86d44` after rebuilding the dependency closure. - typecheck for `@objectstack/spec`, `@objectstack/objectql` and `@objectstack/service-analytics` exits 0 at `99ebe34bbd`; service-analytics exits 0 again at `e117d86d44`. - eslint `--no-inline-config` on the five edited source files exits 0 at `e117d86d44`. - The full suites last ran at round 0's `e5dff0f186`: service-analytics had 221 of 221 test files pass (5646 tests passed, 345 skipped); objectql had 625 of 625 files and 14183 of 14183 tests pass. They were not re-run in round 1, and CI runs them. ## Acceptance notes - **Resolved by S1: the earlier deviation from the ruling's spelling.** Round 0 kept "neither" as `undefined` and had the plugin probe with `typeof` before applying `?? null`. With "neither" now `null`, the plain `engine.fixedReadLeafClassOf?.(leaf)` is the hook's whole answer, and it fails closed with no probe. The ruling's original `?? null` survives only as ablation A2, which shows it would fail open. - **Closed: #35945's changeset sentence.** `.changeset/35874-fixed-read-leaf-census-rest.md` had said `AnalyticsServicePlugin` wires no answer in this release. #35945 reworded that clause at `74cac04849` ("the analytics hook ships unwired until its wiring lands, whichever release that is"). That wording holds whichever release this pull request lands in. - **Stacked form.** AGENTS.md multi-agent §2 marks a stacked series as unsupported. This pull request is stacked because the dispatch claim (comment 7052034983) orders it. - **Two declarations.** objectql's `FixedReadLeafClass` and spec's `EngineFixedReadLeafClass` are separate declarations, checked in one direction by `implements` (N1). Aliasing the objectql type to the spec one would remove the second declaration. That edit is in `fixed-read-leaf-seam.ts`, which is #35945's file. - **Docs page.** `content/docs/kernel/contracts/data-engine.mdx` does not list `IObjectQLEngine`'s members one by one; its only reference is `IObjectQLEngine.transaction(cb)`. So no member line was added there. ## Verification Files to read first, by risk: 1. `packages/services/service-analytics/src/plugin.ts`: the `fixedReadLeafClassOf` bridge, a plain optional call that must stay fail-closed. 2. `packages/objectql/src/fixed-read-leaf-engine-answer.ts` together with the member in `packages/spec/src/contracts/objectql-engine.ts`: the `null` for "neither". 3. `scripts/facade-delegation-registry.json`: the engine.ts ceiling row. Two-minute check: run `pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/fixed-read-leaf-native-compile.test.ts -t 35946` and expect 4 passed. Local gates at `99ebe34bbd`, each exiting 0: - facade and repo checks: `check:facade-delegation-only` (engine.ts 6856 of 6857), `check:engine-double-contract`, `check:nul-bytes`, `check:doc-authoring`, `check:test-source-alias`, `check:cross-package-test-inputs`, `check:adr-anchors`, `check:issue-citations`, `check:closed-ceremony-text`; - runtime checks: `check:startup-registry-verdict`, `check:durability-log-level`, `check:optional-error-sink`, `check:logger-receiver-detach`, `check:undeclared-dep-imports`, `check:spec-docblock-symbol-anchors`, `check:scripts-symbol-anchors`, `check:slot-lookup`, `check:init-service-contract`; - changeset checks: `check-empty-changeset`, `check-changeset-no-major`, `check-adr-0087-registration`, `check:changeset-gate-self-tests`; - spec checks: `check:api-surface`, `check:export-origins`, `check:dual-source-exports`, `check:exported-any`, `check:entry-nameability`, and `check:generated` ("All 14 generated artifacts are up to date"); - build and docs checks: `check:dts-closure`, `check:published-files`, and the docs-audit `check-drift-comment` and `check-affected-docs`. Re-run at `e117d86d44`, each exiting 0: `check:facade-delegation-only`, `check:nul-bytes`, spec `check:api-surface` and `check:export-origins`, `check:test-source-alias`, `check:engine-double-contract` and `check-empty-changeset`. overlap-check reports VERDICT clean (exit 0) against `74cac04849` and against `origin/main` 7de1bad. The local runs are a declared narrowing: `dispatch-gates --commands` derives 115 families against `origin/main`, including #35945's files, and CI runs the full set. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [ ] 4. One issue, one branch off an up-to-date `main`, one pull request. (Stacked on #35945 by the dispatch claim; see Acceptance notes.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7)_ <!-- signed: repo:objectstack#7 · os-tesla · session_01L9qibwJEh7hMPPvagWM1g7 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9ed18a5 commit e72f2aa

9 files changed

Lines changed: 252 additions & 14 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/objectql': patch
4+
'@objectstack/service-analytics': patch
5+
---
6+
7+
feat: the analytics plugin asks the engine which share-grant scopes its native SQL path may compile (ADR-0155 D4)
8+
9+
Clause-②: yes
10+
Metadata-protocol: none
11+
12+
- **New optional contract member** (`@objectstack/spec`). `IObjectQLEngine.fixedReadLeafClassOf(leaf)` answers which of ADR-0155 D4's two classes a `SharedRecordIds` leaf falls in on an engine: `'other-datasource'` (the leaf's object is bound to another datasource than `sys_record_share`) or `'registration-by-name'` (a middleware or a `beforeFind` / `afterFind` hook is registered for `sys_record_share` by name), with what names it. It answers `null` when neither class applies, and throws `TypeError` on a value that is not a fixed-read leaf. The answer type is the new `EngineFixedReadLeafClass`. The member is optional, and because "neither" is `null`, `engine.fixedReadLeafClassOf?.(leaf)` is a caller's whole answer: a class, `null`, or `undefined` from an engine without the member, which cannot say.
13+
- **The engine implements it** (`@objectstack/objectql`). `ObjectQL.fixedReadLeafClassOf` returns the seam's own recognition, `fixedReadLeafClassOfEngine(engine, leaf)`, with "neither" spelled `null`. It reads only datasource bindings, middlewares and hooks. It calls no driver and logs nothing.
14+
- **The analytics plugin wires it** (`@objectstack/service-analytics`). `AnalyticsServicePlugin` now fills `AnalyticsServiceConfig.fixedReadLeafClassOf` from the `"data"` engine on each call. When the engine answers `null` (neither class), the native SQL path compiles a read scope that carries the leaf. When the engine names a class, throws, answers anything but `null`, or has no such member, the query goes to the ObjectQL engine path, as before. An engine without the member is reported once at `warn`. Neither class is restated in analytics.
15+
16+
Nothing a metadata author writes changes. On a host that runs `ObjectQLPlugin`'s engine as `"data"`, a sharing-scoped analytics query outside both classes keeps the native SQL path once the producer starts writing the leaf (ADR-0155 step 6).

‎packages/objectql/src/engine.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import { AsyncLocalStorage } from 'node:async_hooks';
4-
import { QueryAST, QueryInput, HookContext, ServiceObject } from '@objectstack/spec/data';
4+
import { QueryAST, QueryInput, HookContext, ServiceObject, type FixedReadLeaf } from '@objectstack/spec/data';
55
// [commit 74155c735] The defaulting node schema `fillQueryAstDefaults` runs author input
66
// through — the declared `.default()` stays in `packages/spec`, the engine
77
// only invokes it.
@@ -52,6 +52,7 @@ import { negotiatedMessageLocale, objectDisplayLabel, validationMessageContext }
5252
// below hand each body the members it reads (`DatasourceRoutingHost`).
5353
import { getDriver, matchPattern, resolveDatasourceFromMapping } from './engine-datasource-routing.js';
5454
import { relationSemiJoinServes } from './relation-semi-join.js';
55+
import { fixedReadLeafClassAnswerOf } from './fixed-read-leaf-engine-answer.js';
5556
// [#25522 cut 3] The lifecycle health bodies; the methods of the same names
5657
// below hand each body the members it reads (`LifecycleHealthHost`).
5758
import { checkDriversHealth, resolvePrimaryDatasource } from './engine-lifecycle-health.js';
@@ -127,11 +128,10 @@ import { ExecutionContext, type InstalledPackageSource } from '@objectstack/spec
127128
// contract is new (#5945).
128129
import type { IPubSub, IScopedContext, IScopedObjectRepository, IntrospectedSchema as SpecIntrospectedSchema } from '@objectstack/spec/contracts';
129130
// [#20157] The judge-only filter-admission member's verdict and options.
130-
import type { EngineFilterJudgement, EngineFilterJudgementOptions, InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts';
131+
import type { EngineFilterJudgement, EngineFilterJudgementOptions, EngineFixedReadLeafClass, IObjectQLEngine, InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts';
131132
import {
132133
IDataDriver,
133134
IDataEngine,
134-
type IObjectQLEngine,
135135
type EngineTransactionInfo,
136136
type EngineTransactionOptions,
137137
Logger,
@@ -1916,6 +1916,9 @@ export class ObjectQL implements IObjectQLEngine {
19161916
return MiddlewareAndContextFacet.hasObjectMiddleware.call(middlewareAndContextHost.of(this), objectName);
19171917
}
19181918

1919+
/** [ADR-0155 D4] `IObjectQLEngine.fixedReadLeafClassOf`: the seam's own recognition of D4's two classes for `leaf`, `null` for neither. */
1920+
fixedReadLeafClassOf(leaf: FixedReadLeaf): EngineFixedReadLeafClass | null { return fixedReadLeafClassAnswerOf(this, leaf); }
1921+
19191922
private executeWithMiddleware(ctx: OperationContext, executor: () => Promise<any>): Promise<any> {
19201923
// [#29986 codemod] The body moved to `engine-middleware-and-context.ts`, its docblock with it (see `MiddlewareAndContextHost`).
19211924
return MiddlewareAndContextFacet.executeWithMiddleware.call(middlewareAndContextHost.of(this), ctx, executor);
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0155 D4, plan step 5] The answer `IObjectQLEngine.fixedReadLeafClassOf`
5+
* gives, which `ObjectQL` forwards to in one line (its facade allows nothing
6+
* else): the seam's own recognition, {@link fixedReadLeafClassOfEngine}, with
7+
* its "neither class" spelled `null` instead of `undefined`.
8+
*
9+
* Why the respelling: the member is optional, so a caller asking through
10+
* `engine.fixedReadLeafClassOf?.(leaf)` already gets `undefined` from an engine
11+
* without it, and must decline there (it cannot say). Were "neither" also
12+
* `undefined`, that caller could not tell an engine that answered from one
13+
* that could not, and a caller that read `undefined` as "neither" would compile
14+
* what it cannot see. With "neither" as `null`, the optional call is the
15+
* caller's whole three-state answer and its fail-closed reading needs no probe.
16+
*
17+
* Read-only, like the seam: it throws `TypeError` on a value that is not a
18+
* fixed-read leaf, and otherwise calls no driver and logs nothing.
19+
*/
20+
21+
import type { FixedReadLeaf } from '@objectstack/spec/data';
22+
import { fixedReadLeafClassOfEngine, type FixedReadLeafClass } from './fixed-read-leaf-seam.js';
23+
import type { ObjectQL } from './engine.js';
24+
25+
/** Which of D4's two classes `leaf` falls in on `engine`, or `null` when neither. */
26+
export function fixedReadLeafClassAnswerOf(engine: ObjectQL, leaf: FixedReadLeaf): FixedReadLeafClass | null {
27+
return fixedReadLeafClassOfEngine(engine, leaf) ?? null;
28+
}

‎packages/services/service-analytics/src/__tests__/fixed-read-leaf-native-compile.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import type { Cube, FilterCondition } from '@objectstack/spec/data';
3232
import type { AnalyticsQuery } from '@objectstack/spec/contracts';
3333

3434
import { AnalyticsService } from '../analytics-service.js';
35+
import { AnalyticsServicePlugin } from '../plugin.js';
3536
import {
3637
READ_SCOPE_FIXED_READ_LEAF_BRANDS,
3738
assertReadScopeComparandsRunnable,
@@ -297,4 +298,101 @@ describe('[ADR-0155 Q2] the share-grant leaf on the analytics faces, live on SQL
297298
expect(params).toEqual(expect.arrayContaining(['srid_doc', 'user', 'u1']));
298299
});
299300
});
301+
302+
// [#35946, ruling 7051956587] `AnalyticsServicePlugin` wires the hook from
303+
// the "data" engine's `IObjectQLEngine.fixedReadLeafClassOf`, read
304+
// structurally: the engine here is a plain object over the live engine's
305+
// members, so the pin is the plugin's wiring, not the `ObjectQL` class. The
306+
// member's three answers: a class, `null` for neither (compile), and
307+
// `undefined` from an engine without it (decline).
308+
describe('[#35946] AnalyticsServicePlugin asks the data engine\'s fixedReadLeafClassOf', () => {
309+
const CUBE = {
310+
name: 'docs', sql: 'srid_doc', public: true,
311+
measures: { n: { sql: '*', type: 'count', title: 'n' } },
312+
dimensions: { id: { label: 'id', type: 'string', sql: 'id' } },
313+
} as unknown as Cube;
314+
const QUERY = { cube: 'docs', dimensions: ['id'], measures: ['n'] } as AnalyticsQuery;
315+
const READ_SCOPE = S.cases.find((c) => c.name.startsWith("the read scope's shape"))!;
316+
317+
/**
318+
* The "data" engine as a plain object; `member` says what its
319+
* `fixedReadLeafClassOf` is: the live engine's, none, or one that breaks
320+
* the contract by answering `undefined` for neither.
321+
*/
322+
const plainEngine = (member: 'present' | 'absent' | 'answers-undefined'): Record<string, unknown> => ({
323+
aggregate: (o: string, q: any) => engine.aggregate(o, q),
324+
getObject: (n: string) => engine.getObject(n),
325+
judgeFilter: (o: string, w: any, j: any) => engine.judgeFilter(o, w, j),
326+
hasObjectMiddleware: (o: string) => engine.hasObjectMiddleware(o),
327+
getDriverForObject: (o: string) => engine.getDriverForObject(o),
328+
...(member === 'present' ? { fixedReadLeafClassOf: (leaf: any) => engine.fixedReadLeafClassOf(leaf) } : {}),
329+
...(member === 'answers-undefined' ? { fixedReadLeafClassOf: () => undefined } : {}),
330+
});
331+
332+
async function viaPlugin(data: Record<string, unknown>) {
333+
const registered: Record<string, unknown> = {};
334+
const warn = vi.fn();
335+
const rawSql = vi.fn(runRawSql);
336+
const ctx = {
337+
getService: (name: string) => (name === 'data' ? data : registered[name]),
338+
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
339+
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
340+
logger: { ...quiet, warn },
341+
};
342+
await new AnalyticsServicePlugin({
343+
cubes: [CUBE],
344+
queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: true, inMemory: false }),
345+
executeRawSql: (_object, sql, params) => rawSql(sql, params),
346+
getReadScope: () => READ_SCOPE.where() as FilterCondition,
347+
}).init(ctx as never);
348+
const svc = registered.analytics as AnalyticsService;
349+
const answer = () => svc.query(QUERY, { userId: 'u1' } as never).then((r) => ({ rows: r.rows, err: null }), (err: any) => ({ rows: [], err }));
350+
return { answer, rawSql, warn };
351+
}
352+
const idsOf = (rows: Array<Record<string, unknown>>) => rows.map((r) => String(r.id)).sort();
353+
354+
const LEAF = () => SharedRecordIds.read('srid_doc', 'u1');
355+
356+
it('the member present, the object in neither class: it answers null, and the native path compiles the leaf', async () => {
357+
expect(engine.fixedReadLeafClassOf(LEAF())).toBeNull();
358+
const { answer, rawSql } = await viaPlugin(plainEngine('present'));
359+
const { rows, err } = await answer();
360+
expect(err).toBeNull();
361+
expect(rawSql).toHaveBeenCalledTimes(1);
362+
expect(rawSql.mock.calls[0]![0]).toContain('IN (SELECT "record_id" FROM "sys_record_share"');
363+
expect(idsOf(rows)).toEqual([...READ_SCOPE.expected]);
364+
});
365+
366+
it('the member answers a D4 class: the native path declines, and the engine\'s seam refuses', async () => {
367+
engine.registerHook('beforeFind', () => {}, { object: 'sys_record_share' });
368+
try {
369+
expect(engine.fixedReadLeafClassOf(LEAF())).toMatchObject({ class: 'registration-by-name', table: 'sys_record_share' });
370+
const { answer, rawSql } = await viaPlugin(plainEngine('present'));
371+
const { err } = await answer();
372+
expect(rawSql).not.toHaveBeenCalled();
373+
expect({ code: err?.code, status: err?.status }).toEqual(REFUSED);
374+
} finally {
375+
(engine as any).hooks.get('beforeFind').pop();
376+
}
377+
});
378+
379+
it('the member absent: the native path declines, the engine path answers, and the plugin says so once', async () => {
380+
const { answer, rawSql, warn } = await viaPlugin(plainEngine('absent'));
381+
const first = await answer();
382+
await answer();
383+
expect(first.err).toBeNull();
384+
expect(rawSql).not.toHaveBeenCalled();
385+
expect(idsOf(first.rows)).toEqual([...READ_SCOPE.expected]);
386+
expect(warn.mock.calls.filter((c) => String(c[0]).includes('fixedReadLeafClassOf'))).toHaveLength(1);
387+
});
388+
389+
it('a member that answers undefined (not the contract\'s null): the native path declines, the engine path answers', async () => {
390+
const { answer, rawSql, warn } = await viaPlugin(plainEngine('answers-undefined'));
391+
const { rows, err } = await answer();
392+
expect(err).toBeNull();
393+
expect(rawSql).not.toHaveBeenCalled();
394+
expect(idsOf(rows)).toEqual([...READ_SCOPE.expected]);
395+
expect(warn.mock.calls.filter((c) => String(c[0]).includes('fixedReadLeafClassOf'))).toHaveLength(0);
396+
});
397+
});
300398
});

‎packages/services/service-analytics/src/plugin.ts‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,9 @@ import { asAcceptedSqlDialect, type AcceptedSqlDialect } from './text-match-sql.
5858
* `IObjectQLEngine`, so the `Partial<>` around it is not decoration — it is
5959
* what keeps this seam usable against an engine that is not ObjectQL.
6060
* `judgeFilter` (#20157) is optional on the contract itself, by ruling, and
61-
* the auto-bridge probes it the same way. So is `hasObjectMiddleware`
62-
* (#21080), whose absence the bridge below reads as "cannot say".
61+
* the auto-bridge probes it the same way. So are `hasObjectMiddleware`
62+
* (#21080) and `fixedReadLeafClassOf` (ADR-0155 D4, #35946), whose absence
63+
* the bridges below read as "cannot say".
6364
*/
6465
/** One bridged `executeAggregate` call's input (the plugin option's own declaration). */
6566
type BridgedAggregateInput = Parameters<NonNullable<AnalyticsServicePluginOptions['executeAggregate']>>[1];
@@ -82,7 +83,7 @@ const AGGREGATE_ORDER_CUT: unique symbol = Symbol.for('objectstack.objectql.aggr
8283
type DataEngineLike =
8384
Pick<IDataEngine, 'aggregate'>
8485
& Partial<Pick<IDataEngine, 'execute' | 'resolveEffectiveDatasource' | 'getDriverForObject'>>
85-
& Partial<Pick<IObjectQLEngine, 'getObject' | 'judgeFilter' | 'hasObjectMiddleware'>>;
86+
& Partial<Pick<IObjectQLEngine, 'getObject' | 'judgeFilter' | 'hasObjectMiddleware' | 'fixedReadLeafClassOf'>>;
8687

8788
/**
8889
* The slice of the `IDataDriver` CONTRACT the analytics layer consumes —
@@ -1531,6 +1532,44 @@ export class AnalyticsServicePlugin implements Plugin {
15311532
return undefined;
15321533
};
15331534

1535+
/**
1536+
* [ADR-0155 D4, plan step 5, #35946] The engine seam's recognition of D4's
1537+
* two classes for a fixed-read leaf a read scope carries
1538+
* (`IObjectQLEngine.fixedReadLeafClassOf`), resolved per call like
1539+
* `hasObjectMiddleware` above, and handed on as the engine gave it: a
1540+
* class, or `null` for neither, the one answer on which `NativeSQLStrategy`
1541+
* compiles the leaf.
1542+
*
1543+
* It FAILS CLOSED: no engine, a `getService` throw, or an engine without
1544+
* the member answers `undefined` ("cannot say"). The strategy declines
1545+
* every answer but `null` to the engine path, so that tier declines, as a
1546+
* class and a throw do, and so does a member that does not keep the
1547+
* contract (one answering `undefined` for neither, say). ⛔ No copy of either class here (D4: "restates none"). An engine
1548+
* without the member is said once, at `warn`: the rows stay correct, only
1549+
* the native path for a scope carrying the leaf is gone.
1550+
*/
1551+
let reportedEngineWithoutLeafClassAnswer = false;
1552+
const fixedReadLeafClassOf: NonNullable<AnalyticsServiceConfig['fixedReadLeafClassOf']> = (leaf) => {
1553+
let svc: DataEngineLike | undefined;
1554+
try {
1555+
svc = ctx.getService<DataEngineLike>('data');
1556+
} catch {
1557+
return undefined;
1558+
}
1559+
if (!svc) return undefined;
1560+
if (typeof svc.fixedReadLeafClassOf !== 'function' && !reportedEngineWithoutLeafClassAnswer) {
1561+
reportedEngineWithoutLeafClassAnswer = true;
1562+
ctx.logger.warn(
1563+
'[Analytics] The "data" engine has no fixedReadLeafClassOf (IObjectQLEngine.fixedReadLeafClassOf), so ' +
1564+
'NativeSQLStrategy cannot ask the engine whether it may compile a SharedRecordIds leaf in a read scope. It ' +
1565+
'declines every query whose read scope carries one, and the ObjectQL strategy serves it through the engine; ' +
1566+
'a query that strategy cannot serve is refused. Register ObjectQLPlugin\'s engine as "data" to keep the ' +
1567+
'native path for those scopes. Reported once.',
1568+
);
1569+
}
1570+
return svc.fixedReadLeafClassOf?.(leaf);
1571+
};
1572+
15341573
const config: AnalyticsServiceConfig = {
15351574
cubes: this.options.cubes,
15361575
logger: ctx.logger,
@@ -1657,6 +1696,9 @@ export class AnalyticsServicePlugin implements Plugin {
16571696
// `hasObjectMiddleware` above. Wired whoever executes raw SQL: the
16581697
// middlewares live in the engine either way.
16591698
hasObjectMiddleware,
1699+
// [ADR-0155 D4, #35946] The engine seam's class recognition for a
1700+
// fixed-read leaf — see `fixedReadLeafClassOf` above.
1701+
fixedReadLeafClassOf,
16601702
// ADR-0062 D6 — a federated object carries an `external` block (ADR-0015).
16611703
// Reported so NativeSQLStrategy declines it (its hand-compiled FROM would
16621704
// hit the wrong physical table) and the driver-correct ObjectQL path runs.

‎packages/spec/api-surface/contracts.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@
124124
"EngineDatasourceDef (interface)",
125125
"EngineFilterJudgement (type)",
126126
"EngineFilterJudgementOptions (interface)",
127+
"EngineFixedReadLeafClass (type)",
127128
"EngineSchemaRegistryView (interface)",
128129
"EngineTransactionInfo (interface)",
129130
"EngineTransactionOptions (interface)",

‎packages/spec/export-origins/contracts.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@
124124
"EngineDatasourceDef": "src/contracts/data-engine.ts#EngineDatasourceDef (interface)",
125125
"EngineFilterJudgement": "src/contracts/objectql-engine.ts#EngineFilterJudgement (type)",
126126
"EngineFilterJudgementOptions": "src/contracts/objectql-engine.ts#EngineFilterJudgementOptions (interface)",
127+
"EngineFixedReadLeafClass": "src/contracts/objectql-engine.ts#EngineFixedReadLeafClass (type)",
127128
"EngineSchemaRegistryView": "src/contracts/objectql-engine.ts#EngineSchemaRegistryView (interface)",
128129
"EngineTransactionInfo": "src/contracts/objectql-engine.ts#EngineTransactionInfo (interface)",
129130
"EngineTransactionOptions": "src/contracts/objectql-engine.ts#EngineTransactionOptions (interface)",

0 commit comments

Comments
 (0)