test-invariants.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /**
  2. * Vitest-wide invariant host. Ordinary Cordis roots receive the invariant
  3. * service with global enablement plus the current test package's companion.
  4. * One topology test mounts every companion; focused invariant tests own their
  5. * service topology explicitly.
  6. */
  7. import { expect } from 'vitest'
  8. import { FiberState, Inject, RegistryService } from 'cordis'
  9. import type { Context, Plugin } from 'cordis'
  10. import InvariantService from '@deepseek-ai/dsh-invariants'
  11. declare global {
  12. interface ImportMeta {
  13. /** Lazy Vite module-glob expansion used by the Vitest setup file. */
  14. glob<TModule>(pattern: string): Record<string, () => Promise<TModule>>
  15. }
  16. }
  17. /** Loader-safe shape shared by every package invariant companion. */
  18. export interface TestInvariantCompanion {
  19. readonly name: string
  20. readonly inject: readonly string[]
  21. readonly default?: unknown
  22. apply(ctx: Context): Promise<() => void>
  23. }
  24. /** Private service dependency that holds ordinary root plugins until invariant startup completes. */
  25. export const TEST_INVARIANT_READY_SERVICE = 'testInvariantReady'
  26. /**
  27. * Every package companion as a lazy loader keyed by glob path. Ordinary tests
  28. * load only their owner's module; the exhaustive topology test loads and
  29. * executes all of them, so aggregated coverage still observes every
  30. * registration while per-file setup stops importing 168 companions and their
  31. * transitive package sources.
  32. */
  33. export const testInvariantCompanions: Readonly<Record<string, () => Promise<TestInvariantCompanion>>> =
  34. import.meta.glob<TestInvariantCompanion>('../packages/*/*/src/invariant.ts')
  35. /** Manual-topology suites whose names cannot follow the focused invariant convention. */
  36. const MANUAL_INVARIANT_TEST_EXCEPTIONS = [
  37. '/packages/support/invariants/tests/service.spec.ts',
  38. '/packages/examples/agent-spine-demo/tests/agent-core.spec.ts',
  39. ] as const
  40. interface InvariantHost {
  41. readonly byCallback: ReadonlyMap<unknown, PluginFiber>
  42. readonly barrierOwners: WeakSet<Context['fiber']>
  43. readonly ready: Promise<void>
  44. }
  45. type PluginFiber = ReturnType<RegistryService['plugin']>
  46. type PluginCallback = Plugin.Function | Plugin.Constructor
  47. const hosts = new WeakMap<Context, InvariantHost>()
  48. // oxlint-disable-next-line typescript/unbound-method -- every call below supplies its RegistryService receiver explicitly.
  49. const originalPlugin = RegistryService.prototype.plugin
  50. RegistryService.prototype.plugin = function(plugin: Plugin, config?: unknown, getOuterStack?: () => string[]) {
  51. const testPath = expect.getState().testPath ?? ''
  52. if (usesManualInvariantTree(testPath)) return originalPlugin.call(this, plugin, config, getOuterStack)
  53. const root = this.ctx.root
  54. const host = hosts.get(root) ?? startInvariantHost(root)
  55. const callback = this.resolve(plugin)
  56. const existing = callback === undefined ? undefined : host.byCallback.get(callback)
  57. if (existing !== undefined) {
  58. return hasBarrierOwner(host, this.ctx) ? existing : joinInvariantStartup(existing, host.ready)
  59. }
  60. // Causal descendants of a gated target have already crossed the barrier.
  61. // Host service and companion descendants also bypass it so their own startup
  62. // cannot depend on the readiness they are responsible for providing.
  63. if (hasBarrierOwner(host, this.ctx)) {
  64. return originalPlugin.call(this, plugin, config, getOuterStack)
  65. }
  66. if (callback === undefined) {
  67. return originalPlugin.call(this, plugin, config, getOuterStack)
  68. }
  69. const fiber = originalPlugin.call(
  70. this,
  71. withInvariantReadiness(plugin, callback as PluginCallback),
  72. config,
  73. getOuterStack,
  74. )
  75. const initiallyPending = fiber.ctx.fiber.state === FiberState.PENDING
  76. host.barrierOwners.add(fiber.ctx.fiber)
  77. return joinInvariantStartup(fiber, host.ready, initiallyPending)
  78. }
  79. /**
  80. * Detect focused suites that construct service selection or companion lifecycle explicitly.
  81. * @param testPath - absolute or repo-relative Vitest file path.
  82. * @returns whether the global invariant host must leave the root untouched.
  83. */
  84. export function usesManualInvariantTree(testPath: string): boolean {
  85. const normalized = testPath.replaceAll('\\', '/')
  86. if (/\/packages\/[^/]+\/[^/]+\/tests\/[^/]*invariant[^/]*\.spec\.ts$/.test(normalized)) return true
  87. return MANUAL_INVARIANT_TEST_EXCEPTIONS.some(path => normalized.endsWith(path))
  88. }
  89. const ALL_COMPANION_TESTS = ['/scripts/test-invariants.spec.ts'] as const
  90. /**
  91. * Select the package companions that an ordinary test root must register.
  92. * Package tests receive their owner's checks; the dedicated topology test
  93. * receives every owner so coverage and exhaustive runtime registration remain
  94. * independently enforced.
  95. * @param testPath - absolute or repo-relative normalized Vitest file path.
  96. * @returns sorted `import.meta.glob` keys for companions to mount.
  97. */
  98. export function testInvariantCompanionPaths(testPath: string): string[] {
  99. const normalized = testPath.replaceAll('\\', '/')
  100. const allPaths = Object.keys(testInvariantCompanions).sort()
  101. if (ALL_COMPANION_TESTS.some(path => normalized.endsWith(path))) return allPaths
  102. const owner = normalized.match(/\/packages\/([^/]+)\/([^/]+)\/tests\//)
  103. if (owner === null) return []
  104. const companionPath = `../packages/${owner[1]}/${owner[2]}/src/invariant.ts`
  105. if (testInvariantCompanions[companionPath] === undefined) {
  106. throw new Error(`test invariants: package test has no companion at ${companionPath}`)
  107. }
  108. return [companionPath]
  109. }
  110. function startInvariantHost(root: Context): InvariantHost {
  111. const byCallback = new Map<unknown, PluginFiber>()
  112. const barrierOwners = new WeakSet<Context['fiber']>()
  113. const mount = (plugin: Plugin, config?: unknown): PluginFiber => {
  114. const fiber = originalPlugin.call(root.registry, plugin, config)
  115. const callback = root.registry.resolve(plugin)
  116. if (callback === undefined) throw new Error('test invariants: companion is not a valid Cordis plugin')
  117. byCallback.set(callback, fiber)
  118. barrierOwners.add(fiber.ctx.fiber)
  119. return fiber
  120. }
  121. // The service mounts synchronously so the intercepted registration that
  122. // started this host immediately finds its own fiber in byCallback.
  123. // Companions load and mount inside the ready chain (after the service is
  124. // active, so their startup is directly joinable); every joined root plugin
  125. // awaits ready, so none starts ahead of its package checks. Tests plugging
  126. // a companion directly must await an earlier root plugin first — the
  127. // duplicate-mount failure otherwise is loud (owner name already reserved).
  128. const serviceFiber = mount(InvariantService, { enabled: true })
  129. const testPath = expect.getState().testPath ?? ''
  130. const companionPaths = testInvariantCompanionPaths(testPath)
  131. const ready = requireActive(serviceFiber, 'invariant service').then(async () => {
  132. const companions = await Promise.all(companionPaths.map(async (path) => {
  133. const load = testInvariantCompanions[path]
  134. if (load === undefined) {
  135. throw new Error(`test invariants: selected companion vanished at ${path}`)
  136. }
  137. const companion = await load()
  138. if (!companion.inject.includes('invariants')) {
  139. throw new Error(`test invariants: ${path} must inject the invariant service`)
  140. }
  141. return { companion, path }
  142. }))
  143. const companionFibers = companions.map(({ companion, path }) => ({
  144. fiber: mount(companion),
  145. path,
  146. }))
  147. await Promise.all(companionFibers.map(({ fiber, path }) => requireActive(fiber, path)))
  148. root.provide(TEST_INVARIANT_READY_SERVICE, true)
  149. })
  150. const host = { byCallback, barrierOwners, ready }
  151. hosts.set(root, host)
  152. return host
  153. }
  154. function hasBarrierOwner(host: InvariantHost, ctx: Context): boolean {
  155. let fiber = ctx.fiber
  156. while (true) {
  157. if (
  158. host.barrierOwners.has(fiber)
  159. && (fiber.state === FiberState.LOADING || fiber.state === FiberState.ACTIVE)
  160. ) {
  161. return true
  162. }
  163. const parent = fiber.parent.fiber
  164. if (parent === fiber) return false
  165. fiber = parent
  166. }
  167. }
  168. async function requireActive(fiber: PluginFiber, label: string): Promise<void> {
  169. await fiber.await()
  170. if (fiber.state !== FiberState.ACTIVE) {
  171. throw new Error(`test invariants: ${label} settled without becoming active`)
  172. }
  173. }
  174. function withInvariantReadiness(plugin: Plugin, callback: PluginCallback): Plugin.Object {
  175. return {
  176. apply: callback as Plugin.Function,
  177. inject: {
  178. ...Inject.resolve(plugin.inject),
  179. [TEST_INVARIANT_READY_SERVICE]: null,
  180. },
  181. ...(plugin.name === undefined ? {} : { name: plugin.name }),
  182. ...(plugin.Config === undefined ? {} : { Config: plugin.Config }),
  183. ...(plugin.provide === undefined ? {} : { provide: plugin.provide }),
  184. ...(plugin.intercept === undefined ? {} : { intercept: plugin.intercept }),
  185. }
  186. }
  187. function joinInvariantStartup(
  188. fiber: PluginFiber,
  189. invariantReady: Promise<void>,
  190. disposeInitialFailure = false,
  191. ): PluginFiber {
  192. // RegistryService returns a thenable wrapper whose context still points to
  193. // the raw Fiber. Calling inherited await() on the wrapper would return and
  194. // assimilate that thenable, accidentally following later plugin startup.
  195. const rawFiber = fiber.ctx.fiber
  196. const initialized = disposeInitialFailure
  197. ? rawFiber.await().catch(async (error: unknown) => {
  198. // Config validation is the only failure recorded while a gated fiber
  199. // is initially PENDING. Dispose it even if queued readiness publication
  200. // changes its state before this rejection handler runs.
  201. await rawFiber.dispose()
  202. throw error
  203. })
  204. : Promise.resolve()
  205. const readiness = initialized.then(() => invariantReady).then(() => rawFiber.await())
  206. const joined = Object.create(fiber) as PluginFiber
  207. joined.then = readiness.then.bind(readiness)
  208. return joined
  209. }