invariant.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { createScope, scopeTarget } from '@deepseek-ai/dsh-scope'
  4. import { createUserMessage, CallId, createMessage, createToolResultMessage, freezeMessage } from '@deepseek-ai/dsh-llm'
  5. import SessionStore, { SessionId, TOOL_NOT_STARTED } from '@deepseek-ai/dsh-session'
  6. import * as SessionInvariant from '@deepseek-ai/dsh-session/invariant'
  7. import InvariantService, { InvariantError } from '@deepseek-ai/dsh-invariants'
  8. async function setup(): Promise<{ ctx: Context; fiber: Awaited<ReturnType<Context['plugin']>> }> {
  9. const ctx = new Context()
  10. await ctx.plugin(SessionStore)
  11. await ctx.plugin(InvariantService)
  12. const fiber = await ctx.plugin(SessionInvariant)
  13. return { ctx, fiber }
  14. }
  15. describe('session-log invariants', () => {
  16. it('keeps registration global when the companion is mounted under a scope', async () => {
  17. const ctx = new Context()
  18. await ctx.plugin(SessionStore)
  19. await ctx.plugin(InvariantService)
  20. let scopedCtx!: Context
  21. await ctx.plugin(Object.assign((inner: Context) => {
  22. scopedCtx = createScope(inner, {}).ctx
  23. }, { inject: ['sessions', 'invariants'] }))
  24. await scopedCtx.plugin(SessionInvariant)
  25. const session = ctx.sessions.create(SessionId('global-under-scoped-invariants'))
  26. expect(() => {
  27. session.append('turn/start', { turn: 1 })
  28. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  29. }).not.toThrow()
  30. })
  31. it('accepts a well-formed turn, step, and tool sequence', async () => {
  32. const { ctx } = await setup()
  33. const session = ctx.sessions.create()
  34. expect(() => {
  35. session.append('turn/start', { turn: 1 })
  36. session.append('user/message', createUserMessage({
  37. content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' },
  38. }), { surfaceOp: 'append' })
  39. session.append('step/start', { turn: 1, step: 1 })
  40. session.append('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'h' } })
  41. session.append('assistant/message', {
  42. turn: 1,
  43. step: 1,
  44. message: createMessage({
  45. role: 'assistant',
  46. content: [{ type: 'tool-call', id: CallId('c1'), name: 'echo', arguments: '{}' }],
  47. source: {
  48. kind: 'model',
  49. ...{ provider: 'mock', model: 'mock' },
  50. },
  51. }),
  52. }, { surfaceOp: 'append' })
  53. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'echo', arguments: '{}' })
  54. session.append('tool/result', {
  55. turn: 1, step: 1,
  56. message: createToolResultMessage({
  57. callId: CallId('c1'),
  58. content: [],
  59. isError: false,
  60. }),
  61. }, { surfaceOp: 'append' })
  62. session.append('step/end', { turn: 1, step: 1 })
  63. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  64. }).not.toThrow()
  65. })
  66. it('does not advance committed trace state when a later dispatch listener vetoes', async () => {
  67. const { ctx } = await setup()
  68. const session = ctx.sessions.create(SessionId('dispatch-veto-rollback'))
  69. let veto = true
  70. ctx.on('internal/dispatch', (_mode, name) => {
  71. if (name !== 'session/event' || !veto) return
  72. veto = false
  73. throw new Error('later dispatch veto')
  74. })
  75. expect(() => session.append('turn/start', {
  76. turn: 1,
  77. })).toThrow('later dispatch veto')
  78. expect(session.events).toEqual([])
  79. expect(() => {
  80. session.append('turn/start', { turn: 1 })
  81. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  82. }).not.toThrow()
  83. })
  84. it('applies the committed transition after another postcommit observer throws', async () => {
  85. const { ctx } = await setup()
  86. const warnings: string[] = []
  87. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  88. const session = ctx.sessions.create(SessionId('postcommit-peer'))
  89. ctx.on('session/event', () => { throw new Error('hostile observer') }, { prepend: true })
  90. expect(() => {
  91. session.append('turn/start', { turn: 1 })
  92. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  93. }).not.toThrow()
  94. expect(warnings).toHaveLength(2)
  95. })
  96. it('rejects non-monotonic event sequence numbers', async () => {
  97. const { ctx } = await setup()
  98. const session = ctx.sessions.create()
  99. ctx.emit(scopeTarget(session, undefined), 'session/event', session, {
  100. type: 'turn/start',
  101. seq: 0,
  102. time: 1,
  103. data: { turn: 1 },
  104. } as never)
  105. expect(() => { ctx.emit(scopeTarget(session, undefined), 'session/event', session, {
  106. type: 'turn/end',
  107. seq: 0,
  108. time: 2,
  109. data: { turn: 1, reason: { kind: 'completed' } },
  110. } as never) }).toThrow(/seq must strictly increase/)
  111. })
  112. it('enforces turn numbering and core execution enclosure', async () => {
  113. const first = await setup()
  114. const open = first.ctx.sessions.create()
  115. open.append('turn/start', { turn: 1 })
  116. expect(() => open.append('turn/start', { turn: 2 }))
  117. .toThrow(/turn 1 is still open/)
  118. expect(() => open.append('turn/end', { turn: 2, reason: { kind: 'completed' } }))
  119. .toThrow(/does not match open turn 1/)
  120. const second = (await setup()).ctx.sessions.create()
  121. second.append('turn/start', { turn: 1 })
  122. second.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  123. expect(() => second.append('turn/start', { turn: 3 }))
  124. .toThrow(/expected turn 2, got 3/)
  125. const third = (await setup()).ctx.sessions.create()
  126. third.append('turn/start', { turn: 1 })
  127. third.append('step/start', { turn: 1, step: 1 })
  128. third.append('step/end', { turn: 1, step: 1 })
  129. expect(() => third.append('turn/end', { turn: 1, reason: { kind: 'completed' } }))
  130. .not.toThrow()
  131. const enclosed = (await setup()).ctx.sessions.create()
  132. enclosed.append('turn/start', { turn: 1 })
  133. enclosed.append('step/start', { turn: 1, step: 1 })
  134. expect(() => enclosed.append('todo/write', { todos: [] })).not.toThrow()
  135. expect(() => enclosed.append('request/header', {
  136. header: { config: { provider: 'mock', model: 'mock' } },
  137. reason: 'initial',
  138. } as never)).not.toThrow()
  139. expect(() => enclosed.append('request/context', {
  140. provider: 'mock', model: 'mock',
  141. })).not.toThrow()
  142. const outside = (await setup()).ctx.sessions.create()
  143. expect(() => outside.append('user/message', createUserMessage({
  144. content: [{ type: 'text', text: 'idle context' }],
  145. source: { kind: 'plugin', plugin: 'test' },
  146. }), { surfaceOp: 'append' })).not.toThrow()
  147. // Route capacity is core execution state like the header beside it.
  148. expect(() => outside.append('request/context', {
  149. provider: 'mock',
  150. model: 'm',
  151. contextWindow: 128_000,
  152. })).toThrow(/outside any open turn/)
  153. // The owning plugin decides whether a merge-extensible event is log-only.
  154. const appendUnknown = outside.append.bind(outside) as (type: string, data: unknown) => unknown
  155. expect(() => { appendUnknown('plugin/marker', {}) }).not.toThrow()
  156. expect(() => outside.append('turn/start', {
  157. turn: 1,
  158. })).not.toThrow()
  159. })
  160. it('enforces open-step identity and numbering', async () => {
  161. const wrongTurn = (await setup()).ctx.sessions.create()
  162. wrongTurn.append('turn/start', { turn: 1 })
  163. expect(() => wrongTurn.append('step/start', { turn: 2, step: 1 })).toThrow(/open turn is 1/)
  164. const nested = (await setup()).ctx.sessions.create()
  165. nested.append('turn/start', { turn: 1 })
  166. nested.append('step/start', { turn: 1, step: 1 })
  167. expect(() => nested.append('step/start', { turn: 1, step: 2 })).toThrow(/while step 1 is still open/)
  168. expect(() => nested.append('turn/end', { turn: 1, reason: { kind: 'completed' } }))
  169. .toThrow(/while step 1 is still open/)
  170. expect(() => nested.append('step/end', { turn: 1, step: 2 })).toThrow(/open is turn 1\/step 1/)
  171. expect(() => nested.append('assistant/message', {
  172. turn: 1,
  173. step: 2,
  174. message: createMessage({
  175. role: 'assistant',
  176. content: [],
  177. source: {
  178. kind: 'model',
  179. ...{ provider: 'mock', model: 'mock' },
  180. },
  181. }),
  182. }, { surfaceOp: 'append' })).toThrow(/open is turn 1\/step 1/)
  183. const skipped = (await setup()).ctx.sessions.create()
  184. skipped.append('turn/start', { turn: 1 })
  185. skipped.append('step/start', { turn: 1, step: 1 })
  186. skipped.append('step/end', { turn: 1, step: 1 })
  187. expect(() => skipped.append('step/start', { turn: 1, step: 3 }))
  188. .toThrow(/expected step 2 in turn 1, got 3/)
  189. expect(() => skipped.append('turn/end', {
  190. turn: 1,
  191. reason: { kind: 'completed' },
  192. })).not.toThrow()
  193. })
  194. it('requires step-scoped stream and tool events to name the open step', async () => {
  195. const chunk = (await setup()).ctx.sessions.create()
  196. chunk.append('turn/start', { turn: 1 })
  197. expect(() => chunk.append('assistant/chunk', {
  198. turn: 1,
  199. step: 1,
  200. chunk: { type: 'text-delta', index: 0, text: 'x' },
  201. })).toThrow(/open is turn 1\/step null/)
  202. const tool = (await setup()).ctx.sessions.create()
  203. tool.append('turn/start', { turn: 1 })
  204. tool.append('step/start', { turn: 1, step: 1 })
  205. expect(() => tool.append('tool/result', {
  206. turn: 1,
  207. step: 1,
  208. message: createToolResultMessage({
  209. callId: CallId('ghost'),
  210. content: [],
  211. isError: false,
  212. }),
  213. }, { surfaceOp: 'append' })).toThrow(/no prior tool\/call/)
  214. })
  215. it('keeps fresh tool-result appends open-step checked', async () => {
  216. const { ctx } = await setup()
  217. const session = ctx.sessions.create()
  218. session.append('turn/start', { turn: 1 })
  219. expect(() => session.append('tool/result', {
  220. turn: 1,
  221. step: 1,
  222. message: createToolResultMessage({
  223. callId: CallId('closed'),
  224. content: [],
  225. isError: false,
  226. }),
  227. }, { surfaceOp: 'append' })).toThrow(/open is turn 1\/step null/)
  228. })
  229. it('treats a validated tool-result replacement as a turn-enclosed rewrite', async () => {
  230. const { ctx } = await setup()
  231. const session = ctx.sessions.create()
  232. session.append('turn/start', { turn: 1 })
  233. session.append('step/start', { turn: 1, step: 1 })
  234. session.append('tool/call', {
  235. turn: 1,
  236. step: 1,
  237. callId: CallId('rewrite'),
  238. name: 'echo',
  239. arguments: '{}',
  240. })
  241. const original = session.append('tool/result', {
  242. turn: 1,
  243. step: 1,
  244. message: createToolResultMessage({
  245. callId: CallId('rewrite'),
  246. content: [{ type: 'text', text: 'original' }],
  247. isError: false,
  248. }),
  249. }, { surfaceOp: 'append' })
  250. session.append('step/end', { turn: 1, step: 1 })
  251. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  252. session.append('turn/start', { turn: 2 })
  253. expect(() => session.append('tool/result', {
  254. ...original.data,
  255. message: freezeMessage({
  256. ...original.data.message,
  257. content: [{
  258. ...original.data.message.content[0],
  259. content: [{ type: 'text', text: 'pruned' }],
  260. }],
  261. }),
  262. }, {
  263. surfaceOp: { op: 'replace', start: original.seq, end: original.seq },
  264. sourceEventSeqs: [original.seq],
  265. })).not.toThrow()
  266. })
  267. it('rejects a tool-result replacement outside a turn', async () => {
  268. const { ctx } = await setup()
  269. const session = ctx.sessions.create()
  270. session.append('turn/start', { turn: 1 })
  271. session.append('step/start', { turn: 1, step: 1 })
  272. session.append('tool/call', {
  273. turn: 1,
  274. step: 1,
  275. callId: CallId('rewrite'),
  276. name: 'echo',
  277. arguments: '{}',
  278. })
  279. const original = session.append('tool/result', {
  280. turn: 1,
  281. step: 1,
  282. message: createToolResultMessage({
  283. callId: CallId('rewrite'),
  284. content: [{ type: 'text', text: 'original' }],
  285. isError: false,
  286. }),
  287. }, { surfaceOp: 'append' })
  288. session.append('step/end', { turn: 1, step: 1 })
  289. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  290. expect(() => session.append('tool/result', {
  291. ...original.data,
  292. message: freezeMessage({
  293. ...original.data.message,
  294. content: [{
  295. ...original.data.message.content[0],
  296. content: [{ type: 'text', text: 'pruned' }],
  297. }],
  298. }),
  299. }, {
  300. surfaceOp: { op: 'replace', start: original.seq, end: original.seq },
  301. sourceEventSeqs: [original.seq],
  302. })).toThrow(/outside any open turn/)
  303. })
  304. it('allows not-started repair results and unresolved calls at step end', async () => {
  305. const repaired = (await setup()).ctx.sessions.create()
  306. expect(() => {
  307. repaired.append('turn/start', { turn: 1 })
  308. repaired.append('step/start', { turn: 1, step: 1 })
  309. repaired.append('tool/result', {
  310. turn: 1,
  311. step: 1,
  312. message: createToolResultMessage({
  313. callId: CallId('crashed'),
  314. content: [],
  315. isError: true,
  316. }),
  317. error: { name: 'ToolNotStartedError', code: TOOL_NOT_STARTED },
  318. }, { surfaceOp: 'append' })
  319. repaired.append('step/end', { turn: 1, step: 1 })
  320. repaired.append('turn/end', { turn: 1, reason: { kind: 'interrupted' } })
  321. }).not.toThrow()
  322. const unresolved = (await setup()).ctx.sessions.create()
  323. expect(() => {
  324. unresolved.append('turn/start', { turn: 1 })
  325. unresolved.append('step/start', { turn: 1, step: 1 })
  326. unresolved.append('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'echo', arguments: '{}' })
  327. unresolved.append('step/end', { turn: 1, step: 1 })
  328. unresolved.append('turn/end', { turn: 1, reason: { kind: 'error', error: { message: 'boom', code: 'UNKNOWN' } } })
  329. }).not.toThrow()
  330. })
  331. it('does not let a result in a later step satisfy an earlier call', async () => {
  332. const { ctx } = await setup()
  333. const session = ctx.sessions.create()
  334. session.append('turn/start', { turn: 1 })
  335. session.append('step/start', { turn: 1, step: 1 })
  336. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'echo', arguments: '{}' })
  337. session.append('step/end', { turn: 1, step: 1 })
  338. session.append('step/start', { turn: 1, step: 2 })
  339. expect(() => session.append('tool/result', {
  340. turn: 1,
  341. step: 2,
  342. message: createToolResultMessage({
  343. callId: CallId('c1'),
  344. content: [],
  345. isError: false,
  346. }),
  347. }, { surfaceOp: 'append' })).toThrow(/no prior tool\/call in this step/)
  348. })
  349. it('replays seeded sessions and tracks each session independently', async () => {
  350. const { ctx } = await setup()
  351. const badSeed = [
  352. { type: 'turn/start' as const, seq: 0, time: 0, data: { turn: 1 } },
  353. { type: 'turn/start' as const, seq: 1, time: 0, data: { turn: 2 } },
  354. ]
  355. expect(() => ctx.sessions.create(undefined, { seed: badSeed })).toThrow(InvariantError)
  356. const a = ctx.sessions.create(SessionId('a'))
  357. const b = ctx.sessions.create(SessionId('b'))
  358. a.append('turn/start', { turn: 1 })
  359. expect(() => b.append('turn/start', { turn: 1 }))
  360. .not.toThrow()
  361. })
  362. it('rebuilds trace state for sessions that exist when the companion reloads', async () => {
  363. const { ctx, fiber } = await setup()
  364. const session = ctx.sessions.create()
  365. session.append('turn/start', { turn: 1 })
  366. session.append('step/start', { turn: 1, step: 1 })
  367. await fiber.dispose()
  368. await ctx.plugin(SessionInvariant)
  369. expect(() => session.append('assistant/chunk', {
  370. turn: 1,
  371. step: 1,
  372. chunk: { type: 'text-delta', index: 0, text: 'h' },
  373. })).not.toThrow()
  374. expect(() => session.append('turn/start', { turn: 2 }))
  375. .toThrow(/turn 1 is still open/)
  376. })
  377. it('accepts end-seed whether or not a turn is open', async () => {
  378. const { ctx } = await setup()
  379. // Balanced seed: between turns.
  380. expect(() => ctx.sessions.create(SessionId('inherited-between-turns'), { seed: [
  381. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  382. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  383. ] })).not.toThrow()
  384. // Unbalanced seed: inside the open turn, which the relation permits.
  385. const open = ctx.sessions.create(SessionId('inherited-inside-open-turn'), { seed: [
  386. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  387. ] })
  388. expect(open.events.map(event => event.type)).toEqual(['turn/start', 'session/end-seed'])
  389. // Still open afterwards: the boundary moves no cursor.
  390. expect(() => open.append('turn/start', { turn: 2 }))
  391. .toThrow(/turn 1 is still open/)
  392. expect(() => open.append('turn/end', { turn: 1, reason: { kind: 'completed' } })).not.toThrow()
  393. })
  394. it('removes all listeners when the companion is disposed', async () => {
  395. const { ctx, fiber } = await setup()
  396. const session = ctx.sessions.create()
  397. session.append('turn/start', { turn: 1 })
  398. await fiber.dispose()
  399. expect(() => session.append('turn/start', {
  400. turn: 2,
  401. })).not.toThrow()
  402. })
  403. })