test-invariants.spec.ts 17 KB

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