fork.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { Session, SessionForkError, SessionId } from '@deepseek-ai/dsh-session'
  5. import type { SessionEvent, TurnEndReason } from '@deepseek-ai/dsh-session'
  6. async function setup(): Promise<{ ctx: Context; sessions: SessionStore }> {
  7. const ctx = new Context()
  8. await ctx.plugin(SessionStore)
  9. return { ctx, sessions: ctx.sessions }
  10. }
  11. function appendClosedTurn(
  12. session: Session,
  13. turn: number,
  14. text = `hello ${turn}`,
  15. reason: TurnEndReason = { kind: 'completed' },
  16. ): void {
  17. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  18. session.append('user/message', {
  19. content: [{ type: 'text', text }],
  20. source: { kind: 'user' },
  21. }, { surfaceOp: 'append' })
  22. session.append('turn/end', { turn, reason })
  23. }
  24. function appendOpenTurn(session: Session, turn: number): void {
  25. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  26. session.append('user/message', {
  27. content: [{ type: 'text', text: `open ${turn}` }],
  28. source: { kind: 'user' },
  29. }, { surfaceOp: 'append' })
  30. }
  31. function firstUserMessage(events: readonly SessionEvent[]): SessionEvent<'user/message'> {
  32. const event = events.find((e): e is SessionEvent<'user/message'> => e.type === 'user/message')
  33. if (event === undefined) throw new Error('missing user/message')
  34. return event
  35. }
  36. function lastSeq(session: Session): number {
  37. const event = session.events.at(-1)
  38. if (event === undefined) throw new Error('missing last event')
  39. return event.seq
  40. }
  41. describe('SessionStore.fork', () => {
  42. it('forks an empty live session as an empty child with lineage metadata', async () => {
  43. const { ctx, sessions } = await setup()
  44. const source = ctx.sessions.create(SessionId('empty-parent'), { meta: { cwd: '/workspace' } })
  45. const child = sessions.fork(source, undefined, SessionId('empty-child'))
  46. expect(child.events).toEqual([])
  47. expect(child.header).toMatchObject({
  48. id: SessionId('empty-child'),
  49. cwd: '/workspace',
  50. parentSession: SessionId('empty-parent'),
  51. seedLength: 0,
  52. })
  53. })
  54. it('forks the latest completed boundary by default into detached frozen seed events', async () => {
  55. const { ctx, sessions } = await setup()
  56. const source = ctx.sessions.create(SessionId('parent'), { meta: { cwd: '/workspace' } })
  57. appendClosedTurn(source, 1, 'hello')
  58. const child = sessions.fork(SessionId('parent'), undefined, SessionId('child'))
  59. expect(child.events).toEqual(source.events)
  60. expect(child.events).not.toBe(source.events)
  61. expect(child.events[1]).not.toBe(source.events[1])
  62. expect(() => {
  63. firstUserMessage(child.events).data.content[0] = { type: 'text', text: 'child mutation' }
  64. }).toThrow(TypeError)
  65. expect(firstUserMessage(source.events).data.content).toEqual([{ type: 'text', text: 'hello' }])
  66. expect(firstUserMessage(child.events).data.content).toEqual([{ type: 'text', text: 'hello' }])
  67. expect(child.header).toMatchObject({
  68. id: SessionId('child'),
  69. cwd: '/workspace',
  70. parentSession: SessionId('parent'),
  71. seedLength: source.events.length,
  72. })
  73. })
  74. it('forks from an earlier turn boundary even when the source currently has an open tail', async () => {
  75. const { ctx, sessions } = await setup()
  76. const source = ctx.sessions.create(SessionId('parent'), { meta: { cwd: '/workspace' } })
  77. appendClosedTurn(source, 1, 'first')
  78. const firstBoundary = lastSeq(source)
  79. appendClosedTurn(source, 2, 'second')
  80. appendOpenTurn(source, 3)
  81. const child = sessions.fork(source, firstBoundary, SessionId('child-from-first'))
  82. expect(child.events).toEqual(source.events.slice(0, firstBoundary + 1))
  83. expect(child.header.seedLength).toBe(firstBoundary + 1)
  84. expect(child.deriveMessages()).toEqual([{ role: 'user', content: [{ type: 'text', text: 'first' }] }])
  85. })
  86. it('accepts every turn/end reason as an explicit fork boundary', async () => {
  87. const { ctx, sessions } = await setup()
  88. const reasons: TurnEndReason[] = [
  89. { kind: 'completed' },
  90. { kind: 'aborted' },
  91. { kind: 'error', step: 1, message: 'model failed', code: 'MODEL' },
  92. { kind: 'disposed' },
  93. { kind: 'max-tokens' },
  94. { kind: 'interrupted' },
  95. ]
  96. for (const reason of reasons) {
  97. const source = ctx.sessions.create(SessionId(`parent-${reason.kind}`))
  98. appendClosedTurn(source, 1, reason.kind, reason)
  99. const child = sessions.fork(source, lastSeq(source), SessionId(`child-${reason.kind}`))
  100. expect(child.events.at(-1)?.type).toBe('turn/end')
  101. expect(child.header.seedLength).toBe(source.events.length)
  102. }
  103. })
  104. it('rejects invalid boundaries before creating a child', async () => {
  105. const { ctx, sessions } = await setup()
  106. const empty = ctx.sessions.create(SessionId('empty'))
  107. expect(() => sessions.fork(empty, 0, SessionId('empty-child')))
  108. .toThrow(new SessionForkError('fork boundary 0 does not exist in session "empty" (last seq: none)', 'INVALID_BOUNDARY'))
  109. expect(ctx.sessions.get(SessionId('empty-child'))).toBeUndefined()
  110. const source = ctx.sessions.create(SessionId('parent'))
  111. appendClosedTurn(source, 1)
  112. expect(() => sessions.fork(source, -1, SessionId('negative')))
  113. .toThrow(/non-negative safe integer/)
  114. expect(() => sessions.fork(source, 0.5, SessionId('fraction')))
  115. .toThrow(/non-negative safe integer/)
  116. expect(() => sessions.fork(source, Number.MAX_SAFE_INTEGER + 1, SessionId('unsafe')))
  117. .toThrow(/non-negative safe integer/)
  118. expect(() => sessions.fork(source, source.seq, SessionId('past-end')))
  119. .toThrow(new SessionForkError(`fork boundary ${source.seq} does not exist in session "parent" (last seq: ${source.seq - 1})`, 'INVALID_BOUNDARY'))
  120. })
  121. it('rejects a corrupted live source whose array index no longer matches event seq', async () => {
  122. const { ctx, sessions } = await setup()
  123. const source = ctx.sessions.create(SessionId('corrupt-parent'))
  124. appendClosedTurn(source, 1)
  125. const mutableLog = (source as unknown as { log: SessionEvent[] }).log
  126. mutableLog[2] = { ...mutableLog[2]!, seq: 99 }
  127. expect(() => sessions.fork(source, 2, SessionId('corrupt-child')))
  128. .toThrow(new SessionForkError('fork boundary 2 does not match a contiguous event seq in session "corrupt-parent"', 'INVALID_BOUNDARY'))
  129. expect(ctx.sessions.get(SessionId('corrupt-child'))).toBeUndefined()
  130. })
  131. it('rejects an unknown live session id', async () => {
  132. const { sessions } = await setup()
  133. expect(() => sessions.fork(SessionId('missing')))
  134. .toThrow(new SessionForkError('session "missing" not found', 'SESSION_NOT_FOUND'))
  135. })
  136. it('rejects a detached Session object that is not live in ctx.sessions', async () => {
  137. const { sessions } = await setup()
  138. const detached = new Session(SessionId('detached'))
  139. expect(() => sessions.fork(detached))
  140. .toThrow(new SessionForkError('session "detached" not found', 'SESSION_NOT_FOUND'))
  141. })
  142. it('rejects a stale Session object whose id is live on a different instance', async () => {
  143. const { ctx, sessions } = await setup()
  144. ctx.sessions.create(SessionId('same-id'))
  145. const stale = new Session(SessionId('same-id'))
  146. expect(() => sessions.fork(stale))
  147. .toThrow(new SessionForkError('session "same-id" is not the live store instance', 'SESSION_NOT_LIVE'))
  148. })
  149. it('rejects selected slices whose boundary is inside an open turn', async () => {
  150. const { ctx, sessions } = await setup()
  151. const cases: [string, (session: Session) => number][] = [
  152. ['turn/start', (session) => {
  153. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  154. return lastSeq(session)
  155. }],
  156. ['step/start', (session) => {
  157. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  158. session.append('step/start', { turn: 1, step: 1 })
  159. return lastSeq(session)
  160. }],
  161. ['user/message', (session) => {
  162. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  163. session.append('user/message', { content: [{ type: 'text', text: 'open' }], source: { kind: 'user' } }, { surfaceOp: 'append' })
  164. return lastSeq(session)
  165. }],
  166. ['assistant/message', (session) => {
  167. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  168. session.append('step/start', { turn: 1, step: 1 })
  169. session.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' }, turn: 1, step: 1, content: [{ type: 'text', text: 'partial' }] }, { surfaceOp: 'append' })
  170. return lastSeq(session)
  171. }],
  172. ['tool/call', (session) => {
  173. const callId = CallId('call-open')
  174. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  175. session.append('step/start', { turn: 1, step: 1 })
  176. session.append('assistant/message', { provenance: { provider: 'mock', model: 'mock' },
  177. turn: 1,
  178. step: 1,
  179. content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
  180. }, { surfaceOp: 'append' })
  181. session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: '{}' })
  182. return lastSeq(session)
  183. }],
  184. ]
  185. for (const [lastType, build] of cases) {
  186. const source = ctx.sessions.create(SessionId(`open-${lastType}`))
  187. const boundary = build(source)
  188. expect(() => sessions.fork(source, boundary))
  189. .toThrow(new SessionForkError(`fork boundary ${boundary} in session "open-${lastType}" must be turn/end, got ${lastType}`, 'OPEN_TURN'))
  190. }
  191. })
  192. it('rejects a child session id that is already live with a typed fork error', async () => {
  193. const { ctx, sessions } = await setup()
  194. const source = ctx.sessions.create(SessionId('parent'))
  195. appendClosedTurn(source, 1)
  196. ctx.sessions.create(SessionId('child'))
  197. expect(() => sessions.fork(source, undefined, SessionId('child')))
  198. .toThrow(new SessionForkError('session "child" already exists', 'SESSION_ALREADY_EXISTS'))
  199. })
  200. it('rejects a duplicate child session id before validating the boundary', async () => {
  201. const { ctx, sessions } = await setup()
  202. const source = ctx.sessions.create(SessionId('open-parent'))
  203. source.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  204. ctx.sessions.create(SessionId('child'))
  205. expect(() => sessions.fork(source, undefined, SessionId('child')))
  206. .toThrow(new SessionForkError('session "child" already exists', 'SESSION_ALREADY_EXISTS'))
  207. })
  208. })