test-invariants.ts 11 KB

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