fork.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { createUserMessage, ToolCallId , createMessage } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { Session, SessionForkError, SessionId, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
  5. import type { SessionEvent, TurnEndReason } from '@deepseek-ai/dsh-session'
  6. declare module '@deepseek-ai/dsh-session/types' {
  7. interface SessionEventMap {
  8. 'test/log-only': { value: string }
  9. /** Stands in for a plugin's open/close bracket (`compaction/start`). */
  10. 'test/bracket-open': { id: string }
  11. }
  12. }
  13. async function setup(): Promise<{ ctx: Context; sessions: SessionStore }> {
  14. const ctx = new Context()
  15. await ctx.plugin(SessionStore)
  16. return { ctx, sessions: ctx.sessions }
  17. }
  18. function appendClosedTurn(
  19. session: Session,
  20. turn: number,
  21. text = `hello ${turn}`,
  22. reason: TurnEndReason = { kind: 'completed' },
  23. ): void {
  24. session.append('turn/start', { turn })
  25. session.append('user/message', createUserMessage({
  26. content: [{ type: 'text', text }],
  27. source: { kind: 'user' },
  28. }), { surfaceOp: 'append' })
  29. session.append('turn/end', { turn, reason })
  30. }
  31. function appendOpenTurn(session: Session, turn: number): void {
  32. session.append('turn/start', { turn })
  33. session.append('user/message', createUserMessage({
  34. content: [{ type: 'text', text: `open ${turn}` }],
  35. source: { kind: 'user' },
  36. }), { surfaceOp: 'append' })
  37. }
  38. function firstUserMessage(events: readonly SessionEvent[]): SessionEvent<'user/message'> {
  39. const event = events.find((e): e is SessionEvent<'user/message'> => e.type === 'user/message')
  40. if (event === undefined) throw new Error('missing user/message')
  41. return event
  42. }
  43. function lastSeq(session: Session): SessionSeq {
  44. const event = session.snapshotEvents().at(-1)
  45. if (event === undefined) throw new Error('missing last event')
  46. return event.seq
  47. }
  48. /** A seeded child's fork-inherited prefix. */
  49. function inherited(session: Session): readonly SessionEvent[] {
  50. return session.snapshotEvents(SessionLogOffset(0), session.inheritedEventCount)
  51. }
  52. describe('SessionStore.fork', () => {
  53. it('forks an empty live session as an empty child with lineage metadata', async () => {
  54. const { ctx, sessions } = await setup()
  55. const source = ctx.sessions.create(SessionId('empty-parent'), { meta: { cwd: '/workspace' } })
  56. const child = sessions.fork(source, undefined, SessionId('empty-child'))
  57. expect(inherited(child)).toEqual([])
  58. expect(child.header).toMatchObject({
  59. id: SessionId('empty-child'),
  60. cwd: '/workspace',
  61. parentSession: SessionId('empty-parent'),
  62. isSeeded: true,
  63. })
  64. expect(child.inheritedEventCount).toBe(0)
  65. })
  66. it('forks the latest completed boundary by default into detached frozen seed events', async () => {
  67. const { ctx, sessions } = await setup()
  68. const source = ctx.sessions.create(SessionId('parent'), { meta: { cwd: '/workspace' } })
  69. appendClosedTurn(source, 1, 'hello')
  70. const child = sessions.fork(SessionId('parent'), undefined, SessionId('child'))
  71. expect(inherited(child)).toEqual(source.snapshotEvents())
  72. expect(child.snapshotEvents()).not.toBe(source.snapshotEvents())
  73. expect(child.snapshotEvents()[1]).not.toBe(source.snapshotEvents()[1])
  74. expect(() => {
  75. firstUserMessage(child.snapshotEvents()).data.content[0] = { type: 'text', text: 'child mutation' }
  76. }).toThrow(TypeError)
  77. expect(firstUserMessage(source.snapshotEvents()).data.content).toEqual([{ type: 'text', text: 'hello' }])
  78. expect(firstUserMessage(child.snapshotEvents()).data.content).toEqual([{ type: 'text', text: 'hello' }])
  79. expect(child.header).toMatchObject({
  80. id: SessionId('child'),
  81. cwd: '/workspace',
  82. parentSession: SessionId('parent'),
  83. isSeeded: true,
  84. })
  85. expect(child.inheritedEventCount).toBe(source.seq)
  86. })
  87. it('includes stable log-only events appended after a closed turn', async () => {
  88. const { ctx, sessions } = await setup()
  89. const source = ctx.sessions.create(SessionId('log-only-parent'))
  90. appendClosedTurn(source, 1, 'hello')
  91. source.append('test/log-only', { value: 'after execution' })
  92. const child = sessions.fork(source, undefined, SessionId('log-only-child'))
  93. expect(inherited(child)).toEqual(source.snapshotEvents())
  94. expect(inherited(child).at(-1)).toMatchObject({
  95. type: 'test/log-only',
  96. data: { value: 'after execution' },
  97. })
  98. })
  99. it('forks from an earlier turn boundary even when the source currently has an open tail', async () => {
  100. const { ctx, sessions } = await setup()
  101. const source = ctx.sessions.create(SessionId('parent'), { meta: { cwd: '/workspace' } })
  102. appendClosedTurn(source, 1, 'first')
  103. const firstBoundary = lastSeq(source)
  104. appendClosedTurn(source, 2, 'second')
  105. appendOpenTurn(source, 3)
  106. const child = sessions.fork(source, firstBoundary, SessionId('child-from-first'))
  107. expect(inherited(child)).toEqual(source.snapshotEvents().slice(0, firstBoundary + 1))
  108. expect(child.inheritedEventCount).toBe(firstBoundary + 1)
  109. expect(child.deriveMessages()).toEqual([{
  110. id: expect.any(String) as unknown,
  111. role: 'user',
  112. content: [{ type: 'text', text: 'first' }],
  113. source: { kind: 'user' },
  114. }])
  115. })
  116. it('accepts every turn/end reason as an explicit fork boundary', async () => {
  117. const { ctx, sessions } = await setup()
  118. const reasons: TurnEndReason[] = [
  119. { kind: 'completed' },
  120. { kind: 'aborted', reason: { kind: 'user' } },
  121. { kind: 'error', error: { message: 'model failed', code: 'UNKNOWN' } },
  122. { kind: 'aborted', reason: { kind: 'disposed' } },
  123. { kind: 'max-tokens' },
  124. { kind: 'interrupted' },
  125. ]
  126. for (const [index, reason] of reasons.entries()) {
  127. const source = ctx.sessions.create(SessionId(`parent-${index}`))
  128. appendClosedTurn(source, 1, reason.kind, reason)
  129. const child = sessions.fork(source, lastSeq(source), SessionId(`child-${index}`))
  130. expect(inherited(child).at(-1)?.type).toBe('turn/end')
  131. expect(child.inheritedEventCount).toBe(source.seq)
  132. }
  133. })
  134. it('marks a bracket the child inherited from a still-running parent', async () => {
  135. // The constructor placement's central claim, unreachable from the
  136. // persistence load path.
  137. const { ctx, sessions } = await setup()
  138. const parent = ctx.sessions.create(SessionId('bracket-parent'), { meta: { cwd: '/workspace' } })
  139. appendClosedTurn(parent, 1, 'work')
  140. const open = parent.append('test/bracket-open', { id: 'op-1' })
  141. const child = sessions.fork(parent, undefined, SessionId('bracket-child'))
  142. // Parent: no end-seed event follows the bracket, so its owner treats it as live.
  143. expect(parent.snapshotEvents().at(-1)).toBe(open)
  144. expect(parent.snapshotEvents().some(event => event.type === 'session/end-seed')).toBe(false)
  145. // Child: the same bracket is before end-seed, so it belongs to the seed.
  146. const boundary = child.snapshotEvents().at(-1)
  147. expect(boundary).toMatchObject({ type: 'session/end-seed' })
  148. expect(boundary!.seq).toBeGreaterThan(open.seq)
  149. expect(child.firstLiveSeq).toBe(open.seq + 1)
  150. expect(inherited(child).at(-1)).toMatchObject({ type: 'test/bracket-open', data: { id: 'op-1' } })
  151. })
  152. it('rejects invalid boundaries before creating a child', async () => {
  153. const { ctx, sessions } = await setup()
  154. const empty = ctx.sessions.create(SessionId('empty'))
  155. expect(() => sessions.fork(empty, SessionSeq(0), SessionId('empty-child')))
  156. .toThrow(new SessionForkError('fork boundary 0 does not exist in session "empty" (last seq: none)', 'INVALID_BOUNDARY'))
  157. expect(ctx.sessions.get(SessionId('empty-child'))).toBeUndefined()
  158. const source = ctx.sessions.create(SessionId('parent'))
  159. appendClosedTurn(source, 1)
  160. expect(() => sessions.fork(source, -1 as never, SessionId('negative')))
  161. .toThrow(/non-negative safe integer/)
  162. expect(() => sessions.fork(source, 0.5 as never, SessionId('fraction')))
  163. .toThrow(/non-negative safe integer/)
  164. expect(() => sessions.fork(source, (Number.MAX_SAFE_INTEGER + 1) as never, SessionId('unsafe')))
  165. .toThrow(/non-negative safe integer/)
  166. expect(() => sessions.fork(source, SessionSeq(source.seq), SessionId('past-end')))
  167. .toThrow(new SessionForkError(`fork boundary ${source.seq} does not exist in session "parent" (last seq: ${source.seq - 1})`, 'INVALID_BOUNDARY'))
  168. })
  169. it('rejects a corrupted live source whose array index no longer matches event seq', async () => {
  170. const { ctx, sessions } = await setup()
  171. const source = ctx.sessions.create(SessionId('corrupt-parent'))
  172. appendClosedTurn(source, 1)
  173. const mutableLog = (source as unknown as { log: SessionEvent[] }).log
  174. mutableLog[2] = { ...mutableLog[2]!, seq: SessionSeq(99) }
  175. expect(() => sessions.fork(source, SessionSeq(2), SessionId('corrupt-child')))
  176. .toThrow(new SessionForkError('fork boundary 2 does not match a contiguous event seq in session "corrupt-parent"', 'INVALID_BOUNDARY'))
  177. expect(ctx.sessions.get(SessionId('corrupt-child'))).toBeUndefined()
  178. })
  179. it('rejects an unknown live session id', async () => {
  180. const { sessions } = await setup()
  181. expect(() => sessions.fork(SessionId('missing')))
  182. .toThrow(new SessionForkError('session "missing" not found', 'SESSION_NOT_FOUND'))
  183. })
  184. it('rejects a detached Session object that is not live in ctx.sessions', async () => {
  185. const { sessions } = await setup()
  186. const detached = Session.create(SessionId('detached'))
  187. expect(() => sessions.fork(detached))
  188. .toThrow(new SessionForkError('session "detached" not found', 'SESSION_NOT_FOUND'))
  189. })
  190. it('rejects a stale Session object whose id is live on a different instance', async () => {
  191. const { ctx, sessions } = await setup()
  192. ctx.sessions.create(SessionId('same-id'))
  193. const stale = Session.create(SessionId('same-id'))
  194. expect(() => sessions.fork(stale))
  195. .toThrow(new SessionForkError('session "same-id" is not the live store instance', 'SESSION_NOT_LIVE'))
  196. })
  197. it('rejects selected slices whose boundary is inside an open turn', async () => {
  198. const { ctx, sessions } = await setup()
  199. const cases: [string, (session: Session) => number][] = [
  200. ['turn/start', (session) => {
  201. session.append('turn/start', { turn: 1 })
  202. return lastSeq(session)
  203. }],
  204. ['step/start', (session) => {
  205. session.append('turn/start', { turn: 1 })
  206. session.append('step/start', { turn: 1, step: 1 })
  207. return lastSeq(session)
  208. }],
  209. ['user/message', (session) => {
  210. session.append('turn/start', { turn: 1 })
  211. session.append('user/message', createUserMessage({
  212. content: [{ type: 'text', text: 'open' }], source: { kind: 'user' },
  213. }), { surfaceOp: 'append' })
  214. return lastSeq(session)
  215. }],
  216. ['assistant/message', (session) => {
  217. session.append('turn/start', { turn: 1 })
  218. session.append('step/start', { turn: 1, step: 1 })
  219. session.append('assistant/message', {
  220. stream: [],
  221. turn: 1, step: 1,
  222. message: createMessage({
  223. role: 'assistant',
  224. content: [{ type: 'text', text: 'partial' }],
  225. source: {
  226. kind: 'model',
  227. ...{ provider: 'mock', model: 'mock' },
  228. },
  229. }),
  230. }, { surfaceOp: 'append' })
  231. return lastSeq(session)
  232. }],
  233. ['tool/call', (session) => {
  234. const callId = ToolCallId('call-open')
  235. session.append('turn/start', { turn: 1 })
  236. session.append('step/start', { turn: 1, step: 1 })
  237. session.append('assistant/message', {
  238. stream: [],
  239. turn: 1,
  240. step: 1,
  241. message: createMessage({
  242. role: 'assistant',
  243. content: [{ type: 'tool-call', id: callId, name: 'bash', arguments: '{}' }],
  244. source: {
  245. kind: 'model',
  246. ...{ provider: 'mock', model: 'mock' },
  247. },
  248. }),
  249. }, { surfaceOp: 'append' })
  250. session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: '{}' })
  251. return lastSeq(session)
  252. }],
  253. ]
  254. for (const [lastType, build] of cases) {
  255. const source = ctx.sessions.create(SessionId(`open-${lastType}`))
  256. const boundary = build(source)
  257. expect(() => sessions.fork(source, SessionSeq(boundary)))
  258. .toThrow(new SessionForkError(`fork boundary ${boundary} in session "open-${lastType}" ends inside open turn 1`, 'OPEN_TURN'))
  259. }
  260. })
  261. it('rejects a child session id that is already live with a typed fork error', async () => {
  262. const { ctx, sessions } = await setup()
  263. const source = ctx.sessions.create(SessionId('parent'))
  264. appendClosedTurn(source, 1)
  265. ctx.sessions.create(SessionId('child'))
  266. expect(() => sessions.fork(source, undefined, SessionId('child')))
  267. .toThrow(new SessionForkError('session "child" already exists', 'SESSION_ALREADY_EXISTS'))
  268. })
  269. it('rejects a duplicate child session id before validating the boundary', async () => {
  270. const { ctx, sessions } = await setup()
  271. const source = ctx.sessions.create(SessionId('open-parent'))
  272. source.append('turn/start', { turn: 1 })
  273. ctx.sessions.create(SessionId('child'))
  274. expect(() => sessions.fork(source, undefined, SessionId('child')))
  275. .toThrow(new SessionForkError('session "child" already exists', 'SESSION_ALREADY_EXISTS'))
  276. })
  277. })