invariant.spec.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  4. import InvariantService from '@deepseek-ai/dsh-invariants'
  5. import * as AgentLoopInvariant from '@deepseek-ai/dsh-agent-loop/invariant'
  6. import { createUserMessage, markAgentLoopRequest, type GenerateOptions } from '@deepseek-ai/dsh-llm'
  7. async function setup(): Promise<Context> {
  8. const ctx = new Context()
  9. await ctx.plugin(SessionStore)
  10. await ctx.plugin(InvariantService)
  11. await ctx.plugin(AgentLoopInvariant)
  12. return ctx
  13. }
  14. function dispatch(ctx: Context, options: unknown): void {
  15. void ctx.waterfall('llm/stream', options as never, () => (async function* () {})() as never)
  16. }
  17. function loopRequest<T extends object>(options: T): Readonly<T> {
  18. markAgentLoopRequest(options as GenerateOptions)
  19. return Object.freeze(options)
  20. }
  21. async function requestSetup() {
  22. const ctx = await setup()
  23. const session = ctx.sessions.create(SessionId('req-check'))
  24. session.append('turn/start', { turn: 1 })
  25. session.append('user/message', createUserMessage({
  26. content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' },
  27. }), { surfaceOp: 'append' })
  28. const boundary = session.deriveMessages()
  29. session.append('step/start', { turn: 1, step: 1 })
  30. session.append('request/header', { header: { config: { provider: 'mock', model: 'm' } }, reason: 'initial' })
  31. return { ctx, session, boundary }
  32. }
  33. describe('request-reconstruction invariant', () => {
  34. it('accepts a frozen request equal to the boundary derivation and folded header', async () => {
  35. const { ctx, session, boundary } = await requestSetup()
  36. const options = loopRequest({ model: 'm', messages: Object.freeze(boundary), sessionId: session.id })
  37. expect(() => { dispatch(ctx, options) }).not.toThrow()
  38. })
  39. it('includes context appended inside the open step before dispatch', async () => {
  40. const { ctx, session } = await requestSetup()
  41. session.append('user/message', createUserMessage({
  42. content: [{ type: 'text', text: '[step context]' }], source: { kind: 'plugin', plugin: 'x' },
  43. }), { surfaceOp: 'append' })
  44. const options = loopRequest({
  45. model: 'm',
  46. messages: Object.freeze(session.deriveMessages()),
  47. sessionId: session.id,
  48. })
  49. expect(() => { dispatch(ctx, options) }).not.toThrow()
  50. })
  51. it('requires the messages to equal the boundary derivation exactly (no unlogged prefix)', async () => {
  52. const { ctx, session, boundary } = await requestSetup()
  53. const extra = { role: 'user' as const, content: [{ type: 'text' as const, text: '<system-reminder>catalog</system-reminder>' }] }
  54. expect(() => { dispatch(ctx, loopRequest({ model: 'm', messages: Object.freeze([...boundary]), sessionId: session.id })) })
  55. .not.toThrow()
  56. expect(() => { dispatch(ctx, loopRequest({ model: 'm', messages: Object.freeze([extra, ...boundary]), sessionId: session.id })) })
  57. .toThrow(/diverges from the dispatch-time durable derivation/)
  58. expect(() => { dispatch(ctx, loopRequest({ model: 'm', messages: Object.freeze([...boundary, extra]), sessionId: session.id })) })
  59. .toThrow(/diverges from the dispatch-time durable derivation/)
  60. })
  61. it('rejects message and header divergence', async () => {
  62. const { ctx, session, boundary } = await requestSetup()
  63. const divergent = [...boundary, { role: 'user', content: [{ type: 'text', text: 'phantom' }] }]
  64. expect(() => { dispatch(ctx, loopRequest({ model: 'm', messages: Object.freeze(divergent), sessionId: session.id })) })
  65. .toThrow(/diverges from the dispatch-time durable derivation/)
  66. expect(() => { dispatch(ctx, loopRequest({ model: 'other', messages: Object.freeze(boundary), sessionId: session.id })) })
  67. .toThrow(/diverges from the folded request header/)
  68. })
  69. it('rejects loop requests with no boundary or header', async () => {
  70. const ctx = await setup()
  71. const session = ctx.sessions.create(SessionId('req-bare'))
  72. session.append('turn/start', { turn: 1 })
  73. const bare = loopRequest({ model: 'm', messages: Object.freeze([]), sessionId: session.id })
  74. expect(() => { dispatch(ctx, bare) }).toThrow(/no step\/start/)
  75. session.append('step/start', { turn: 1, step: 1 })
  76. expect(() => { dispatch(ctx, bare) }).toThrow(/no request\/header event/)
  77. })
  78. it('rejects an unfrozen messages array but skips requests outside the loop contract', async () => {
  79. const { ctx, session, boundary } = await requestSetup()
  80. expect(() => { dispatch(ctx, loopRequest({ model: 'm', messages: [...boundary], sessionId: session.id })) })
  81. .toThrow(/frozen messages array/)
  82. expect(() => { dispatch(ctx, { model: 'summarizer', messages: [], sessionId: session.id }) }).not.toThrow()
  83. expect(() => { dispatch(ctx, Object.freeze({ model: 'm', messages: Object.freeze([]) })) }).not.toThrow()
  84. expect(() => { dispatch(ctx, Object.freeze({ model: 'm', messages: Object.freeze([]), sessionId: SessionId('ghost') })) })
  85. .not.toThrow()
  86. const directSession = ctx.sessions.create(SessionId('direct-one-shot'))
  87. expect(() => {
  88. dispatch(ctx, Object.freeze({ model: 'one-shot', messages: Object.freeze([]), sessionId: directSession.id }))
  89. }).not.toThrow()
  90. })
  91. it('rejects malformed requests carrying the loop marker', async () => {
  92. const { ctx, session } = await requestSetup()
  93. const messages: GenerateOptions['messages'] = []
  94. Object.freeze(messages)
  95. expect(() => {
  96. dispatch(ctx, markAgentLoopRequest({ provider: 'p', model: 'm', messages, sessionId: session.id }))
  97. }).toThrow(/request must be frozen/)
  98. expect(() => {
  99. dispatch(ctx, loopRequest({ model: 'm', messages: Object.freeze([]) }))
  100. }).toThrow(/carry a session id/)
  101. expect(() => {
  102. dispatch(ctx, loopRequest({
  103. model: 'm',
  104. messages: Object.freeze([]),
  105. sessionId: SessionId('missing-loop-session'),
  106. }))
  107. }).toThrow(/live session id/)
  108. })
  109. it('prepends ahead of a short-circuiting stream listener', async () => {
  110. const ctx = new Context()
  111. await ctx.plugin(SessionStore)
  112. ctx.on('llm/stream', () => (async function* () {})() as never)
  113. await ctx.plugin(InvariantService)
  114. await ctx.plugin(AgentLoopInvariant)
  115. const session = ctx.sessions.create(SessionId('prepend-check'))
  116. session.append('turn/start', { turn: 1 })
  117. session.append('user/message', createUserMessage({
  118. content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' },
  119. }), { surfaceOp: 'append' })
  120. session.append('step/start', { turn: 1, step: 1 })
  121. session.append('request/header', { header: { config: { provider: 'mock', model: 'm' } }, reason: 'initial' })
  122. const divergent = loopRequest({
  123. model: 'm',
  124. messages: Object.freeze([{ role: 'user', content: [{ type: 'text', text: 'phantom' }] }]),
  125. sessionId: session.id,
  126. })
  127. expect(() => { dispatch(ctx, divergent) }).toThrow(/diverges from the dispatch-time durable derivation/)
  128. })
  129. })