Skip to content

Commit f6836ca

Browse files
fix(cli): run an app's onEnable and its handlers from one module evaluation (#34297)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbTGhxJSYAmQXU7efVdNqrpw)_ Fixes #34179 Clause-②: no Metadata-protocol: none (boot composition; no authorable key changes; the dev confirms against the diff) ## 维护者速读 - 改了什么:从编译产物启动时,应用的 job/hook/action 处理函数改为和 `onEnable` 取自同一次加载的配置模块,不再一部分取自产物里打包的 runtime 模块(那是同一份源码的第二次求值)。 - 为什么改:`onEnable` 在模块级保存的状态(例如 duly 的数据引擎)在 job 里读不到,`os dev` 下 job 每次都报 "no data engine";实测非 host 配置的 `os start` 生产启动也一样。 - 风险与回滚:只影响从产物启动且配置带 `onEnable` 的启动;元数据仍取自产物。产物里有、源码里已没有的处理函数保持原样,并打印一次警告。回滚即 revert 本 PR。 - 先看:`packages/cli/src/utils/graft-runtime-hooks.ts`(`graftAuthoredRuntimeMembers` 的改指向逻辑),然后是 `packages/cli/src/commands/serve.ts` 的两处调用和警告文案。 - 两分钟验证:`pnpm --filter @objectstack/cli exec vitest run --project unit src/utils/graft-runtime-hooks.test.ts`,预期 21 个用例全绿,其中 "a job handler and a hook see the state onEnable bound" 通过。 - 需要你做的:无,席位落地。 ## What changes A boot that serves the compiled artifact gets the app's callables from the artifact's runtime module (`dist/objectstack-runtime.*.mjs`). `loadArtifactBundle` imports that module and `mergeRuntimeModule` merges its `functions`. The module is an esbuild bundle of the same config source, so it is a second evaluation of it, with its own module state. serve then grafted the loaded config module's `onEnable` beside those callables. So `onEnable` and the handlers ran from two evaluations, and state that `onEnable` binds at module scope never reached a handler. `graftAuthoredRuntimeMembers` (now async, still the one graft both serve routes call) closes the split. The re-point runs only when the target bundle has a `runtimeModule` and runs the config module's `onEnable`. In that case every callable the runtime module supplied is replaced, ref for ref, with the config module's own callable. The ref map is `lowerCallables(normalizeStackInput(config)).functions`, the same reading `os compile` writes the runtime module from. Each entry keeps its declaration (`effect`, and so on), and no entry without a callable gains one. The lowering is loaded lazily, so a boot without the split does not load the TypeScript parser. - **Doors fixed:** `os dev` on a host config (the `devArtifactDoor` wrap) and on a non-host config, and `os start` / `os serve` on a non-host config (the standalone stack plus the `hasAppPluginAlready` graft). The production path was measured double-evaluating too. - **Doors unchanged:** a boot from an artifact alone (no config module, so no `onEnable` at all), and host `os start` (it already wraps the module, one evaluation). - **Stale artifact:** if the artifact names a ref the config no longer serves (for example `os dev --no-compile` over an older build), that callable stays on the runtime module. The boot then warns once and names it. Files: - `packages/cli/src/utils/graft-runtime-hooks.ts` - `packages/cli/src/commands/serve.ts` (both call sites, the warning, the #31761 docblock) - `packages/cli/src/utils/graft-runtime-hooks.test.ts` (pins; existing cases now `await`) - `packages/cli/test/normalized-call-sites.test.ts` (one `top-level` row for the deliberate `bundle.functions` read, granted by the area) - `.changeset/34179-dev-one-module-evaluation.md` (patch) ## Tests The new pin composes the boot from the real producer to the real reader, in the cli unit tier. It runs an in-process `os compile` on a fixture whose `onEnable` binds a module-scope engine. A `functions` entry (the shape a job `handler` names) and a hook read that engine. The pin loads the artifact with the runtime's own `loadArtifactBundle`, loads the config with serve's `bundleConfigModule`, and wraps it in a real `AppPlugin`. It then reads handlers through `collectBundleFunctions`, the map job and string-named hook handlers resolve against. It asserts that both handlers see the engine. Further cases cover a stale ref (reported, left alone), the array form, a bundle with no runtime module, and a bundle whose own `onEnable` won (both untouched). ## Acceptance notes - **Artifact-only boot:** it runs no `onEnable` because the runtime module exports only `functions`. This is a single evaluation and the documented behaviour (the job context hands `ql` for that reason), so it is not this defect. - **`--no-compile` with matching refs:** handlers now run the edited source's code beside the artifact's metadata. That is the rule the #31761 docblock states: the module contributes the members a JSON artifact cannot carry. `onEnable` already came from the module there. ## Verification Head e367244 (`origin/main` merged). Session `session_01QsR2jTEivi2wogPpeo3xd5`. <details><summary>Ablation: put the two-evaluation composition back</summary> `node scripts/ablation-replace.mjs` mutated the re-point line (anchor x1 to x0; blob 4ae519b to 250315e758f2), then ran the pin file: ``` × a job handler and a hook see the state onEnable bound × re-points the refs the module serves and reports the ones it does not (an artifact older than its source) × re-points the array form too, and never gives an entry without a callable one Caused by: Error: Job 'one_dispatch' has no data engine Tests 3 failed | 18 passed (21) ablation-replace: ok restored: blob == HEAD (4ae519b) and `git diff HEAD` is empty ``` </details> <details><summary>Real boots: a 1 s interval job writes the module state onEnable set</summary> Built `bin/run.js`, `OS_AUTOMATION_SCHEDULED_WORK_ENABLED=true`. The "main" column is this build with the re-point line removed from `dist/` (restored by sha256 afterwards). It is the same composition as `main`, not a separate build. | door | main | this PR | |:--|:--|:--| | host config, `os dev` | `unset` | `bound` | | host config, `os start` | `bound` | `bound` | | non-host config, `os dev` | `unset` | `bound` | | non-host config, `os start` | `unset` | `bound` | | artifact only, `os start` | `unset` (no onEnable runs) | `unset` (unchanged) | Host `os dev --no-compile` with refs matching: `bound`. With the job's function renamed in source after compiling: `unset`, plus this warning: ``` ⚠ 1 handler of the compiled artifact (mm_job) has no counterpart in objectstack.config.ts as this boot evaluated it, so it runs from ./objectstack-runtime.433af1218610613d.mjs, a second evaluation of the same source: module state its onEnable sets is not visible there. Recompile (os compile) so the artifact matches the config. ``` </details> <details><summary>Local gates on e367244</summary> - `pnpm --filter @objectstack/cli typecheck` (`NODE_OPTIONS=--max-old-space-size=8192`): exit 0. - cli unit project (`vitest run --project unit`): Test Files 423 passed (423), Tests 6017 passed (6017). - `pnpm lint`: exit 0. - `dispatch-gates --commands` on the merged tree: 74 families, all exit 0, reconciled with `--ran` ("74 run, 0 NOT-MEASURED (a DERIVED zero)"). - `check:dual-build-cjs-loads` and `check:i18n-coverage` first exited 3 (workspace not built). Both read exit 0 after a whole-workspace build. - `check:type-check-debt` first answered 99 (lock queue). It read exit 0 on the re-take. - cli `integration` tier: declared to CI (no spawn entry or integration file touched). - Direct dependents of `@objectstack/cli`: declared to CI. `graft-runtime-hooks` is not in the package's `exports`, so the published surface is unchanged. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e53e02e commit f6836ca

5 files changed

Lines changed: 424 additions & 53 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
fix(cli): an app's `onEnable` and its job, hook and action handlers run from one evaluation of its config module
6+
7+
Clause-②: no
8+
Metadata-protocol: none (boot composition; no authorable key changes; the dev confirms against the diff)
9+
10+
A boot that serves the compiled artifact took the handlers from the artifact's runtime module (`dist/objectstack-runtime.*.mjs`). That module is a bundle of the same config source, so it is a second evaluation of it. `onEnable` came from the config module the boot had loaded. State that `onEnable` sets at module scope, such as a data engine a job reads, was therefore missing when the handler ran. Under `os dev` on a host config, a job that read it failed on every run with "no data engine", while `os start` served the same project.
11+
12+
`os start` and `os serve` on a config without its own plugin instances (a non-host config) had the same split, because they boot from the compiled artifact too and add the config's `onEnable` the same way.
13+
14+
Every handler the runtime module supplies now runs from the config module this boot loaded, the same module as `onEnable`. This covers `os dev` on any config and `os start` / `os serve` on a non-host config. A boot from an artifact alone, with no config, is unchanged: it has no `onEnable` to run. Handlers are matched by the ref the build gave them. Metadata still comes from the artifact. If the artifact names a handler that the config no longer has (for example `os dev --no-compile` over an older build), that handler still runs from the runtime module. The boot warns once and names it.

‎packages/cli/src/commands/serve.ts‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ import {
118118
type ListenerProtocol,
119119
} from '../utils/dev-tls-contract.js';
120120
import { BootLogCapture, isVerboseBootLevel } from '../utils/boot-log-capture.js';
121-
import { graftAuthoredRuntimeMembers, isAppPluginLike } from '../utils/graft-runtime-hooks.js';
121+
import { graftAuthoredRuntimeMembers, isAppPluginLike, type RuntimeGraftResult } from '../utils/graft-runtime-hooks.js';
122122
// [ADR-0130 D4 / option B, #15006] Every read below that keys off a
123123
// PACKAGE-OWNED collection goes through this seam, so an option-B artifact
124124
// (flattened top level gone, `packages[]` carrying everything once) reaches
@@ -3876,7 +3876,23 @@ export default class Serve extends Command {
38763876
// order and one story in the boot logs.
38773877
// A config whose code found no app bundle to land on is reported, never
38783878
// dropped (#4095) — on both routes below that graft it.
3879-
const warnOrphanedRuntimeMembers = (graft: ReturnType<typeof graftAuthoredRuntimeMembers>): void => {
3879+
const reportRuntimeGraft = (graft: RuntimeGraftResult): void => {
3880+
// The graft's other loud answer: code of the artifact's runtime module
3881+
// that the module this boot evaluated does not serve, so it still runs
3882+
// from that module's separate evaluation and cannot see state the
3883+
// config's `onEnable` binds. Said once, naming the refs and the remedy.
3884+
const unbound = graft.unbound ?? [];
3885+
if (unbound.length > 0) {
3886+
console.warn(chalk.yellow(
3887+
` ⚠ ${unbound.length} handler${unbound.length === 1 ? '' : 's'} of the compiled artifact `
3888+
+ `(${unbound.join(', ')}) ${graft.rebindError
3889+
? `could not be matched to ${relativeConfig} (${graft.rebindError})`
3890+
: `${unbound.length === 1 ? 'has' : 'have'} no counterpart in ${relativeConfig} as this boot evaluated it`}`
3891+
+ `, so ${unbound.length === 1 ? 'it runs' : 'they run'} from ${graft.runtimeModule}, a second evaluation of`
3892+
+ `\n the same source: module state its onEnable sets is not visible there. Recompile (os compile) so the`
3893+
+ '\n artifact matches the config.',
3894+
));
3895+
}
38803896
if (graft.orphaned.length === 0) return;
38813897
console.warn(chalk.yellow(
38823898
` ⚠ ${relativeConfig} exports ${graft.orphaned.join(' / ')} but no app bundle claimed `
@@ -3909,6 +3925,16 @@ export default class Serve extends Command {
39093925
// the same module, so nothing served changes; with `--no-compile`
39103926
// the boot serves the artifact, as the warning says.
39113927
//
3928+
// "One evaluation" is the graft's to keep, not the compile's: the
3929+
// artifact's callables arrive from its compiled runtime module, an
3930+
// esbuild bundle of this same source and so a SECOND evaluation of
3931+
// it, and grafting the module's `onEnable` beside them put state
3932+
// `onEnable` binds at module scope out of every handler's reach (a
3933+
// job reading it failed each run while `os start` served it).
3934+
// `graftAuthoredRuntimeMembers` re-points those callables at the module's own,
3935+
// ref for ref, so `onEnable` and every handler share one evaluation;
3936+
// a ref the module no longer serves is announced, never left silent.
3937+
//
39123938
// An artifact that does not load (malformed, unreadable) leaves the
39133939
// module as the wrap's bundle, as before — `loadArtifactBundle`
39143940
// has already said why, and the door, reading the same bytes,
@@ -3932,7 +3958,7 @@ export default class Serve extends Command {
39323958
// Grafted onto THIS wrap only: the host's own `plugins[]` may hold
39333959
// other apps, and the module's code belongs to the bundle it was
39343960
// compiled into.
3935-
warnOrphanedRuntimeMembers(graftAuthoredRuntimeMembers([wrap], config));
3961+
reportRuntimeGraft(await graftAuthoredRuntimeMembers([wrap], config));
39363962
// The ready banner names the file the metadata came from (#21501).
39373963
configBootBundle = path.relative(process.cwd(), devArtifactDoorPath) || devArtifactDoorPath;
39383964
}
@@ -3960,8 +3986,12 @@ export default class Serve extends Command {
39603986
// — that silent drop is what hid this.
39613987
// Success is silent: on the config-boot path this is now the normal
39623988
// route by which handlers reach the engine, and the observable proof is
3963-
// that the actions dispatch.
3964-
warnOrphanedRuntimeMembers(graftAuthoredRuntimeMembers(plugins, config));
3989+
// that the actions dispatch. The standalone stack's bundle got its
3990+
// callables from the artifact's runtime module, a second evaluation of
3991+
// this source, so the graft also re-points them at the module's own
3992+
// (`graftAuthoredRuntimeMembers`): the `onEnable` grafted here and every handler
3993+
// then share one module evaluation, as the wrap above gives a host.
3994+
reportRuntimeGraft(await graftAuthoredRuntimeMembers(plugins, config));
39653995
}
39663996

39673997
// 3b. Auto-register I18nServicePlugin if config contains translations/i18n

0 commit comments

Comments
 (0)