Skip to content

Commit 1bf5f6e

Browse files
fix(runtime,objectql): ctx.title() answers a title formula over lookups — the one hop is served on the body's own channel (#24307)
Part of #24197 (part 2 of 3: the hook-body title accessor. The ADR-0079 note follows as its own Tier H PR.) Clause-②: yes (widening) (re-declared by the seat in claim 6249052664: the `@objectstack/objectql` index gains `resolveServedRecordTitle`, `servedRecordTitle` and the type `FormulaServingChannel`, and the exported classes `ObjectQL` and `ScopedContext` each gain a public `serveFormulaField`; nothing is removed or renamed. The accessor's own answer is a declared capability honoured: it names the record by its declared title.) **Published export change, reported for the seat to re-declare the line above:** `@objectstack/objectql`'s `index.ts` gains `resolveServedRecordTitle`, `servedRecordTitle` and the type `FormulaServingChannel`. The exported classes `ObjectQL` and `ScopedContext` each gain one public method, `serveFormulaField`. Nothing is removed or renamed. The changeset grades objectql `minor` and runtime `patch`. ## What was wrong PR #24274 made the read path serve one hop, so `GET` of a junction object shows `record.book.title + ' · ' + record.reader.name`. A hook body's `ctx.title()` still answered `null` for it. Both forms of the accessor evaluated the title with the synchronous `evaluateFormulaField`, which preloads no hop. `ctx.title('field')` also discarded the related record's own one-hop title that its `findOne` had already served, because it re-derived the title synchronously. ## What changed - **`ObjectQL.serveFormulaField(objectName, record, field, context)`** (`engine.ts`) evaluates one declared formula field over a record in hand, the way a read evaluates it. It uses the same plan builder, the same hop loader (`resolveFormulaRelated` → `resolveOneHopRelated(…, 'caller')`, including the `formulaHopReads` one-hop guard), the same `can()` permission map and the same fault sink. No second loader or evaluator is added anywhere, and runtime has no copy of either. - **`ScopedContext.serveFormulaField(objectName, record, field)`** calls it with the context's own `ExecutionContext`. That is the body's `ctx.api` channel, so its identity, its permissions and (inside a transaction) its `transaction` handle all carry over. - **`record-title.ts`** adds `resolveServedRecordTitle(schema, record, channel)`, the async sibling of `resolveRecordTitle`. It also adds `servedRecordTitle(schema, row)`, which reads the title a read already served off the row. `resolveRecordTitle` is unchanged and still serves no hop. Its docblock now says so. - **`body-runner.ts` `buildTitleSurface`:** - `ctx.title()` resolves over `hookRecordState` (the in-flight state) on the channel the installer hands in per call (`txState.api ?? ctx.api`). - `ctx.title('field')` reads the title off the row its `findOne` served. - A channel without `serveFormulaField` falls back to the synchronous path, which still resolves a title over the record's own columns. That is the unscoped api of a `runAs: 'user'` hook with no user, which cannot read. **Which channel serves the hop, and why.** The body's own `ctx.api`, transaction-scoped when the body has one open. The hop is the engine's own loader (`this.find` on the target with the channel's context). It is not a repository read through the channel's `object(...)`, because a repository rebuilds the query object, which would lose the identity-keyed one-hop marker and let the related object's formulas take a second hop. ## Hypotheses, measured | | Hypothesis | Result | |---|---|---| | H1 | `ctx.title()` follows the in-flight key | **Confirmed.** `beforeInsert` names the payload's book. A `beforeUpdate` that moves `book` b1 to b2 names `Emma`, not `Dune`. `afterUpdate` names the after-state. | | H2 | The hop rides the body's channel | **Confirmed on real SQLite** (better-sqlite3, one pooled connection). In a `beforeUpdate` where the body opens `ctx.api.transaction` (the body owns it), both hop reads run on that transaction's handle. In an `afterUpdate`, the body JOINS the write's own unit of work (`inAfterAbortUnit`), and every read runs on that one handle. Ablation: when the hop is routed through the hook's base `api` instead, the owned-transaction pin hangs (`Acquire connection error: aborted`, test timeout at 30 s), which is the deadlock. | | H3 | Re-deriving the related title discards a served one-hop value | **Confirmed.** With the old re-derivation, `ctx.title('book')` for a book whose title is `record.title + ' @ ' + record.shelf.code` answers `null`. Reading the served value answers `Dune @ A-1`, which equals `findOne` for the same caller. | | H4 | A caller who may not read a related record gets the read's answer | **Confirmed.** Row-level security hides one reader. `ctx.title()` answers `null`, and `findOne` of the junction row as the same caller answers `title: null`. Neither returns the readable half or the hidden name. SYSTEM gets `Dune · Hidden Person` from both (control). | | H5 | No second hop | **Confirmed.** A copy titled `record.book.label`, where the book's `label` reads its shelf, answers `null` from both `ctx.title()` and the read. No `lib_shelf` read is issued. | **Cost (measured):** a title over lookups costs one batched read per reference field it reads through: exactly +2 reads (`lib_book`, `lib_reader`) against the same write with a body that does not ask, and the book read is `where id $in [b1]` with fields `[id, title]`. A title over the row's own columns still costs 0 reads; that pin is kept and renamed to say so. The related form costs one `findOne`, plus whatever hop that record's own title formula reads. ## Verification Head `0d133459d7` (after merging `origin/main`): - **Full build:** `pnpm build --concurrency=2`, 76/76 tasks, exit 0. - **Typecheck:** `pnpm --filter @objectstack/{objectql,runtime,cli} typecheck` exit 0 each. Each script includes `check:test-typecheck` over `tsconfig.test.json`, so the new tests are type-checked. - **Suites:** - `@objectstack/objectql` `pnpm test`: 439 files, 8280 tests passed. - `@objectstack/runtime` `pnpm test`: 418 files, 6574 passed and 19 skipped, run on the pre-merge head `650581b9`. - On the final head, rebuilt: `hook-ctx-title-one-hop.integration.test.ts` and `hook-ctx-title.integration.test.ts` 20/20, and `engine-formula-one-hop.test.ts` and `record-title.test.ts` 47/47. - **New pins:** - `packages/runtime/src/sandbox/hook-ctx-title-one-hop.integration.test.ts`: 11 tests (real engine, real SQLite, real QuickJS). - 8 tests in `engine-formula-one-hop.test.ts`, covering `serveFormulaField`: hop by the in-hand key, parity with `findOne`, zero reads for own columns, the transaction handle, the caller-permission null, no second hop, and the served row title. - **Gates:** `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` (no paths) derived 102 commands. All 102 ran, each exit captured before any pipe: 102 × exit 0. `--ran` output: "102 derived famil(ies) accounted for — 102 run, 0 NOT-MEASURED". - **Ablations:** made via `scripts/ablation-replace.mjs`. Each one landed (anchor 1 → 0, blob moved), and each restore was proven by blob == HEAD with `git diff HEAD` empty. - **A1:** served path → synchronous `resolveRecordTitle`. 8 of the 11 runtime pins go red. - **A2:** channel → the hook's base `api`. The owned-transaction H2 pin deadlocks and times out. - **A3:** related form re-derives. The H3 pin goes red (`null`). - **A4:** engine hop read as SYSTEM. Exactly the caller-permission pin goes red. - **A5:** `ScopedContext` drops `transaction`. Exactly the transaction pin goes red. - A4 and A5 ran on the objectql suite, which imports `./engine.js` from source, so no `dist` leg was needed. A1 to A3 mutate runtime source, which that suite imports directly. ## Settled choices (see the report's open questions) - **The related form prefers the served value.** It no longer re-derives. The old guard defended against a hypothetical embedder whose `findOne` does not compute formulas. Every in-repo channel (`ScopedContext`, `ql.object`, `ql.createContext`, the repo facade over `ql.find`) computes them. Re-deriving also computed a title that field-level security had deleted from the row. - **`ctx.title()` still needs no capability**, even when the title's hop reads. The hop reads are the declaration's, made on the body's own channel under the caller's permissions. Requiring `api.read` only when a title happens to traverse a lookup would make a body's grant depend on another object's metadata. ## Deviations from the claim's file surface These are comment-only or documentation-only edits outside the fence. The pin sweep forced each one, because each stated the old cost: - `content/docs/automation/hook-bodies.mdx`: three rows and one bullet pair said `ctx.title()` performs no read. - `packages/runtime/src/sandbox/quickjs-runner.ts` and `script-runner.ts`: comments and a docblock. - `packages/cli/src/utils/extract-hook-body.ts`: one comment. No behaviour changed in any of them. The two existing measurement pins in `hook-ctx-title.integration.test.ts` keep their assertions and are renamed to the own-column case. ## Acceptance notes - **REST parity is pinned against `engine.findOne` with the same context.** That is the read the REST data route serves. No HTTP server was booted. - **A hop's target in the stored-metadata family is not refused for a body's title.** The hop is the engine's read, so it does not pass through the body api's family-read refusal (`refuseStoredMetadataBodyReads`). It is still read under the caller's own permissions, and the REST read serves the same value. No in-repo object composes a title through a lookup to a family table. Noted here, not filed. - **The changelog text of #11293 (`packages/*/CHANGELOG.md`) still says "no read at all".** That text is release-owned, so it is left as is. This PR's changesets state the new cost. --- _Generated by [Claude Code](https://claude.ai/code/session_01XpmVCa3CH5g9uCZLy3j587)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 52ff308 commit 1bf5f6e

13 files changed

Lines changed: 670 additions & 52 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/objectql': minor
3+
---
4+
5+
feat(objectql): evaluate a formula field over a record in hand the way a read serves it, one hop through a reference included
6+
7+
A formula title over lookups (`record.book.title + ' · ' + record.reader.name`) is computed on every read since the formula read path reads one hop. A record no read returned, such as the state a hook fires on, had no way to get the same value: the synchronous `evaluateFormulaField` reads no hop, so it answered `null`.
8+
9+
- **`ScopedContext.serveFormulaField(objectName, record, field)`** evaluates one declared formula field over `record` with the read path's own evaluation, under that context: the one hop it reads through a reference (one batched read per reference field, through the reader's own permissions, on the context's transaction when it carries one), the `can()` permission map, and the fault report. A related record the reader may not read, a missing one and a second hop leave the field `null` with the read's reason, as a read does. `ObjectQL.serveFormulaField(objectName, record, field, context)` is the engine method behind it.
10+
- **`resolveServedRecordTitle(schema, record, channel)`** is the async sibling of `resolveRecordTitle`: this record's title, with a formula title served on `channel` (a `ScopedContext`). `resolveRecordTitle` is unchanged and still reads no hop.
11+
- **`servedRecordTitle(schema, row)`** reads the title a read already served off the row it returned, instead of re-deriving it.
12+
13+
What to do. Nothing. Code that names a record it holds in hand and wants the title a read shows calls `resolveServedRecordTitle` with the caller's `ScopedContext`.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
fix(runtime): `ctx.title()` in a hook body answers a title formula that reads through a lookup, as a read of the record shows it
6+
7+
A junction object's composed title, `record.book.title + ' · ' + record.reader.name`, is shown by every read of the record, but a hook body's `ctx.title()` answered `null` for it, and `ctx.title('<lookup field>')` answered `null` for a related record whose own title reads through a lookup.
8+
9+
- **`ctx.title()`** now reads the one hop the title formula reads, through the body's own `ctx.api` channel: one read per lookup the title reads through, with the caller's permissions, on the transaction the body has open. It follows the lookup's value in this write, so a `beforeInsert` names the payload's book and a `beforeUpdate` that changes `book` names the new book. A title over the record's own columns still costs no read.
10+
- **`ctx.title('<lookup field>')`** returns the title its `findOne` served, the related record's own one-hop title included, instead of re-computing it without the hop.
11+
- A related record the caller may not read leaves the title `null`, as the read of the same record shows no title to that caller. It is never a partial title and never the hidden name. A title that would need a second hop is `null`, as it is on a read.
12+
13+
What to do. Nothing. A hook that composed a junction object's title by hand can call `ctx.title()` instead.

‎content/docs/automation/hook-bodies.mdx‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ The script sees only what the surrounding `ctx` object exposes:
100100
| `ctx.user` / `ctx.session` | Identity context. | none |
101101
| `ctx.api.object(name).find\|count\|aggregate` | Cross-object reads, scoped to current tenant. | `api.read` |
102102
| `ctx.api.object(name).insert\|update\|delete` | Cross-object writes. | `api.write` |
103-
| `ctx.title()` | This record's title — the object's `nameField`, **including when it is a `formula`** (evaluated server-side against the record already in hand, no extra read). | none |
104-
| `ctx.title('<lookup field>')` | The related record's title, through a lookup / master_detail / user / tree column. Costs one `findOne`. | `api.read` |
103+
| `ctx.title()` | This record's title — the object's `nameField`, **including when it is a `formula`** (evaluated server-side against the record already in hand: no extra read over the record's own columns, one read per lookup a title such as `record.book.title + ' · ' + record.reader.name` reads through). | none |
104+
| `ctx.title('<lookup field>')` | The related record's title, through a lookup / master_detail / user / tree column. Costs one `findOne` (plus the lookups that record's own title reads through). | `api.read` |
105105
| `ctx.crypto.randomUUID()` | UUID generation. | `crypto.uuid` |
106106
| `ctx.log.{info,warn,error}` | Structured logging. | `log` |
107107
| `ctx.connector(name).<method>(...)` _(planned)_ | Outbound HTTP / SaaS calls. **Not yet wired into the sandbox** — ships with the separate Connector spec. | (separate Connector spec) |
@@ -127,14 +127,21 @@ const account = await ctx.title('account_id');
127127

128128
Three properties worth knowing:
129129

130-
- **A formula `nameField` costs nothing extra.** It is evaluated server-side
131-
against the record the hook is already firing on — the same expression, the
132-
same evaluator and the same rounding a `GET` of that record would use, so the
133-
title a hook writes and the title the UI shows cannot drift.
134-
- **The related form costs exactly one `findOne`**, through your body's own read
130+
- **A formula `nameField` is evaluated the way a `GET` evaluates it.** Against
131+
the record the hook is already firing on — the same expression, the same
132+
evaluator and the same rounding a `GET` of that record would use, so the title
133+
a hook writes and the title the UI shows cannot drift. A title over the
134+
record's own columns costs nothing extra. A title that reads one hop through a
135+
lookup (`record.book.title + ' · ' + record.reader.name`) costs one read per
136+
lookup it reads through, follows the lookup's value in this write (a
137+
`beforeUpdate` that changes `book` names the new book), and is read through
138+
your body's own read channel: a related record you may not read leaves the
139+
title `null`, exactly as the `GET` shows no title.
140+
- **The related form costs one `findOne`**, through your body's own read
135141
channel — so it obeys the caller's scope and joins an open
136142
`ctx.api.transaction`. That is why it requires `api.read` while the bare form
137-
requires nothing: the token gates the read, and there is no read to gate.
143+
requires nothing: the token gates your body's reach for another record; the
144+
bare form names this record by its own declaration.
138145
- **It never falls back to the id.** No title resolvable ⇒ `null`. An id-shaped
139146
string is a plausible-looking title to whatever renders it, so the platform
140147
will not manufacture one; write your own fallback if you want one.
@@ -410,7 +417,7 @@ The extractor scans each body for known patterns and adds the matching capabilit
410417
| `*.object(…).insert / update / upsert / delete / patch / remove / create` | `api.write` |
411418
| `ctx.crypto.randomUUID` | `crypto.uuid` |
412419
| `ctx.log.info / warn / error / debug` | `log` |
413-
| `*.title(<argument>)` — the related-record form only; bare `ctx.title()` performs no read | `api.read` |
420+
| `*.title(<argument>)` — the related-record form only; bare `ctx.title()` names this record and needs no token | `api.read` |
414421

415422
The matcher is deliberately over-inclusive — it names spellings the VM does not install (`patch`, `remove`, `get`, `list`, `create`) because an over-inferred token costs nothing the sandbox ever checks, while an under-inferred one surfaces as a sandbox refusal far from its cause. `create` is listed only for that reason: a body spelling it is refused at lowering (see [What the sandbox forbids](#what-the-sandbox-forbids)) and never reaches inference at all.
416423

‎packages/cli/src/utils/extract-hook-body.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -529,7 +529,8 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
529529
{ rx: /ctx\.log\.(?:info|warn|error|debug)\b/, cap: 'log' },
530530
// [#11293] `ctx.title(field)` — the RELATED-record form, and only that form.
531531
// `ctx.title()` resolves this record's title (formula included) from the
532-
// state the hook is already firing on and performs no read at all, so it
532+
// state the hook is already firing on — no read over its own columns, and
533+
// only its declaration's one hop through a reference otherwise — so it
533534
// needs no capability and inferring one for it would tax the majority case
534535
// with a grant it never exercises. The argument form costs exactly one
535536
// `findOne` through the body's own read channel, which is the same read

‎packages/objectql/src/engine-formula-one-hop.test.ts‎

Lines changed: 84 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
*/
2828
import { beforeEach, describe, expect, it } from 'vitest';
2929
import { ObjectQL } from './engine.js';
30+
import { resolveRecordTitle, resolveServedRecordTitle, servedRecordTitle } from './record-title.js';
3031

3132
type Rec = Record<string, unknown>;
3233

@@ -66,13 +67,13 @@ function makeDriver() {
6667
for (const f of fields) if (r[f] !== undefined) out[f] = r[f];
6768
return out;
6869
};
69-
const calls: Array<{ object: string; ast: any }> = [];
70+
const calls: Array<{ object: string; ast: any; options?: any }> = [];
7071
let n = 0;
7172
const driver: any = {
7273
name: 'memory', version: '0.0.0', supports: {},
7374
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
74-
async find(object: string, ast: any) {
75-
calls.push({ object, ast });
75+
async find(object: string, ast: any, options?: any) {
76+
calls.push({ object, ast, options });
7677
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
7778
// Hold the caller's page: `offset` then `limit`, as a real driver does.
7879
const offset = typeof ast?.offset === 'number' ? ast.offset : 0;
@@ -339,4 +340,84 @@ describe('#24197 — a formula field reads one hop through a reference', () => {
339340
engine.find('lib_loan', { orderBy: [{ field: 'title', order: 'asc' }], context: READER }),
340341
).rejects.toMatchObject({ code: 'INVALID_SORT', status: 400, field: 'title' });
341342
});
343+
344+
// [#24197] The record a hook fires on was never read back, so nothing served
345+
// its title: `serveFormulaField` is the read path's evaluation over a record
346+
// in hand, reached through a channel (`ScopedContext`) that carries the
347+
// reader's own context. The hook body's `ctx.title()` is built on it.
348+
describe('serveFormulaField — a record in hand, served as a read serves it', () => {
349+
const LOAN_SCHEMA = { name: 'lib_loan', nameField: 'title' };
350+
351+
it('reads the hop through the IN-HAND foreign keys, one batched read per reference field', async () => {
352+
d.calls.length = 0;
353+
// Stored l1 names b1; the in-flight state names b2.
354+
const value = await engine.createContext(READER).serveFormulaField('lib_loan', { id: 'l1', book: 'b2', reader: 'r1' }, 'title');
355+
expect(value).toBe('Emma · Ann');
356+
expect(relatedReads('lib_book')).toBe(1);
357+
expect(relatedReads('lib_reader')).toBe(1);
358+
expect(relatedReads('lib_loan')).toBe(0);
359+
expect(d.calls.find((c) => c.object === 'lib_book')!.ast.where).toEqual({ id: { $in: ['b2'] } });
360+
});
361+
362+
it('answers the title a read of the same record answers, where the synchronous evaluator answers none', async () => {
363+
const read = await engine.findOne('lib_loan', { where: { id: 'l3' }, context: READER });
364+
const inHand = { id: 'l3', book: 'b3', reader: 'r2' };
365+
expect(await resolveServedRecordTitle(LOAN_SCHEMA, inHand, engine.createContext(READER))).toBe(read?.title);
366+
expect(read?.title).toBe('Ulysses · Bo');
367+
// The before-state of this seam: no hop, no title.
368+
expect(resolveRecordTitle({ ...LOAN_SCHEMA, fields: engine.getObject('lib_loan')!.fields }, inHand)).toBeUndefined();
369+
});
370+
371+
it('a formula over the record\'s own columns reads nothing', async () => {
372+
d.calls.length = 0;
373+
expect(await engine.createContext(READER).serveFormulaField('lib_book', { id: 'b1', title: 'dune' }, 'shout')).toBe('DUNE');
374+
expect(d.calls).toEqual([]);
375+
});
376+
377+
it('a field that is not a formula answers undefined, so the stored column is read instead', async () => {
378+
expect(await engine.createContext(READER).serveFormulaField('lib_loan', { id: 'l1', book: 'b1' }, 'book')).toBeUndefined();
379+
});
380+
381+
it('reads the hop on the transaction the channel carries', async () => {
382+
const trx = { __trx: 'body' };
383+
d.calls.length = 0;
384+
await engine.createContext({ ...READER, transaction: trx }).serveFormulaField('lib_loan', { id: 'l1', book: 'b1', reader: 'r1' }, 'title');
385+
const hops = d.calls.filter((c) => c.object === 'lib_book' || c.object === 'lib_reader');
386+
expect(hops).toHaveLength(2);
387+
for (const c of hops) expect(c.options?.transaction).toBe(trx);
388+
});
389+
390+
it('a related record the channel may not read leaves it null with the read\'s reason, and leaks nothing', async () => {
391+
engine.registerMiddleware(async (ctx: any, next: () => Promise<void>) => {
392+
if (ctx.object === 'lib_reader' && ['find', 'findOne'].includes(ctx.operation) && !ctx.context?.isSystem) {
393+
const scoped = { visible: true };
394+
ctx.ast = { ...(ctx.ast ?? {}), where: ctx.ast?.where ? { $and: [ctx.ast.where, scoped] } : scoped };
395+
}
396+
await next();
397+
});
398+
const inHand = { id: 'lx', book: 'b1', reader: 'r_hidden' };
399+
expect(await engine.createContext(READER).serveFormulaField('lib_loan', inHand, 'title')).toBeNull();
400+
expect(await resolveServedRecordTitle(LOAN_SCHEMA, inHand, engine.createContext(READER))).toBeUndefined();
401+
expect(faultsOn('lib_loan', 'title')[0].message).toContain('was not found by this read');
402+
// CONTROL — the SYSTEM channel reads the reader.
403+
expect(await engine.createContext({ isSystem: true }).serveFormulaField('lib_loan', inHand, 'title')).toBe('Dune · Hidden Person');
404+
});
405+
406+
it('a second hop reached through the related object\'s formula is not served', async () => {
407+
registerLoan('record.book.shelf_code');
408+
d.calls.length = 0;
409+
expect(await engine.createContext(READER).serveFormulaField('lib_loan', { id: 'l1', book: 'b1' }, 'title')).toBeNull();
410+
expect(relatedReads('lib_shelf')).toBe(0);
411+
});
412+
413+
it('servedRecordTitle reads the title a read served off the row, never re-derived', async () => {
414+
const book = { name: 'lib_book', nameField: 'shelf_code', fields: engine.getObject('lib_book')!.fields };
415+
// A row a read returned with its one-hop title served…
416+
expect(servedRecordTitle(book, { id: 'b1', title: 'Dune', shelf: 's1', shelf_code: 'A-1' })).toBe('A-1');
417+
// …which the synchronous re-derivation throws away.
418+
expect(resolveRecordTitle(book, { id: 'b1', title: 'Dune', shelf: 's1', shelf_code: 'A-1' })).toBeUndefined();
419+
// A row the read served no title on has none.
420+
expect(servedRecordTitle(book, { id: 'b1', title: 'Dune', shelf: 's1', shelf_code: null })).toBeUndefined();
421+
});
422+
});
342423
});

‎packages/objectql/src/engine.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2851,6 +2851,8 @@ async function hydrateWriteFormulas(
28512851
* above. [#24197] For the same reason it preloads no relationship hop, so a
28522852
* formula reading `record.<reference>.<field>` yields `null` here too. The read and write paths resolve the map first
28532853
* ({@link ObjectQL.resolveFormulaPermissions}); a helper with no resolver cannot.
2854+
* A caller that holds a read channel and wants the read's answer calls
2855+
* {@link ObjectQL.serveFormulaField} (through `ScopedContext.serveFormulaField`).
28542856
*
28552857
* Returns `undefined` when `field` is not a declared formula field, which is
28562858
* how a caller tells "read the stored column instead" from "the formula
@@ -6215,6 +6217,57 @@ export class ObjectQL implements IObjectQLEngine {
62156217
return (row) => lookup(row);
62166218
}
62176219

6220+
/**
6221+
* [#24197] Materialize ONE declared `formula` field against a record already
6222+
* in hand, SERVED the way a read serves it: the one hop the formula reads
6223+
* through a reference field ({@link resolveFormulaRelated}), the `can()`
6224+
* permission map ({@link resolveFormulaPermissions}) and the fault report
6225+
* ({@link formulaFaultSink}), all under `context`.
6226+
*
6227+
* The asynchronous twin of the module's {@link evaluateFormulaField}, which
6228+
* is synchronous and so serves none of the three. It exists for a record the
6229+
* engine never read back — a hook's in-flight state (stored ⊕ payload), whose
6230+
* foreign keys may name records the stored row does not — so the title a hook
6231+
* body asks for (`ctx.title()`) is the title a read of that state would show.
6232+
*
6233+
* ## Under which authority, on which connection
6234+
*
6235+
* `context` is the reader's own: every hop is the reader's own `find`, through
6236+
* every enforcement layer a read applies, exactly as the read path's hop is
6237+
* (`authority: 'caller'`). A related record that read does not return leaves
6238+
* the formula `null` with the read path's reason — never a fallback. A context
6239+
* carrying a `transaction` reads on that transaction's connection, so a body
6240+
* that opened one never asks the pool for a second (a deadlock on SQLite's
6241+
* `pool max=1`). Call it through {@link ScopedContext.serveFormulaField},
6242+
* which hands in the context the body's own `ctx.api` reads with.
6243+
*
6244+
* ## What it costs
6245+
*
6246+
* One batched read per reference field the formula reads through — the read
6247+
* path's own cost for one row — and nothing for a formula over the record's
6248+
* own columns. A read that is itself a formula's hop serves no hop of its own,
6249+
* so a second hop reads `null` with its reason here as it does on a read.
6250+
*
6251+
* Returns `undefined` when `field` is not a declared formula field on
6252+
* `objectName`, as {@link evaluateFormulaField} does. Evaluates against a
6253+
* shallow COPY of `record`.
6254+
*/
6255+
async serveFormulaField(
6256+
objectName: string,
6257+
record: Record<string, unknown>,
6258+
field: string,
6259+
context?: ExecutionContext,
6260+
): Promise<unknown> {
6261+
const schema = this._registry.getObject(objectName);
6262+
const { plan } = planFormulaProjection(schema, [field]);
6263+
if (plan.length === 0) return undefined;
6264+
const scratch: Record<string, unknown> = { ...record };
6265+
applyFormulaPlan(plan, [scratch], context, await this.resolveFormulaPermissions(
6266+
objectName, plan, [scratch], context, this.permissionResolution(context),
6267+
), this.formulaFaultSink(objectName), await this.resolveFormulaRelated(schema, plan, [scratch], context));
6268+
return scratch[field];
6269+
}
6270+
62186271
/**
62196272
* [#22019] The (object, field) pairs whose formula fault this engine instance
62206273
* has already reported — see {@link reportFormulaFault}.
@@ -21714,4 +21767,17 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi {
2171421767

2171521768
/** Internal: expose the transaction handle for driver-level access */
2171621769
get transactionHandle() { return this.executionContext.transaction; }
21770+
21771+
/**
21772+
* [#24197] One declared `formula` field of `objectName`, evaluated over
21773+
* `record` as a read under THIS context serves it — {@link
21774+
* ObjectQL.serveFormulaField} with this context's own execution context, so
21775+
* the one hop the formula reads through a reference is read with this
21776+
* context's identity and permissions and, inside a transaction this context
21777+
* carries, on that transaction's connection. `undefined` when `field` is not
21778+
* a declared formula field.
21779+
*/
21780+
async serveFormulaField(objectName: string, record: Record<string, unknown>, field: string): Promise<unknown> {
21781+
return (this.engine as unknown as ObjectQL).serveFormulaField(objectName, record, field, this.executionContext);
21782+
}
2171721783
}

‎packages/objectql/src/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,11 +402,13 @@ export { hookRecordState } from './hook-wrappers.js';
402402
// exactly these; they are exported so it does not have to re-derive any of it.
403403
export {
404404
resolveRecordTitle,
405+
resolveServedRecordTitle,
406+
servedRecordTitle,
405407
resolveRelatedTitleTarget,
406408
titleFieldOf,
407409
RecordTitleFieldError,
408410
} from './record-title.js';
409-
export type { RelatedTitleTarget } from './record-title.js';
411+
export type { RelatedTitleTarget, FormulaServingChannel } from './record-title.js';
410412
export { evaluateFormulaField } from './engine.js';
411413

412414
// Export Validation

0 commit comments

Comments
 (0)