test-invariants.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context, FiberState, Service, ValidationError } from '@deepseek-ai/cordis'
  3. import Loader from '@deepseek-ai/cordis-plugin-loader'
  4. import z from '@deepseek-ai/schemastery'
  5. import InvariantRegistry from '@deepseek-ai/dsh-invariants'
  6. import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
  7. import { packageInvariantOwners } from './package-invariants.ts'
  8. import {
  9. TEST_INVARIANT_READY_SERVICE,
  10. testInvariantCompanionPaths,
  11. testInvariantCompanions,
  12. type TestInvariantCompanion,
  13. usesManualInvariantTree,
  14. } from './test-invariants.ts'
  15. declare module '@deepseek-ai/cordis' {
  16. interface Context {
  17. testInvariantProbe: TestInvariantProbe
  18. }
  19. }
  20. class TestInvariantProbe extends Service {
  21. constructor(ctx: Context) {
  22. super(ctx, 'testInvariantProbe')
  23. }
  24. }
  25. function deferred(): { readonly promise: Promise<void>; readonly resolve: () => void } {
  26. let resolve!: () => void
  27. const promise = new Promise<void>((done) => {
  28. resolve = done
  29. })
  30. return { promise, resolve }
  31. }
  32. function requiredConfig() {
  33. return z.object({
  34. requiredValue: z.string().required(),
  35. })
  36. }
  37. function invalidConfigApply(): never {
  38. throw new Error('invalid plugin apply executed')
  39. }
  40. async function rejectionOf(fiber: ReturnType<Context['plugin']>): Promise<unknown> {
  41. return fiber.then(
  42. () => undefined,
  43. (error: unknown) => error,
  44. )
  45. }
  46. function expectRequiredConfigValidation(error: unknown): void {
  47. expect(error).toBeInstanceOf(ValidationError)
  48. expect(error).toHaveProperty('message', expect.stringMatching(/requiredValue/))
  49. }
  50. async function withFakeCompanions(
  51. create: (path: string, index: number) => () => Promise<TestInvariantCompanion>,
  52. run: () => Promise<void>,
  53. ): Promise<void> {
  54. const mutable = testInvariantCompanions as Record<string, () => Promise<TestInvariantCompanion>>
  55. const originals = Object.entries(mutable)
  56. for (const [index, [path]] of originals.entries()) {
  57. mutable[path] = create(path, index)
  58. }
  59. try {
  60. await run()
  61. } finally {
  62. for (const [path, load] of originals) {
  63. mutable[path] = load
  64. }
  65. }
  66. }
  67. async function withDelayedFirstCompanion(
  68. run: (control: { readonly started: Promise<void>; readonly release: () => void }) => Promise<void>,
  69. ): Promise<void> {
  70. const started = deferred()
  71. const release = deferred()
  72. await withFakeCompanions(
  73. (_path, index) => async () => ({
  74. name: `test-invariant-${index}`,
  75. inject: ['invariants'],
  76. async apply() {
  77. if (index === 0) {
  78. started.resolve()
  79. await release.promise
  80. }
  81. return () => {}
  82. },
  83. }),
  84. () => run({ started: started.promise, release: release.resolve }),
  85. )
  86. }
  87. describe('global test invariant host', () => {
  88. it('uses one exhaustive topology to reserve every package name with enabled checks', async () => {
  89. const ctx = new Context()
  90. await ctx.plugin(TestInvariantProbe)
  91. const owners = packageInvariantOwners(process.cwd())
  92. expect(Object.keys(testInvariantCompanions)).toHaveLength(owners.length)
  93. const unreserved: string[] = []
  94. for (const owner of owners) {
  95. try {
  96. const dispose = ctx.invariants.register(owner.packageName, () => {})
  97. unreserved.push(owner.packageName)
  98. dispose()
  99. } catch (error) {
  100. expect(error).toHaveProperty(
  101. 'message',
  102. `invariants: package "${owner.packageName}" is already registered`,
  103. )
  104. }
  105. }
  106. expect(unreserved).toEqual([])
  107. })
  108. it('mounts the owning package companion while leaving non-package roots service-only', () => {
  109. expect(testInvariantCompanionPaths('/repo/packages/core/tools/tests/tools.spec.ts'))
  110. .toEqual(['../packages/core/tools/src/invariant.ts'])
  111. expect(testInvariantCompanionPaths('/repo/apps/cli/tests/profiles/headless/example.spec.ts')).toEqual([])
  112. expect(testInvariantCompanionPaths('/repo/scripts/test-invariants.spec.ts'))
  113. .toEqual(Object.keys(testInvariantCompanions).sort())
  114. })
  115. it('loads and executes every source companion through the real Loader setup', async () => {
  116. const owners = new Map(packageInvariantOwners(process.cwd()).map(owner => [owner.sourcePath, owner.packageName]))
  117. const registrations = new Map<string, string>()
  118. const loader = Object.create(Loader.prototype) as Loader
  119. const register = vi.fn((_packageName: string, installer: InvariantInstaller) => {
  120. expect(typeof installer).toBe('function')
  121. return () => {}
  122. })
  123. const fakeContext = { invariants: { register } } as unknown as Context
  124. for (const [rawPath, load] of Object.entries(testInvariantCompanions)) {
  125. const companion = await load()
  126. const path = rawPath.replace(/^\.\.\//, '')
  127. expect(companion.default, path).toBeUndefined()
  128. const unwrapped = loader.unwrapExports(companion) as typeof companion
  129. expect(unwrapped, path).toBe(companion)
  130. expect(typeof unwrapped.name, path).toBe('string')
  131. expect(unwrapped.inject, path).toContain('invariants')
  132. expect(typeof unwrapped.apply, path).toBe('function')
  133. await unwrapped.apply(fakeContext)
  134. const call = register.mock.calls.at(-1)
  135. if (call === undefined) throw new Error(`${path}: companion did not register`)
  136. registrations.set(path, call[0])
  137. }
  138. expect(registrations).toEqual(owners)
  139. })
  140. it('recognizes focused invariant suites without a package inventory', () => {
  141. expect(usesManualInvariantTree('/repo/packages/core/session/tests/invariant.spec.ts')).toBe(true)
  142. expect(usesManualInvariantTree('/repo/packages/core/session/tests/request-invariant-hmr.spec.ts')).toBe(true)
  143. expect(usesManualInvariantTree('C:\\repo\\packages\\runtime-diagnostics\\invariants\\tests\\service.spec.ts')).toBe(true)
  144. expect(usesManualInvariantTree('/repo/packages/core/session/tests/session.spec.ts')).toBe(false)
  145. })
  146. it('preserves config validation failures without starting the rejected plugin', async () => {
  147. const ctx = new Context()
  148. const apply = vi.fn(invalidConfigApply)
  149. const plugin = {
  150. apply,
  151. Config: requiredConfig(),
  152. }
  153. const fiber = ctx.plugin(plugin, {})
  154. const firstError = await rejectionOf(fiber)
  155. expectRequiredConfigValidation(firstError)
  156. await ctx.plugin(TestInvariantProbe)
  157. const secondError = await rejectionOf(fiber)
  158. expect(secondError).toBe(firstError)
  159. expect(fiber.state).toBe(FiberState.DISPOSED)
  160. expect(apply).not.toHaveBeenCalled()
  161. })
  162. it('disposes invalid config after delayed invariant readiness', async () => {
  163. await withDelayedFirstCompanion(
  164. async ({ started, release }) => {
  165. const ctx = new Context()
  166. const apply = vi.fn(invalidConfigApply)
  167. const plugin = {
  168. apply,
  169. Config: requiredConfig(),
  170. }
  171. const fiber = ctx.plugin(plugin, {})
  172. const returnedError = rejectionOf(fiber)
  173. await started
  174. expect(fiber.state).toBe(FiberState.PENDING)
  175. expect(apply).not.toHaveBeenCalled()
  176. release()
  177. expectRequiredConfigValidation(await returnedError)
  178. expect(fiber.state).toBe(FiberState.DISPOSED)
  179. expect(apply).not.toHaveBeenCalled()
  180. },
  181. )
  182. })
  183. it('retains a valid plugin failure after delayed invariant readiness', async () => {
  184. await withDelayedFirstCompanion(
  185. async ({ started, release }) => {
  186. const ctx = new Context()
  187. const failure = new Error('valid plugin apply failed')
  188. const apply = vi.fn(function validConfigApply() {
  189. throw failure
  190. })
  191. const plugin = {
  192. apply,
  193. Config: z.object({}),
  194. }
  195. const fiber = ctx.plugin(plugin, {})
  196. const returnedError = rejectionOf(fiber)
  197. await started
  198. expect(fiber.state).toBe(FiberState.PENDING)
  199. expect(apply).not.toHaveBeenCalled()
  200. release()
  201. expect(await returnedError).toBe(failure)
  202. expect(fiber.state).toBe(FiberState.FAILED)
  203. expect(apply).toHaveBeenCalledOnce()
  204. expect(ctx.registry.has(plugin)).toBe(true)
  205. expect(ctx.registry.get(plugin)?.fibers).toHaveLength(1)
  206. },
  207. )
  208. })
  209. it('holds a root plugin until every lazy companion is active, then permits nested startup', async () => {
  210. const delayedStarted = deferred()
  211. const releaseDelayed = deferred()
  212. const order: string[] = []
  213. let delayedCompanion: TestInvariantCompanion | undefined
  214. const companionNestedApply = vi.fn(function companionNestedApply() {})
  215. await withFakeCompanions(
  216. (path, index) => async () => {
  217. const companion: TestInvariantCompanion = {
  218. name: `test-invariant-${index}`,
  219. inject: ['invariants'],
  220. async apply(companionCtx) {
  221. order.push(`companion-start:${path}`)
  222. if (index === 0) {
  223. delayedStarted.resolve()
  224. await releaseDelayed.promise
  225. }
  226. if (index === 1) await companionCtx.plugin(companionNestedApply)
  227. order.push(`companion-active:${path}`)
  228. return () => {}
  229. },
  230. }
  231. if (index === 0) delayedCompanion = companion
  232. return companion
  233. },
  234. async () => {
  235. const ctx = new Context()
  236. ctx.provide('testInvariantTargetDependency', true)
  237. let nestedFiber: ReturnType<Context['plugin']> | undefined
  238. const nestedApply = vi.fn(function nestedApply() {
  239. order.push('nested')
  240. })
  241. const targetApply = Object.assign(vi.fn(function targetApply(targetCtx: Context) {
  242. order.push('target')
  243. nestedFiber = targetCtx.plugin(nestedApply)
  244. }), {
  245. inject: ['testInvariantTargetDependency'],
  246. })
  247. const targetFiber = ctx.plugin(targetApply)
  248. expect(ctx.registry.get(targetApply)?.callback).toBe(targetApply)
  249. expect(targetFiber.inject).toEqual({
  250. testInvariantTargetDependency: null,
  251. [TEST_INVARIANT_READY_SERVICE]: null,
  252. })
  253. await delayedStarted.promise
  254. await Promise.resolve()
  255. await Promise.resolve()
  256. expect(targetApply).not.toHaveBeenCalled()
  257. releaseDelayed.resolve()
  258. await targetFiber
  259. if (nestedFiber === undefined) throw new Error('target did not register its nested plugin')
  260. await nestedFiber
  261. expect(targetFiber.state).toBe(FiberState.ACTIVE)
  262. expect(targetApply).toHaveBeenCalledOnce()
  263. expect(nestedApply).toHaveBeenCalledOnce()
  264. expect(companionNestedApply).toHaveBeenCalledOnce()
  265. const targetIndex = order.indexOf('target')
  266. expect(targetIndex).toBeGreaterThan(-1)
  267. expect(order.slice(0, targetIndex)).toHaveLength(Object.keys(testInvariantCompanions).length * 2)
  268. expect(order.at(-1)).toBe('nested')
  269. if (delayedCompanion === undefined) throw new Error('delayed companion did not load')
  270. await ctx.plugin(InvariantRegistry, { enabled: true })
  271. await ctx.plugin(delayedCompanion)
  272. expect(ctx.registry.get(InvariantRegistry)?.fibers).toHaveLength(1)
  273. expect(ctx.registry.get(delayedCompanion)?.fibers).toHaveLength(1)
  274. },
  275. )
  276. })
  277. it('holds plugins registered on a root-derived context until companion readiness', async () => {
  278. await withDelayedFirstCompanion(
  279. async ({ started, release }) => {
  280. const ctx = new Context()
  281. const rootApply = vi.fn(function rootApply() {})
  282. const derivedApply = vi.fn(function derivedApply() {})
  283. const derived = ctx.extend()
  284. .isolate('testInvariantDerived')
  285. .intercept('testInvariantDerived', {})
  286. const rootFiber = ctx.plugin(rootApply)
  287. const derivedFiber = derived.plugin(derivedApply)
  288. await started
  289. await Promise.resolve()
  290. await Promise.resolve()
  291. expect(rootApply).not.toHaveBeenCalled()
  292. expect(derivedApply).not.toHaveBeenCalled()
  293. expect(derivedFiber.inject).toEqual({
  294. [TEST_INVARIANT_READY_SERVICE]: null,
  295. })
  296. release()
  297. await Promise.all([rootFiber, derivedFiber])
  298. expect(rootFiber.state).toBe(FiberState.ACTIVE)
  299. expect(derivedFiber.state).toBe(FiberState.ACTIVE)
  300. expect(rootApply).toHaveBeenCalledOnce()
  301. expect(derivedApply).toHaveBeenCalledOnce()
  302. },
  303. )
  304. })
  305. it('holds a child registered externally on a pending target context', async () => {
  306. await withDelayedFirstCompanion(
  307. async ({ started, release }) => {
  308. const ctx = new Context()
  309. const targetApply = vi.fn(function targetApply() {})
  310. const childApply = vi.fn(function childApply() {})
  311. const targetFiber = ctx.plugin(targetApply)
  312. const childFiber = targetFiber.ctx.plugin(childApply)
  313. await started
  314. await Promise.resolve()
  315. await Promise.resolve()
  316. expect(targetFiber.state).toBe(FiberState.PENDING)
  317. expect(childFiber.state).toBe(FiberState.PENDING)
  318. expect(targetApply).not.toHaveBeenCalled()
  319. expect(childApply).not.toHaveBeenCalled()
  320. expect(childFiber.inject).toEqual({
  321. [TEST_INVARIANT_READY_SERVICE]: null,
  322. })
  323. release()
  324. await Promise.all([targetFiber, childFiber])
  325. expect(targetFiber.state).toBe(FiberState.ACTIVE)
  326. expect(childFiber.state).toBe(FiberState.ACTIVE)
  327. expect(targetApply).toHaveBeenCalledOnce()
  328. expect(childApply).toHaveBeenCalledOnce()
  329. },
  330. )
  331. })
  332. it.each(['load', 'startup'] as const)(
  333. 'rejects a target when a lazy companion fails during %s without starting the target',
  334. async (phase) => {
  335. const failure = new Error(`test invariant companion ${phase} failed`)
  336. await withFakeCompanions(
  337. (_path, index) => phase === 'load' && index === 0
  338. ? async () => { throw failure }
  339. : async () => ({
  340. name: `test-invariant-${index}`,
  341. inject: ['invariants'],
  342. async apply() {
  343. if (phase === 'startup' && index === 0) throw failure
  344. return () => {}
  345. },
  346. }),
  347. async () => {
  348. const ctx = new Context()
  349. const targetApply = vi.fn(function targetApply() {})
  350. const targetFiber = ctx.plugin(targetApply)
  351. await expect(targetFiber).rejects.toBe(failure)
  352. expect(targetApply).not.toHaveBeenCalled()
  353. expect(targetFiber.state).toBe(FiberState.PENDING)
  354. await expect(targetFiber.dispose()).resolves.toBeUndefined()
  355. expect(targetFiber.state).toBe(FiberState.DISPOSED)
  356. },
  357. )
  358. },
  359. )
  360. it('disposes a pending target without waiting for companion readiness', async () => {
  361. await withDelayedFirstCompanion(
  362. async ({ started, release }) => {
  363. const ctx = new Context()
  364. const targetApply = vi.fn(function targetApply() {})
  365. const targetFiber = ctx.plugin(targetApply)
  366. await started
  367. await expect(targetFiber.dispose()).resolves.toBeUndefined()
  368. expect(targetFiber.state).toBe(FiberState.DISPOSED)
  369. expect(targetApply).not.toHaveBeenCalled()
  370. release()
  371. await targetFiber
  372. expect(targetApply).not.toHaveBeenCalled()
  373. },
  374. )
  375. })
  376. })