Fix invariant readiness after CI sync

This commit is contained in:
Hypatia May
2026-07-31 00:20:18 +08:00
parent 6307708e34
commit be44f073e1
6 changed files with 352 additions and 50 deletions
+71 -15
View File
@@ -6,7 +6,7 @@
*/
import { expect } from 'vitest'
import { RegistryService } from 'cordis'
import { FiberState, Inject, RegistryService } from 'cordis'
import type { Context, Plugin } from 'cordis'
import InvariantService from '@deepseek-ai/dsh-invariants'
@@ -25,6 +25,9 @@ export interface TestInvariantCompanion {
apply(ctx: Context): Promise<() => void>
}
/** Private service dependency that holds ordinary root plugins until invariant startup completes. */
export const TEST_INVARIANT_READY_SERVICE = 'testInvariantReady'
/**
* Every package companion as a lazy loader keyed by glob path. Ordinary tests
* load only their owner's module; the exhaustive topology test loads and
@@ -43,10 +46,12 @@ const MANUAL_INVARIANT_TEST_EXCEPTIONS = [
interface InvariantHost {
readonly byCallback: ReadonlyMap<unknown, PluginFiber>
readonly barrierOwners: WeakSet<Context['fiber']>
readonly ready: Promise<void>
}
type PluginFiber = ReturnType<RegistryService['plugin']>
type PluginCallback = Plugin.Function | Plugin.Constructor
const hosts = new WeakMap<Context, InvariantHost>()
// oxlint-disable-next-line typescript/unbound-method -- every call below supplies its RegistryService receiver explicitly.
@@ -61,13 +66,24 @@ RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, ge
const callback = this.resolve(plugin)
const existing = callback === undefined ? undefined : host.byCallback.get(callback)
if (existing !== undefined) {
return this.ctx === root ? joinInvariantStartup(existing, host.ready) : existing
return hasBarrierOwner(host, this.ctx) ? existing : joinInvariantStartup(existing, host.ready)
}
const fiber = originalPlugin.call(this, plugin, config, getOuterStack)
// A root-level await is the test's composition boundary. Nested plugin
// fibers must not await their own companion parent through the global host.
if (this.ctx !== root) return fiber
// Causal descendants of a gated target have already crossed the barrier.
// Host service and companion descendants also bypass it so their own startup
// cannot depend on the readiness they are responsible for providing.
if (hasBarrierOwner(host, this.ctx)) {
return originalPlugin.call(this, plugin, config, getOuterStack)
}
if (callback === undefined) return originalPlugin.call(this, plugin, config, getOuterStack)
const fiber = originalPlugin.call(
this,
withInvariantReadiness(plugin, callback as PluginCallback),
config,
getOuterStack,
)
host.barrierOwners.add(fiber.ctx.fiber)
return joinInvariantStartup(fiber, host.ready)
}
@@ -108,11 +124,13 @@ export function testInvariantCompanionPaths(testPath: string): string[] {
function startInvariantHost(root: Context): InvariantHost {
const byCallback = new Map<unknown, PluginFiber>()
const barrierOwners = new WeakSet<Context['fiber']>()
const mount = (plugin: Plugin, config?: unknown): PluginFiber => {
const fiber = originalPlugin.call(root.registry, plugin, config)
const callback = root.registry.resolve(plugin)
if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
byCallback.set(callback, fiber)
barrierOwners.add(fiber.ctx.fiber)
return fiber
}
@@ -126,8 +144,8 @@ function startInvariantHost(root: Context): InvariantHost {
const serviceFiber = mount(InvariantService, { enabled: true })
const testPath = expect.getState().testPath ?? ''
const companionPaths = testInvariantCompanionPaths(testPath)
const ready = serviceFiber.await().then(async () => {
const companionFibers = await Promise.all(companionPaths.map(async (path) => {
const ready = requireActive(serviceFiber, 'invariant service').then(async () => {
const companions = await Promise.all(companionPaths.map(async (path) => {
const load = testInvariantCompanions[path]
if (load === undefined) {
throw new Error(`test invariants: selected companion vanished at ${path}`)
@@ -136,20 +154,58 @@ function startInvariantHost(root: Context): InvariantHost {
if (!companion.inject.includes('invariants')) {
throw new Error(`test invariants: ${path} must inject the invariant service`)
}
return mount(companion)
return { companion, path }
}))
await Promise.all(companionFibers.map(fiber => fiber.await()))
const companionFibers = companions.map(({ companion, path }) => ({
fiber: mount(companion),
path,
}))
await Promise.all(companionFibers.map(({ fiber, path }) => requireActive(fiber, path)))
root.provide(TEST_INVARIANT_READY_SERVICE, true)
})
const host = { byCallback, ready }
const host = { byCallback, barrierOwners, ready }
hosts.set(root, host)
return host
}
function hasBarrierOwner(host: InvariantHost, ctx: Context): boolean {
let fiber = ctx.fiber
while (true) {
if (
host.barrierOwners.has(fiber)
&& (fiber.state === FiberState.LOADING || fiber.state === FiberState.ACTIVE)
) {
return true
}
const parent = fiber.parent.fiber
if (parent === fiber) return false
fiber = parent
}
}
async function requireActive(fiber: PluginFiber, label: string): Promise<void> {
await fiber.await()
if (fiber.state !== FiberState.ACTIVE) {
throw new Error(`test invariants: ${label} settled without becoming active`)
}
}
function withInvariantReadiness(plugin: Plugin, callback: PluginCallback): Plugin.Object {
return {
apply: callback as Plugin.Function,
inject: {
...Inject.resolve(plugin.inject),
[TEST_INVARIANT_READY_SERVICE]: null,
},
...(plugin.name === undefined ? {} : { name: plugin.name }),
...(plugin.Config === undefined ? {} : { Config: plugin.Config }),
...(plugin.provide === undefined ? {} : { provide: plugin.provide }),
...(plugin.intercept === undefined ? {} : { intercept: plugin.intercept }),
}
}
function joinInvariantStartup(fiber: PluginFiber, invariantReady: Promise<void>): PluginFiber {
const readiness = fiber.await().then(async (loaded) => {
await invariantReady
return loaded
})
const readiness = invariantReady.then(() => fiber.await())
const joined = Object.create(fiber) as PluginFiber
joined.then = readiness.then.bind(readiness)
return joined