test-invariants.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 topology to reserve every companion owner 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 an owning companion and leaves omitted or 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/packages/util/brand/tests/brand.spec.ts')).toEqual([])
  112. expect(testInvariantCompanionPaths('/repo/apps/cli/tests/profiles/headless/example.spec.ts')).toEqual([])
  113. expect(testInvariantCompanionPaths('/repo/scripts/test-invariants.spec.ts'))
  114. .toEqual(Object.keys(testInvariantCompanions).sort())
  115. })
  116. it('loads and executes every source companion through the real Loader setup', async () => {
  117. const owners = new Map(packageInvariantOwners(process.cwd()).map(owner => [owner.sourcePath, owner.packageName]))
  118. const registrations = new Map<string, string>()
  119. const loader = Object.create(Loader.prototype) as Loader
  120. const register = vi.fn((_packageName: string, installer: InvariantInstaller) => {
  121. expect(typeof installer).toBe('function')
  122. return () => {}
  123. })
  124. const fakeContext = { invariants: { register } } as unknown as Context
  125. for (const [rawPath, load] of Object.entries(testInvariantCompanions)) {
  126. const companion = await load()
  127. const path = rawPath.replace(/^\.\.\//, '')
  128. expect(companion.default, path).toBeUndefined()
  129. const unwrapped = loader.unwrapExports(companion) as typeof companion
  130. expect(unwrapped, path).toBe(companion)
  131. expect(typeof unwrapped.name, path).toBe('string')
  132. expect(unwrapped.inject, path).toContain('invariants')
  133. expect(typeof unwrapped.apply, path).toBe('function')
  134. await unwrapped.apply(fakeContext)
  135. const call = register.mock.calls.at(-1)
  136. if (call === undefined) throw new Error(`${path}: companion did not register`)
  137. registrations.set(path, call[0])
  138. }
  139. expect(registrations).toEqual(owners)
  140. })
  141. it('recognizes focused invariant suites without a package inventory', () => {
  142. expect(usesManualInvariantTree('/repo/packages/core/session/tests/invariant.spec.ts')).toBe(true)
  143. expect(usesManualInvariantTree('/repo/packages/core/session/tests/request-invariant-hmr.spec.ts')).toBe(true)
  144. expect(usesManualInvariantTree('C:\\repo\\packages\\runtime-diagnostics\\invariants\\tests\\service.spec.ts')).toBe(true)
  145. expect(usesManualInvariantTree('/repo/packages/core/session/tests/session.spec.ts')).toBe(false)
  146. })
  147. it('preserves config validation failures without starting the rejected plugin', async () => {
  148. const ctx = new Context()
  149. const apply = vi.fn(invalidConfigApply)
  150. const plugin = {
  151. apply,
  152. Config: requiredConfig(),
  153. }
  154. const fiber = ctx.plugin(plugin, {})
  155. const firstError = await rejectionOf(fiber)
  156. expectRequiredConfigValidation(firstError)
  157. await ctx.plugin(TestInvariantProbe)
  158. const secondError = await rejectionOf(fiber)
  159. expect(secondError).toBe(firstError)
  160. expect(fiber.state).toBe(FiberState.DISPOSED)
  161. expect(apply).not.toHaveBeenCalled()
  162. })
  163. it('disposes invalid config after delayed invariant readiness', async () => {
  164. await withDelayedFirstCompanion(
  165. async ({ started, release }) => {
  166. const ctx = new Context()
  167. const apply = vi.fn(invalidConfigApply)
  168. const plugin = {
  169. apply,
  170. Config: requiredConfig(),
  171. }
  172. const fiber = ctx.plugin(plugin, {})
  173. const returnedError = rejectionOf(fiber)
  174. await started
  175. expect(fiber.state).toBe(FiberState.PENDING)
  176. expect(apply).not.toHaveBeenCalled()
  177. release()
  178. expectRequiredConfigValidation(await returnedError)
  179. expect(fiber.state).toBe(FiberState.DISPOSED)
  180. expect(apply).not.toHaveBeenCalled()
  181. },
  182. )
  183. })
  184. it('retains a valid plugin failure after delayed invariant readiness', async () => {
  185. await withDelayedFirstCompanion(
  186. async ({ started, release }) => {
  187. const ctx = new Context()
  188. const failure = new Error('valid plugin apply failed')
  189. const apply = vi.fn(function validConfigApply() {
  190. throw failure
  191. })
  192. const plugin = {
  193. apply,
  194. Config: z.object({}),
  195. }
  196. const fiber = ctx.plugin(plugin, {})
  197. const returnedError = rejectionOf(fiber)
  198. await started
  199. expect(fiber.state).toBe(FiberState.PENDING)
  200. expect(apply).not.toHaveBeenCalled()
  201. release()
  202. expect(await returnedError).toBe(failure)
  203. expect(fiber.state).toBe(FiberState.FAILED)
  204. expect(apply).toHaveBeenCalledOnce()
  205. expect(ctx.registry.has(plugin)).toBe(true)
  206. expect(ctx.registry.get(plugin)?.fibers).toHaveLength(1)
  207. },
  208. )
  209. })
  210. it('holds a root plugin until every lazy companion is active, then permits nested startup', async () => {
  211. const delayedStarted = deferred()
  212. const releaseDelayed = deferred()
  213. const order: string[] = []
  214. let delayedCompanion: TestInvariantCompanion | undefined
  215. const companionNestedApply = vi.fn(function companionNestedApply() {})
  216. await withFakeCompanions(
  217. (path, index) => async () => {
  218. const companion: TestInvariantCompanion = {
  219. name: `test-invariant-${index}`,
  220. inject: ['invariants'],
  221. async apply(companionCtx) {
  222. order.push(`companion-start:${path}`)
  223. if (index === 0) {
  224. delayedStarted.resolve()
  225. await releaseDelayed.promise
  226. }
  227. if (index === 1) await companionCtx.plugin(companionNestedApply)
  228. order.push(`companion-active:${path}`)
  229. return () => {}
  230. },
  231. }
  232. if (index === 0) delayedCompanion = companion
  233. return companion
  234. },
  235. async () => {
  236. const ctx = new Context()
  237. ctx.provide('testInvariantTargetDependency', true)
  238. let nestedFiber: ReturnType<Context['plugin']> | undefined
  239. const nestedApply = vi.fn(function nestedApply() {
  240. order.push('nested')
  241. })
  242. const targetApply = Object.assign(vi.fn(function targetApply(targetCtx: Context) {
  243. order.push('target')
  244. nestedFiber = targetCtx.plugin(nestedApply)
  245. }), {
  246. inject: ['testInvariantTargetDependency'],
  247. })
  248. const targetFiber = ctx.plugin(targetApply)
  249. expect(ctx.registry.get(targetApply)?.callback).toBe(targetApply)
  250. expect(targetFiber.inject).toEqual({
  251. testInvariantTargetDependency: null,
  252. [TEST_INVARIANT_READY_SERVICE]: null,
  253. })
  254. await delayedStarted.promise
  255. await Promise.resolve()
  256. await Promise.resolve()
  257. expect(targetApply).not.toHaveBeenCalled()
  258. releaseDelayed.resolve()
  259. await targetFiber
  260. if (nestedFiber === undefined) throw new Error('target did not register its nested plugin')
  261. await nestedFiber
  262. expect(targetFiber.state).toBe(FiberState.ACTIVE)
  263. expect(targetApply).toHaveBeenCalledOnce()
  264. expect(nestedApply).toHaveBeenCalledOnce()
  265. expect(companionNestedApply).toHaveBeenCalledOnce()
  266. const targetIndex = order.indexOf('target')
  267. expect(targetIndex).toBeGreaterThan(-1)
  268. expect(order.slice(0, targetIndex)).toHaveLength(Object.keys(testInvariantCompanions).length * 2)
  269. expect(order.at(-1)).toBe('nested')
  270. if (delayedCompanion === undefined) throw new Error('delayed companion did not load')
  271. await ctx.plugin(InvariantRegistry, { enabled: true })
  272. await ctx.plugin(delayedCompanion)
  273. expect(ctx.registry.get(InvariantRegistry)?.fibers).toHaveLength(1)
  274. expect(ctx.registry.get(delayedCompanion)?.fibers).toHaveLength(1)
  275. },
  276. )
  277. })
  278. it('holds plugins registered on a root-derived context until companion readiness', async () => {
  279. await withDelayedFirstCompanion(
  280. async ({ started, release }) => {
  281. const ctx = new Context()
  282. const rootApply = vi.fn(function rootApply() {})
  283. const derivedApply = vi.fn(function derivedApply() {})
  284. const derived = ctx.extend()
  285. .isolate('testInvariantDerived')
  286. .intercept('testInvariantDerived', {})
  287. const rootFiber = ctx.plugin(rootApply)
  288. const derivedFiber = derived.plugin(derivedApply)
  289. await started
  290. await Promise.resolve()
  291. await Promise.resolve()
  292. expect(rootApply).not.toHaveBeenCalled()
  293. expect(derivedApply).not.toHaveBeenCalled()
  294. expect(derivedFiber.inject).toEqual({
  295. [TEST_INVARIANT_READY_SERVICE]: null,
  296. })
  297. release()
  298. await Promise.all([rootFiber, derivedFiber])
  299. expect(rootFiber.state).toBe(FiberState.ACTIVE)
  300. expect(derivedFiber.state).toBe(FiberState.ACTIVE)
  301. expect(rootApply).toHaveBeenCalledOnce()
  302. expect(derivedApply).toHaveBeenCalledOnce()
  303. },
  304. )
  305. })
  306. it('holds a child registered externally on a pending target context', async () => {
  307. await withDelayedFirstCompanion(
  308. async ({ started, release }) => {
  309. const ctx = new Context()
  310. const targetApply = vi.fn(function targetApply() {})
  311. const childApply = vi.fn(function childApply() {})
  312. const targetFiber = ctx.plugin(targetApply)
  313. const childFiber = targetFiber.ctx.plugin(childApply)
  314. await started
  315. await Promise.resolve()
  316. await Promise.resolve()
  317. expect(targetFiber.state).toBe(FiberState.PENDING)
  318. expect(childFiber.state).toBe(FiberState.PENDING)
  319. expect(targetApply).not.toHaveBeenCalled()
  320. expect(childApply).not.toHaveBeenCalled()
  321. expect(childFiber.inject).toEqual({
  322. [TEST_INVARIANT_READY_SERVICE]: null,
  323. })
  324. release()
  325. await Promise.all([targetFiber, childFiber])
  326. expect(targetFiber.state).toBe(FiberState.ACTIVE)
  327. expect(childFiber.state).toBe(FiberState.ACTIVE)
  328. expect(targetApply).toHaveBeenCalledOnce()
  329. expect(childApply).toHaveBeenCalledOnce()
  330. },
  331. )
  332. })
  333. it.each(['load', 'startup'] as const)(
  334. 'rejects a target when a lazy companion fails during %s without starting the target',
  335. async (phase) => {
  336. const failure = new Error(`test invariant companion ${phase} failed`)
  337. await withFakeCompanions(
  338. (_path, index) => phase === 'load' && index === 0
  339. ? async () => { throw failure }
  340. : async () => ({
  341. name: `test-invariant-${index}`,
  342. inject: ['invariants'],
  343. async apply() {
  344. if (phase === 'startup' && index === 0) throw failure
  345. return () => {}
  346. },
  347. }),
  348. async () => {
  349. const ctx = new Context()
  350. const targetApply = vi.fn(function targetApply() {})
  351. const targetFiber = ctx.plugin(targetApply)
  352. await expect(targetFiber).rejects.toBe(failure)
  353. expect(targetApply).not.toHaveBeenCalled()
  354. expect(targetFiber.state).toBe(FiberState.PENDING)
  355. await expect(targetFiber.dispose()).resolves.toBeUndefined()
  356. expect(targetFiber.state).toBe(FiberState.DISPOSED)
  357. },
  358. )
  359. },
  360. )
  361. it('disposes a pending target without waiting for companion readiness', async () => {
  362. await withDelayedFirstCompanion(
  363. async ({ started, release }) => {
  364. const ctx = new Context()
  365. const targetApply = vi.fn(function targetApply() {})
  366. const targetFiber = ctx.plugin(targetApply)
  367. await started
  368. await expect(targetFiber.dispose()).resolves.toBeUndefined()
  369. expect(targetFiber.state).toBe(FiberState.DISPOSED)
  370. expect(targetApply).not.toHaveBeenCalled()
  371. release()
  372. await targetFiber
  373. expect(targetApply).not.toHaveBeenCalled()
  374. },
  375. )
  376. })
  377. })