invariant.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from '@deepseek-ai/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 InvariantRegistry, { 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(InvariantRegistry)
  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(InvariantRegistry)
  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('request/header', {
  135. header: { config: { provider: 'mock', model: 'mock' } },
  136. reason: 'initial',
  137. } as never)).not.toThrow()
  138. expect(() => enclosed.append('request/context', {
  139. provider: 'mock', model: 'mock',
  140. })).not.toThrow()
  141. const outside = (await setup()).ctx.sessions.create()
  142. expect(() => outside.append('user/message', createUserMessage({
  143. content: [{ type: 'text', text: 'idle context' }],
  144. source: { kind: 'plugin', plugin: 'test' },
  145. }), { surfaceOp: 'append' })).not.toThrow()
  146. // Route capacity is core execution state like the header beside it.
  147. expect(() => outside.append('request/context', {
  148. provider: 'mock',
  149. model: 'm',
  150. contextWindow: 128_000,
  151. })).toThrow(/outside any open turn/)
  152. // The owning plugin decides whether a merge-extensible event is log-only.
  153. const appendUnknown = outside.append.bind(outside) as (type: string, data: unknown) => unknown
  154. expect(() => { appendUnknown('plugin/marker', {}) }).not.toThrow()
  155. expect(() => outside.append('turn/start', {
  156. turn: 1,
  157. })).not.toThrow()
  158. })
  159. it('enforces open-step identity and numbering', async () => {
  160. const wrongTurn = (await setup()).ctx.sessions.create()
  161. wrongTurn.append('turn/start', { turn: 1 })
  162. expect(() => wrongTurn.append('step/start', { turn: 2, step: 1 })).toThrow(/open turn is 1/)
  163. const nested = (await setup()).ctx.sessions.create()
  164. nested.append('turn/start', { turn: 1 })
  165. nested.append('step/start', { turn: 1, step: 1 })
  166. expect(() => nested.append('step/start', { turn: 1, step: 2 })).toThrow(/while step 1 is still open/)
  167. expect(() => nested.append('turn/end', { turn: 1, reason: { kind: 'completed' } }))
  168. .toThrow(/while step 1 is still open/)
  169. expect(() => nested.append('step/end', { turn: 1, step: 2 })).toThrow(/open is turn 1\/step 1/)
  170. expect(() => nested.append('assistant/message', {
  171. turn: 1,
  172. step: 2,
  173. message: createMessage({
  174. role: 'assistant',
  175. content: [],
  176. source: {
  177. kind: 'model',
  178. ...{ provider: 'mock', model: 'mock' },
  179. },
  180. }),
  181. }, { surfaceOp: 'append' })).toThrow(/open is turn 1\/step 1/)
  182. const skipped = (await setup()).ctx.sessions.create()
  183. skipped.append('turn/start', { turn: 1 })
  184. skipped.append('step/start', { turn: 1, step: 1 })
  185. skipped.append('step/end', { turn: 1, step: 1 })
  186. expect(() => skipped.append('step/start', { turn: 1, step: 3 }))
  187. .toThrow(/expected step 2 in turn 1, got 3/)
  188. expect(() => skipped.append('turn/end', {
  189. turn: 1,
  190. reason: { kind: 'completed' },
  191. })).not.toThrow()
  192. })
  193. it('requires step-scoped stream and tool events to name the open step', async () => {
  194. const chunk = (await setup()).ctx.sessions.create()
  195. chunk.append('turn/start', { turn: 1 })
  196. expect(() => chunk.append('assistant/chunk', {
  197. turn: 1,
  198. step: 1,
  199. chunk: { type: 'text-delta', index: 0, text: 'x' },
  200. })).toThrow(/open is turn 1\/step null/)
  201. const tool = (await setup()).ctx.sessions.create()
  202. tool.append('turn/start', { turn: 1 })
  203. tool.append('step/start', { turn: 1, step: 1 })
  204. expect(() => tool.append('tool/result', {
  205. turn: 1,
  206. step: 1,
  207. message: createToolResultMessage({
  208. callId: CallId('ghost'),
  209. content: [],
  210. isError: false,
  211. }),
  212. }, { surfaceOp: 'append' })).toThrow(/no prior tool\/call/)
  213. })
  214. it('keeps fresh tool-result appends open-step checked', async () => {
  215. const { ctx } = await setup()
  216. const session = ctx.sessions.create()
  217. session.append('turn/start', { turn: 1 })
  218. expect(() => session.append('tool/result', {
  219. turn: 1,
  220. step: 1,
  221. message: createToolResultMessage({
  222. callId: CallId('closed'),
  223. content: [],
  224. isError: false,
  225. }),
  226. }, { surfaceOp: 'append' })).toThrow(/open is turn 1\/step null/)
  227. })
  228. it('treats a validated tool-result replacement as a turn-enclosed rewrite', async () => {
  229. const { ctx } = await setup()
  230. const session = ctx.sessions.create()
  231. session.append('turn/start', { turn: 1 })
  232. session.append('step/start', { turn: 1, step: 1 })
  233. session.append('tool/call', {
  234. turn: 1,
  235. step: 1,
  236. callId: CallId('rewrite'),
  237. name: 'echo',
  238. arguments: '{}',
  239. })
  240. const original = session.append('tool/result', {
  241. turn: 1,
  242. step: 1,
  243. message: createToolResultMessage({
  244. callId: CallId('rewrite'),
  245. content: [{ type: 'text', text: 'original' }],
  246. isError: false,
  247. }),
  248. }, { surfaceOp: 'append' })
  249. session.append('step/end', { turn: 1, step: 1 })
  250. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  251. session.append('turn/start', { turn: 2 })
  252. expect(() => session.append('tool/result', {
  253. ...original.data,
  254. message: freezeMessage({
  255. ...original.data.message,
  256. content: [{
  257. ...original.data.message.content[0],
  258. content: [{ type: 'text', text: 'pruned' }],
  259. }] satisfies typeof original.data.message.content,
  260. }),
  261. }, {
  262. surfaceOp: { op: 'replace', start: original.seq, end: original.seq },
  263. sourceEventSeqs: [original.seq],
  264. })).not.toThrow()
  265. })
  266. it('rejects a tool-result replacement outside a turn', async () => {
  267. const { ctx } = await setup()
  268. const session = ctx.sessions.create()
  269. session.append('turn/start', { turn: 1 })
  270. session.append('step/start', { turn: 1, step: 1 })
  271. session.append('tool/call', {
  272. turn: 1,
  273. step: 1,
  274. callId: CallId('rewrite'),
  275. name: 'echo',
  276. arguments: '{}',
  277. })
  278. const original = session.append('tool/result', {
  279. turn: 1,
  280. step: 1,
  281. message: createToolResultMessage({
  282. callId: CallId('rewrite'),
  283. content: [{ type: 'text', text: 'original' }],
  284. isError: false,
  285. }),
  286. }, { surfaceOp: 'append' })
  287. session.append('step/end', { turn: 1, step: 1 })
  288. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  289. expect(() => session.append('tool/result', {
  290. ...original.data,
  291. message: freezeMessage({
  292. ...original.data.message,
  293. content: [{
  294. ...original.data.message.content[0],
  295. content: [{ type: 'text', text: 'pruned' }],
  296. }] satisfies typeof original.data.message.content,
  297. }),
  298. }, {
  299. surfaceOp: { op: 'replace', start: original.seq, end: original.seq },
  300. sourceEventSeqs: [original.seq],
  301. })).toThrow(/outside any open turn/)
  302. })
  303. it('allows not-started repair results and unresolved calls at step end', async () => {
  304. const repaired = (await setup()).ctx.sessions.create()
  305. expect(() => {
  306. repaired.append('turn/start', { turn: 1 })
  307. repaired.append('step/start', { turn: 1, step: 1 })
  308. repaired.append('tool/result', {
  309. turn: 1,
  310. step: 1,
  311. message: createToolResultMessage({
  312. callId: CallId('crashed'),
  313. content: [],
  314. isError: true,
  315. }),
  316. error: { name: 'ToolNotStartedError', code: TOOL_NOT_STARTED },
  317. }, { surfaceOp: 'append' })
  318. repaired.append('step/end', { turn: 1, step: 1 })
  319. repaired.append('turn/end', { turn: 1, reason: { kind: 'interrupted' } })
  320. }).not.toThrow()
  321. const unresolved = (await setup()).ctx.sessions.create()
  322. expect(() => {
  323. unresolved.append('turn/start', { turn: 1 })
  324. unresolved.append('step/start', { turn: 1, step: 1 })
  325. unresolved.append('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'echo', arguments: '{}' })
  326. unresolved.append('step/end', { turn: 1, step: 1 })
  327. unresolved.append('turn/end', { turn: 1, reason: { kind: 'error', error: { message: 'boom', code: 'UNKNOWN' } } })
  328. }).not.toThrow()
  329. })
  330. it('does not let a result in a later step satisfy an earlier call', async () => {
  331. const { ctx } = await setup()
  332. const session = ctx.sessions.create()
  333. session.append('turn/start', { turn: 1 })
  334. session.append('step/start', { turn: 1, step: 1 })
  335. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'echo', arguments: '{}' })
  336. session.append('step/end', { turn: 1, step: 1 })
  337. session.append('step/start', { turn: 1, step: 2 })
  338. expect(() => session.append('tool/result', {
  339. turn: 1,
  340. step: 2,
  341. message: createToolResultMessage({
  342. callId: CallId('c1'),
  343. content: [],
  344. isError: false,
  345. }),
  346. }, { surfaceOp: 'append' })).toThrow(/no prior tool\/call in this step/)
  347. })
  348. it('replays seeded sessions and tracks each session independently', async () => {
  349. const { ctx } = await setup()
  350. const badSeed = [
  351. { type: 'turn/start' as const, seq: 0, time: 0, data: { turn: 1 } },
  352. { type: 'turn/start' as const, seq: 1, time: 0, data: { turn: 2 } },
  353. ]
  354. expect(() => ctx.sessions.create(undefined, { seed: badSeed })).toThrow(InvariantError)
  355. const a = ctx.sessions.create(SessionId('a'))
  356. const b = ctx.sessions.create(SessionId('b'))
  357. a.append('turn/start', { turn: 1 })
  358. expect(() => b.append('turn/start', { turn: 1 }))
  359. .not.toThrow()
  360. })
  361. it('rebuilds trace state for sessions that exist when the companion reloads', async () => {
  362. const { ctx, fiber } = await setup()
  363. const session = ctx.sessions.create()
  364. session.append('turn/start', { turn: 1 })
  365. session.append('step/start', { turn: 1, step: 1 })
  366. await fiber.dispose()
  367. await ctx.plugin(SessionInvariant)
  368. expect(() => session.append('assistant/chunk', {
  369. turn: 1,
  370. step: 1,
  371. chunk: { type: 'text-delta', index: 0, text: 'h' },
  372. })).not.toThrow()
  373. expect(() => session.append('turn/start', { turn: 2 }))
  374. .toThrow(/turn 1 is still open/)
  375. })
  376. it('accepts end-seed whether or not a turn is open', async () => {
  377. const { ctx } = await setup()
  378. // Balanced seed: between turns.
  379. expect(() => ctx.sessions.create(SessionId('inherited-between-turns'), { seed: [
  380. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  381. { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
  382. ] })).not.toThrow()
  383. // Unbalanced seed: inside the open turn, which the relation permits.
  384. const open = ctx.sessions.create(SessionId('inherited-inside-open-turn'), { seed: [
  385. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
  386. ] })
  387. expect(open.events.map(event => event.type)).toEqual(['turn/start', 'session/end-seed'])
  388. // Still open afterwards: the boundary moves no cursor.
  389. expect(() => open.append('turn/start', { turn: 2 }))
  390. .toThrow(/turn 1 is still open/)
  391. expect(() => open.append('turn/end', { turn: 1, reason: { kind: 'completed' } })).not.toThrow()
  392. })
  393. it('removes all listeners when the companion is disposed', async () => {
  394. const { ctx, fiber } = await setup()
  395. const session = ctx.sessions.create()
  396. session.append('turn/start', { turn: 1 })
  397. await fiber.dispose()
  398. expect(() => session.append('turn/start', {
  399. turn: 2,
  400. })).not.toThrow()
  401. })
  402. })