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
16 changes: 16 additions & 0 deletions .changeset/35946-fixed-read-leaf-engine-member.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/spec': patch
'@objectstack/objectql': patch
'@objectstack/service-analytics': patch
---

feat: the analytics plugin asks the engine which share-grant scopes its native SQL path may compile (ADR-0155 D4)

Clause-②: yes
Metadata-protocol: none

- **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.
- **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.
- **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.

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).
9 changes: 6 additions & 3 deletions packages/objectql/src/engine.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

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

/** [ADR-0155 D4] `IObjectQLEngine.fixedReadLeafClassOf`: the seam's own recognition of D4's two classes for `leaf`, `null` for neither. */
fixedReadLeafClassOf(leaf: FixedReadLeaf): EngineFixedReadLeafClass | null { return fixedReadLeafClassAnswerOf(this, leaf); }

private executeWithMiddleware(ctx: OperationContext, executor: () => Promise<any>): Promise<any> {
// [#29986 codemod] The body moved to `engine-middleware-and-context.ts`, its docblock with it (see `MiddlewareAndContextHost`).
return MiddlewareAndContextFacet.executeWithMiddleware.call(middlewareAndContextHost.of(this), ctx, executor);
Expand Down
28 changes: 28 additions & 0 deletions packages/objectql/src/fixed-read-leaf-engine-answer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [ADR-0155 D4, plan step 5] The answer `IObjectQLEngine.fixedReadLeafClassOf`
* gives, which `ObjectQL` forwards to in one line (its facade allows nothing
* else): the seam's own recognition, {@link fixedReadLeafClassOfEngine}, with
* its "neither class" spelled `null` instead of `undefined`.
*
* Why the respelling: the member is optional, so a caller asking through
* `engine.fixedReadLeafClassOf?.(leaf)` already gets `undefined` from an engine
* without it, and must decline there (it cannot say). Were "neither" also
* `undefined`, that caller could not tell an engine that answered from one
* that could not, and a caller that read `undefined` as "neither" would compile
* what it cannot see. With "neither" as `null`, the optional call is the
* caller's whole three-state answer and its fail-closed reading needs no probe.
*
* Read-only, like the seam: it throws `TypeError` on a value that is not a
* fixed-read leaf, and otherwise calls no driver and logs nothing.
*/

import type { FixedReadLeaf } from '@objectstack/spec/data';
import { fixedReadLeafClassOfEngine, type FixedReadLeafClass } from './fixed-read-leaf-seam.js';
import type { ObjectQL } from './engine.js';

/** Which of D4's two classes `leaf` falls in on `engine`, or `null` when neither. */
export function fixedReadLeafClassAnswerOf(engine: ObjectQL, leaf: FixedReadLeaf): FixedReadLeafClass | null {
return fixedReadLeafClassOfEngine(engine, leaf) ?? null;
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import type { Cube, FilterCondition } from '@objectstack/spec/data';
import type { AnalyticsQuery } from '@objectstack/spec/contracts';

import { AnalyticsService } from '../analytics-service.js';
import { AnalyticsServicePlugin } from '../plugin.js';
import {
READ_SCOPE_FIXED_READ_LEAF_BRANDS,
assertReadScopeComparandsRunnable,
Expand Down Expand Up @@ -297,4 +298,101 @@ describe('[ADR-0155 Q2] the share-grant leaf on the analytics faces, live on SQL
expect(params).toEqual(expect.arrayContaining(['srid_doc', 'user', 'u1']));
});
});

// [#35946, ruling 7051956587] `AnalyticsServicePlugin` wires the hook from
// the "data" engine's `IObjectQLEngine.fixedReadLeafClassOf`, read
// structurally: the engine here is a plain object over the live engine's
// members, so the pin is the plugin's wiring, not the `ObjectQL` class. The
// member's three answers: a class, `null` for neither (compile), and
// `undefined` from an engine without it (decline).
describe('[#35946] AnalyticsServicePlugin asks the data engine\'s fixedReadLeafClassOf', () => {
const CUBE = {
name: 'docs', sql: 'srid_doc', public: true,
measures: { n: { sql: '*', type: 'count', title: 'n' } },
dimensions: { id: { label: 'id', type: 'string', sql: 'id' } },
} as unknown as Cube;
const QUERY = { cube: 'docs', dimensions: ['id'], measures: ['n'] } as AnalyticsQuery;
const READ_SCOPE = S.cases.find((c) => c.name.startsWith("the read scope's shape"))!;

/**
* The "data" engine as a plain object; `member` says what its
* `fixedReadLeafClassOf` is: the live engine's, none, or one that breaks
* the contract by answering `undefined` for neither.
*/
const plainEngine = (member: 'present' | 'absent' | 'answers-undefined'): Record<string, unknown> => ({
aggregate: (o: string, q: any) => engine.aggregate(o, q),
getObject: (n: string) => engine.getObject(n),
judgeFilter: (o: string, w: any, j: any) => engine.judgeFilter(o, w, j),
hasObjectMiddleware: (o: string) => engine.hasObjectMiddleware(o),
getDriverForObject: (o: string) => engine.getDriverForObject(o),
...(member === 'present' ? { fixedReadLeafClassOf: (leaf: any) => engine.fixedReadLeafClassOf(leaf) } : {}),
...(member === 'answers-undefined' ? { fixedReadLeafClassOf: () => undefined } : {}),
});

async function viaPlugin(data: Record<string, unknown>) {
const registered: Record<string, unknown> = {};
const warn = vi.fn();
const rawSql = vi.fn(runRawSql);
const ctx = {
getService: (name: string) => (name === 'data' ? data : registered[name]),
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
logger: { ...quiet, warn },
};
await new AnalyticsServicePlugin({
cubes: [CUBE],
queryCapabilities: () => ({ nativeSql: true, objectqlAggregate: true, inMemory: false }),
executeRawSql: (_object, sql, params) => rawSql(sql, params),
getReadScope: () => READ_SCOPE.where() as FilterCondition,
}).init(ctx as never);
const svc = registered.analytics as AnalyticsService;
const answer = () => svc.query(QUERY, { userId: 'u1' } as never).then((r) => ({ rows: r.rows, err: null }), (err: any) => ({ rows: [], err }));
return { answer, rawSql, warn };
}
const idsOf = (rows: Array<Record<string, unknown>>) => rows.map((r) => String(r.id)).sort();

const LEAF = () => SharedRecordIds.read('srid_doc', 'u1');

it('the member present, the object in neither class: it answers null, and the native path compiles the leaf', async () => {
expect(engine.fixedReadLeafClassOf(LEAF())).toBeNull();
const { answer, rawSql } = await viaPlugin(plainEngine('present'));
const { rows, err } = await answer();
expect(err).toBeNull();
expect(rawSql).toHaveBeenCalledTimes(1);
expect(rawSql.mock.calls[0]![0]).toContain('IN (SELECT "record_id" FROM "sys_record_share"');
expect(idsOf(rows)).toEqual([...READ_SCOPE.expected]);
});

it('the member answers a D4 class: the native path declines, and the engine\'s seam refuses', async () => {
engine.registerHook('beforeFind', () => {}, { object: 'sys_record_share' });
try {
expect(engine.fixedReadLeafClassOf(LEAF())).toMatchObject({ class: 'registration-by-name', table: 'sys_record_share' });
const { answer, rawSql } = await viaPlugin(plainEngine('present'));
const { err } = await answer();
expect(rawSql).not.toHaveBeenCalled();
expect({ code: err?.code, status: err?.status }).toEqual(REFUSED);
} finally {
(engine as any).hooks.get('beforeFind').pop();
}
});

it('the member absent: the native path declines, the engine path answers, and the plugin says so once', async () => {
const { answer, rawSql, warn } = await viaPlugin(plainEngine('absent'));
const first = await answer();
await answer();
expect(first.err).toBeNull();
expect(rawSql).not.toHaveBeenCalled();
expect(idsOf(first.rows)).toEqual([...READ_SCOPE.expected]);
expect(warn.mock.calls.filter((c) => String(c[0]).includes('fixedReadLeafClassOf'))).toHaveLength(1);
});

it('a member that answers undefined (not the contract\'s null): the native path declines, the engine path answers', async () => {
const { answer, rawSql, warn } = await viaPlugin(plainEngine('answers-undefined'));
const { rows, err } = await answer();
expect(err).toBeNull();
expect(rawSql).not.toHaveBeenCalled();
expect(idsOf(rows)).toEqual([...READ_SCOPE.expected]);
expect(warn.mock.calls.filter((c) => String(c[0]).includes('fixedReadLeafClassOf'))).toHaveLength(0);
});
});
});
48 changes: 45 additions & 3 deletions packages/services/service-analytics/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ import { asAcceptedSqlDialect, type AcceptedSqlDialect } from './text-match-sql.
* `IObjectQLEngine`, so the `Partial<>` around it is not decoration — it is
* what keeps this seam usable against an engine that is not ObjectQL.
* `judgeFilter` (#20157) is optional on the contract itself, by ruling, and
* the auto-bridge probes it the same way. So is `hasObjectMiddleware`
* (#21080), whose absence the bridge below reads as "cannot say".
* the auto-bridge probes it the same way. So are `hasObjectMiddleware`
* (#21080) and `fixedReadLeafClassOf` (ADR-0155 D4, #35946), whose absence
* the bridges below read as "cannot say".
*/
/** One bridged `executeAggregate` call's input (the plugin option's own declaration). */
type BridgedAggregateInput = Parameters<NonNullable<AnalyticsServicePluginOptions['executeAggregate']>>[1];
Expand All @@ -82,7 +83,7 @@ const AGGREGATE_ORDER_CUT: unique symbol = Symbol.for('objectstack.objectql.aggr
type DataEngineLike =
Pick<IDataEngine, 'aggregate'>
& Partial<Pick<IDataEngine, 'execute' | 'resolveEffectiveDatasource' | 'getDriverForObject'>>
& Partial<Pick<IObjectQLEngine, 'getObject' | 'judgeFilter' | 'hasObjectMiddleware'>>;
& Partial<Pick<IObjectQLEngine, 'getObject' | 'judgeFilter' | 'hasObjectMiddleware' | 'fixedReadLeafClassOf'>>;

/**
* The slice of the `IDataDriver` CONTRACT the analytics layer consumes —
Expand Down Expand Up @@ -1531,6 +1532,44 @@ export class AnalyticsServicePlugin implements Plugin {
return undefined;
};

/**
* [ADR-0155 D4, plan step 5, #35946] The engine seam's recognition of D4's
* two classes for a fixed-read leaf a read scope carries
* (`IObjectQLEngine.fixedReadLeafClassOf`), resolved per call like
* `hasObjectMiddleware` above, and handed on as the engine gave it: a
* class, or `null` for neither, the one answer on which `NativeSQLStrategy`
* compiles the leaf.
*
* It FAILS CLOSED: no engine, a `getService` throw, or an engine without
* the member answers `undefined` ("cannot say"). The strategy declines
* every answer but `null` to the engine path, so that tier declines, as a
* class and a throw do, and so does a member that does not keep the
* contract (one answering `undefined` for neither, say). ⛔ No copy of either class here (D4: "restates none"). An engine
* without the member is said once, at `warn`: the rows stay correct, only
* the native path for a scope carrying the leaf is gone.
*/
let reportedEngineWithoutLeafClassAnswer = false;
const fixedReadLeafClassOf: NonNullable<AnalyticsServiceConfig['fixedReadLeafClassOf']> = (leaf) => {
let svc: DataEngineLike | undefined;
try {
svc = ctx.getService<DataEngineLike>('data');
} catch {
return undefined;
}
if (!svc) return undefined;
if (typeof svc.fixedReadLeafClassOf !== 'function' && !reportedEngineWithoutLeafClassAnswer) {
reportedEngineWithoutLeafClassAnswer = true;
ctx.logger.warn(
'[Analytics] The "data" engine has no fixedReadLeafClassOf (IObjectQLEngine.fixedReadLeafClassOf), so ' +
'NativeSQLStrategy cannot ask the engine whether it may compile a SharedRecordIds leaf in a read scope. It ' +
'declines every query whose read scope carries one, and the ObjectQL strategy serves it through the engine; ' +
'a query that strategy cannot serve is refused. Register ObjectQLPlugin\'s engine as "data" to keep the ' +
'native path for those scopes. Reported once.',
);
}
return svc.fixedReadLeafClassOf?.(leaf);
};

const config: AnalyticsServiceConfig = {
cubes: this.options.cubes,
logger: ctx.logger,
Expand Down Expand Up @@ -1657,6 +1696,9 @@ export class AnalyticsServicePlugin implements Plugin {
// `hasObjectMiddleware` above. Wired whoever executes raw SQL: the
// middlewares live in the engine either way.
hasObjectMiddleware,
// [ADR-0155 D4, #35946] The engine seam's class recognition for a
// fixed-read leaf — see `fixedReadLeafClassOf` above.
fixedReadLeafClassOf,
// ADR-0062 D6 — a federated object carries an `external` block (ADR-0015).
// Reported so NativeSQLStrategy declines it (its hand-compiled FROM would
// hit the wrong physical table) and the driver-correct ObjectQL path runs.
Expand Down
1 change: 1 addition & 0 deletions packages/spec/api-surface/contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@
"EngineDatasourceDef (interface)",
"EngineFilterJudgement (type)",
"EngineFilterJudgementOptions (interface)",
"EngineFixedReadLeafClass (type)",
"EngineSchemaRegistryView (interface)",
"EngineTransactionInfo (interface)",
"EngineTransactionOptions (interface)",
Expand Down
1 change: 1 addition & 0 deletions packages/spec/export-origins/contracts.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@
"EngineDatasourceDef": "src/contracts/data-engine.ts#EngineDatasourceDef (interface)",
"EngineFilterJudgement": "src/contracts/objectql-engine.ts#EngineFilterJudgement (type)",
"EngineFilterJudgementOptions": "src/contracts/objectql-engine.ts#EngineFilterJudgementOptions (interface)",
"EngineFixedReadLeafClass": "src/contracts/objectql-engine.ts#EngineFixedReadLeafClass (type)",
"EngineSchemaRegistryView": "src/contracts/objectql-engine.ts#EngineSchemaRegistryView (interface)",
"EngineTransactionInfo": "src/contracts/objectql-engine.ts#EngineTransactionInfo (interface)",
"EngineTransactionOptions": "src/contracts/objectql-engine.ts#EngineTransactionOptions (interface)",
Expand Down
Loading
Loading