invariant.spec.ts 18 KB

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