From 288a2bd6dcb13e8310eb31cbe65db9ae149bf436 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Sun, 4 Oct 2026 16:09:45 +0800 Subject: [PATCH] fix(cordis): adopt effect disposers from their owning fiber --- docs/cordis-api/fiber.i18n.yaml | 68 ++++++++++++------------- docs/cordis-api/fiber.md | 34 ++++++------- docs/cordis-api/fiber.zh.md | 34 ++++++------- packages/core/scope/tests/scope.spec.ts | 34 ++++++++++++- vendor/README.md | 2 +- vendor/cordis/src/fiber.ts | 6 ++- 6 files changed, 107 insertions(+), 71 deletions(-) diff --git a/docs/cordis-api/fiber.i18n.yaml b/docs/cordis-api/fiber.i18n.yaml index acc84e2f3a..4936b0e926 100644 --- a/docs/cordis-api/fiber.i18n.yaml +++ b/docs/cordis-api/fiber.i18n.yaml @@ -9,56 +9,56 @@ en: b5b3510f4b6dd13a zh: a0c70471b6d779b5 /fiber/ctx-effect-execute-label: - en: ef3418fd5ffbe86d - zh: c98935435da8bc7e + en: 49e7a90726351489 + zh: 4db6bc88e42f016e /fiber/ctx-fiber: en: a10e38bf26b4ecfe zh: 7c91817984c95c99 /fiber/the-fiber-class: - en: 0e0fcb134ed44957 - zh: 326f4232aa0e65d1 + en: 0236f94c618945af + zh: 49653ee34995ff85 /fiber/the-fiber-class/fiber-uid: - en: 2f0eb3658bb8497e - zh: 65d3c17ca8bd4f95 + en: 79c8967b6a2cdd2d + zh: 0f8742c72403678f /fiber/the-fiber-class/fiber-ctx: - en: 1b527d85759324f9 - zh: 54aa40db2705b95c + en: 336ae46a13dcd6d7 + zh: 8de906a115e8d89b /fiber/the-fiber-class/fiber-config: - en: ee804c03c39e7806 - zh: 4353ba7817ec61ec + en: b6602e675fbc5a6c + zh: b57d551306265ead /fiber/the-fiber-class/fiber-state: - en: 999ad29dfc29661b - zh: 20245d11c338e3f1 + en: 3cf3270ab93ac5a9 + zh: cbe060dc345d0727 /fiber/the-fiber-class/fiber-dispose: - en: 29e304d183eb9104 - zh: 9ac5023f518e06c4 + en: aae5e01bce1c0d26 + zh: 8efb2b510eb97ad6 /fiber/the-fiber-class/fiber-store: - en: c4185e5d051136a2 - zh: 5714d9e4f5461ca3 + en: dd95f75be5d5801c + zh: c684954d453f69c0 /fiber/the-fiber-class/fiber-inertia: - en: 2a3b1d3bc37bf986 - zh: 83bd257ee685d38b + en: e14d839e4ebe6093 + zh: df5ba69c211360b3 /fiber/the-fiber-class/fiber-name: - en: e5c2ecca13167a32 - zh: 284a461f0f1cd35b + en: e4f962090c7ec2d8 + zh: 09d98a9d8cc42d24 /fiber/the-fiber-class/fiber-assertactive: - en: cceb503899634d09 - zh: a8381af1a23436f3 + en: 41f16c6770cb4a42 + zh: 78e5a409fcb8b51d /fiber/the-fiber-class/fiber-effect-execute-label: - en: 55dcfacf295bbcf2 - zh: 6e3ec27bb8da5a3d + en: b5dcba51da82bb48 + zh: 102779d0a7033a83 /fiber/the-fiber-class/fiber-geteffects: - en: 4d739a9c186fd9c2 - zh: f80fd3b87e79b004 + en: 2681d305e49df146 + zh: c376155efa901cee /fiber/the-fiber-class/fiber-await: - en: 1d6258cbea61cd18 - zh: 2f10dda8918dadc5 + en: 8b60c045fea02941 + zh: b9f3e1fcaffa2208 /fiber/the-fiber-class/fiber-restart: - en: 62d68dedb20b4fa9 - zh: 5a735ae0ff1266f4 + en: 5bd67e068f3a4a66 + zh: 93c5abb9bc677abd /fiber/the-fiber-class/fiber-update-config-nosave: - en: b57ce0f6260c2cb8 - zh: 3bfb6c5bc252a2c2 + en: 2d77e40537926a7b + zh: 334b4e91d1ef9f39 /fiber/effect: en: 007d5b214e8a8610 zh: d74c26fbb1b8aeb6 @@ -69,8 +69,8 @@ en: 849aa91b8e67809f zh: 4b31d7e2acd2a008 /fiber/cordiserror: - en: d276771958d3c05f - zh: 0141656ade938d55 + en: 36c9d46499342212 + zh: 82e4012ae4efab4b /fiber/validationerror: en: 178782124cc15210 zh: 2b226f43f48af555 diff --git a/docs/cordis-api/fiber.md b/docs/cordis-api/fiber.md index 3044301eff..cc31600bb9 100644 --- a/docs/cordis-api/fiber.md +++ b/docs/cordis-api/fiber.md @@ -34,7 +34,7 @@ Register a cleanup-aware effect on this fiber. **Returns** a disposer that tears the effect down and settles once done. -[Source](../../vendor/cordis/src/fiber.ts#L415) +[Source](../../vendor/cordis/src/fiber.ts#L417) ### ctx.fiber @@ -53,7 +53,7 @@ Runtime instance of one plugin application. A fiber tracks dependency state, validated config, lifecycle effects, and cleanup for the plugin context returned by `ctx.plugin()`. -[Source](../../vendor/cordis/src/fiber.ts#L184) +[Source](../../vendor/cordis/src/fiber.ts#L186) ### fiber.uid @@ -64,7 +64,7 @@ public uid: number | null Unique id within the registry; 0 for the root fiber, `null` once disposed. -[Source](../../vendor/cordis/src/fiber.ts#L186) +[Source](../../vendor/cordis/src/fiber.ts#L188) ### fiber.ctx @@ -75,7 +75,7 @@ public readonly ctx: Context The context this fiber's plugin runs in (extends the parent context). -[Source](../../vendor/cordis/src/fiber.ts#L188) +[Source](../../vendor/cordis/src/fiber.ts#L190) ### fiber.config @@ -86,7 +86,7 @@ public config: any The validated plugin config (updated by `update()`). -[Source](../../vendor/cordis/src/fiber.ts#L190) +[Source](../../vendor/cordis/src/fiber.ts#L192) ### fiber.state @@ -97,7 +97,7 @@ public state Current lifecycle state; transitions emit `internal/status`. -[Source](../../vendor/cordis/src/fiber.ts#L194) +[Source](../../vendor/cordis/src/fiber.ts#L196) ### fiber.dispose @@ -108,7 +108,7 @@ public readonly dispose: () => Promise Dispose this fiber: unload the plugin, then settle once cleanup finished. -[Source](../../vendor/cordis/src/fiber.ts#L196) +[Source](../../vendor/cordis/src/fiber.ts#L198) ### fiber.store @@ -119,7 +119,7 @@ public store: Dict | undefined Snapshot of required service implementations while loaded; `undefined` otherwise. -[Source](../../vendor/cordis/src/fiber.ts#L198) +[Source](../../vendor/cordis/src/fiber.ts#L200) ### fiber.inertia @@ -130,7 +130,7 @@ public inertia: Promise | undefined The in-flight load/unload transition, if one is currently running. -[Source](../../vendor/cordis/src/fiber.ts#L200) +[Source](../../vendor/cordis/src/fiber.ts#L202) ### fiber.name @@ -141,7 +141,7 @@ get name() The plugin's display name, inherited from the nearest named ancestor, else `'root'`. -[Source](../../vendor/cordis/src/fiber.ts#L336) +[Source](../../vendor/cordis/src/fiber.ts#L338) ### fiber.assertActive() @@ -159,7 +159,7 @@ Throw if the fiber has already been disposed. **Returns** nothing when the fiber is still active. -[Source](../../vendor/cordis/src/fiber.ts#L351) +[Source](../../vendor/cordis/src/fiber.ts#L353) ### fiber.effect(execute, label?) @@ -190,7 +190,7 @@ Register a cleanup-aware effect on this fiber. **Returns** a disposer that tears the effect down and settles once done. -[Source](../../vendor/cordis/src/fiber.ts#L415) +[Source](../../vendor/cordis/src/fiber.ts#L417) ### fiber.getEffects() @@ -207,7 +207,7 @@ Return metadata for currently registered effects. **Returns** one `EffectMeta` tree per labeled live effect. -[Source](../../vendor/cordis/src/fiber.ts#L568) +[Source](../../vendor/cordis/src/fiber.ts#L572) ### fiber.await() @@ -225,7 +225,7 @@ Wait for current lifecycle work and rethrow startup errors. **Returns** this fiber, once it has settled into a stable state. -[Source](../../vendor/cordis/src/fiber.ts#L704) +[Source](../../vendor/cordis/src/fiber.ts#L708) ### fiber.restart() @@ -243,7 +243,7 @@ Dispose and immediately reload this plugin with its current config. **Returns** a promise resolving once the reload settled. -[Source](../../vendor/cordis/src/fiber.ts#L718) +[Source](../../vendor/cordis/src/fiber.ts#L722) ### fiber.update(config, noSave?) @@ -271,7 +271,7 @@ Runs the `internal/update` waterfall first, so update hooks (and HMR) can veto o **Returns** nothing; the restart runs behind the `internal/update` waterfall. -[Source](../../vendor/cordis/src/fiber.ts#L736) +[Source](../../vendor/cordis/src/fiber.ts#L740) ## Effect @@ -352,7 +352,7 @@ namespace CordisError { } ``` -[Source](../../vendor/cordis/src/fiber.ts#L157) +[Source](../../vendor/cordis/src/fiber.ts#L159) ## ValidationError diff --git a/docs/cordis-api/fiber.zh.md b/docs/cordis-api/fiber.zh.md index bee2f523f1..1d5dc3cee5 100644 --- a/docs/cordis-api/fiber.zh.md +++ b/docs/cordis-api/fiber.zh.md @@ -36,7 +36,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable> **返回**一个用于撤销该作用的清理函数,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L415) +[源码](../../vendor/cordis/src/fiber.ts#L417) ### ctx.fiber @@ -55,7 +55,7 @@ fiber: Fiber fiber 会跟踪 `ctx.plugin()` 返回的插件上下文所对应的依赖状态、经过校验的配置、生命周期作用和清理操作。 -[源码](../../vendor/cordis/src/fiber.ts#L184) +[源码](../../vendor/cordis/src/fiber.ts#L186) ### fiber.uid @@ -66,7 +66,7 @@ public uid: number | null 在注册表中的唯一 id;根 fiber 的 id 为 0,dispose 后为 `null`。 -[源码](../../vendor/cordis/src/fiber.ts#L186) +[源码](../../vendor/cordis/src/fiber.ts#L188) ### fiber.ctx @@ -77,7 +77,7 @@ public readonly ctx: Context 此 fiber 的插件运行所在的上下文(扩展自父上下文)。 -[源码](../../vendor/cordis/src/fiber.ts#L188) +[源码](../../vendor/cordis/src/fiber.ts#L190) ### fiber.config @@ -88,7 +88,7 @@ public config: any 经过校验的插件配置(由 `update()` 更新)。 -[源码](../../vendor/cordis/src/fiber.ts#L190) +[源码](../../vendor/cordis/src/fiber.ts#L192) ### fiber.state @@ -99,7 +99,7 @@ public state 当前生命周期状态;状态转换会发出 `internal/status`。 -[源码](../../vendor/cordis/src/fiber.ts#L194) +[源码](../../vendor/cordis/src/fiber.ts#L196) ### fiber.dispose @@ -110,7 +110,7 @@ public readonly dispose: () => Promise dispose 此 fiber:卸载插件,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L196) +[源码](../../vendor/cordis/src/fiber.ts#L198) ### fiber.store @@ -121,7 +121,7 @@ public store: Dict | undefined 加载期间所需服务实现的快照;其他情况下为 `undefined`。 -[源码](../../vendor/cordis/src/fiber.ts#L198) +[源码](../../vendor/cordis/src/fiber.ts#L200) ### fiber.inertia @@ -132,7 +132,7 @@ public inertia: Promise | undefined 当前正在进行的加载或卸载转换;如果没有此类转换,则为 undefined。 -[源码](../../vendor/cordis/src/fiber.ts#L200) +[源码](../../vendor/cordis/src/fiber.ts#L202) ### fiber.name @@ -143,7 +143,7 @@ get name() 插件的显示名称,继承自最近的具名祖先;如果不存在,则为 `'root'`。 -[源码](../../vendor/cordis/src/fiber.ts#L336) +[源码](../../vendor/cordis/src/fiber.ts#L338) ### fiber.assertActive() @@ -161,7 +161,7 @@ assertActive() **返回**:fiber 仍处于活动状态时不返回任何内容。 -[源码](../../vendor/cordis/src/fiber.ts#L351) +[源码](../../vendor/cordis/src/fiber.ts#L353) ### fiber.effect(execute, label?) @@ -192,7 +192,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable> **返回**一个用于撤销该作用的清理函数,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L415) +[源码](../../vendor/cordis/src/fiber.ts#L417) ### fiber.getEffects() @@ -209,7 +209,7 @@ getEffects() **返回**:每个带标签的活动作用对应一棵 `EffectMeta` 树。 -[源码](../../vendor/cordis/src/fiber.ts#L568) +[源码](../../vendor/cordis/src/fiber.ts#L572) ### fiber.await() @@ -227,7 +227,7 @@ async await() **返回**:进入稳定状态后的此 fiber。 -[源码](../../vendor/cordis/src/fiber.ts#L704) +[源码](../../vendor/cordis/src/fiber.ts#L708) ### fiber.restart() @@ -245,7 +245,7 @@ dispose 此插件,并立即使用其当前配置重新加载。 **返回**一个在重新加载完成后兑现的 promise。 -[源码](../../vendor/cordis/src/fiber.ts#L718) +[源码](../../vendor/cordis/src/fiber.ts#L722) ### fiber.update(config, noSave?) @@ -273,7 +273,7 @@ update(config: any, noSave = false) **返回**无返回值;重启由 `internal/update` waterfall 执行。 -[源码](../../vendor/cordis/src/fiber.ts#L736) +[源码](../../vendor/cordis/src/fiber.ts#L740) ## Effect @@ -354,7 +354,7 @@ namespace CordisError { } ``` -[源码](../../vendor/cordis/src/fiber.ts#L157) +[源码](../../vendor/cordis/src/fiber.ts#L159) ## ValidationError diff --git a/packages/core/scope/tests/scope.spec.ts b/packages/core/scope/tests/scope.spec.ts index fa9c1dc705..13942fdf9d 100644 --- a/packages/core/scope/tests/scope.spec.ts +++ b/packages/core/scope/tests/scope.spec.ts @@ -1,4 +1,4 @@ -import { describe, expect, expectTypeOf, it } from 'vitest' +import { describe, expect, expectTypeOf, it, onTestFinished } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { bindScopeParent, carrierKeyOf, createScope, isScopeCarrier, scopeChainOf, scopeOf, scopeParentOf, scopeTarget } from '@deepseek-ai/dsh-scope' import type { Scope, Scoped } from '@deepseek-ai/dsh-scope' @@ -87,6 +87,38 @@ describe('createScope', () => { await dispose() expect(order).toEqual(['inner', 'scope', 'outer']) }) + + it('moves scope cleanup to a composite on another fiber', async () => { + const ctx = new Context() + const release = Promise.withResolvers() + onTestFinished(async () => { + release.resolve(undefined) + await ctx.fiber.dispose() + }) + let originCtx!: Context + const origin = await ctx.plugin((inner: Context) => { originCtx = inner }) + const scope = createScope(originCtx, { name: 'cross-fiber' }) + const order: string[] = [] + scope.ctx.effect(() => () => { order.push('scope') }) + const draining = Promise.withResolvers() + const owner = await ctx.plugin((inner: Context) => { + inner.effect(function* () { + yield scope.rawDispose + yield async () => { + draining.resolve(undefined) + await release.promise + order.push('drained') + } + }) + }) + const disposal = owner.dispose() + await draining.promise + await origin.dispose() + expect(order).toEqual([]) + release.resolve(undefined) + await disposal + expect(order).toEqual(['drained', 'scope']) + }) }) describe('scopeTarget', () => { diff --git a/vendor/README.md b/vendor/README.md index 71cd648b03..1de68b02bd 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -35,7 +35,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. 3. **All `tsconfig.json` files**: regenerated to extend the repo-root `tsconfig.base.json`, emit TypeScript intermediates to `lib/types`, and declare project references. 4. **Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces. 5. **`schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface. -6. **`cordis/src/fiber.ts` lifecycle hardening**: locally closes three reentrant disposal gaps. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, skip plugin execution when reentrant disposal invalidates the load epoch before its first checkpoint, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup. +6. **`cordis/src/fiber.ts` lifecycle hardening**: locally hardens reentrant and composed disposal. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. A composite effect adopts each returned or yielded Cordis disposer from its original fiber, including when the dependency context and cleanup owner are different fibers; the original fiber cannot independently dispose the adopted resource. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, skip plugin execution when reentrant disposal invalidates the load epoch before its first checkpoint, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup. 7. **Cordis and Loader JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed to the fork. 8. **`include/src/index.ts` resilient file refresh and patch reapplication**: [#514](https://github.com/deepseek-harness/deepseek-harness/pull/514) validates a top-level entry array before caching parsed content, logs refresh failures, reapplies patches after file or Include-config edits, updates the Include config when it vetoes a restart, and uses `initial` only after `ENOENT`. These parse protections retain the running tree after an invalid file; plugin activation failures can leave a partially applied tree. Loader entry/group/tree mutations follow the pinned eager, non-transactional implementation and do not restore previous plugins or options. Covered by `packages/boot/app-boot/tests/{config-reload,user-patches}.spec.ts`. 9. **`hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. Covered by `packages/boot/hmr/tests/watch-config.spec.ts`. diff --git a/vendor/cordis/src/fiber.ts b/vendor/cordis/src/fiber.ts index 6bb1caa7a5..7ae2649dd5 100644 --- a/vendor/cordis/src/fiber.ts +++ b/vendor/cordis/src/fiber.ts @@ -110,6 +110,8 @@ interface EffectRunner { // Public effect disposers remain single-shot, but structural owners and outer // effects must still be able to join a cleanup that another caller started. const effectInertia = new WeakMap void | Promise>() +// Composites can adopt effects created through another fiber's dependency context. +const effectOwners = new WeakMap() function runDisposable(dispose: Disposable) { const result = dispose() @@ -447,7 +449,8 @@ export class Fiber { epoch: true, collect: (dispose) => { disposables.push(dispose) - this._disposables.delete(dispose) + const owner = effectOwners.get(dispose) ?? this + owner._disposables.delete(dispose) if (dispose[symbols.effect]) { meta.children.push(dispose[symbols.effect]) } @@ -513,6 +516,7 @@ export class Fiber { }) }, symbols.effect, meta) as AsyncDisposable effectInertia.set(wrapper, () => inFlight) + effectOwners.set(wrapper, this) // Make the effect visible to a reentrant owner unload before execute() // runs any plugin code. Async teardown stays owner-visible until it