properties.spec.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /**
  2. * Property-based tests for the Session event log (the property-testing Agent Note).
  3. *
  4. * Generates arbitrary event logs and asserts the derivation invariants the
  5. * agent loop and replay depend on: deriveMessages is deterministic and
  6. * replay-from-seed reproduces it; seq is strictly monotonic; non-message
  7. * events never affect derived history.
  8. */
  9. import { describe, expect, it } from 'vitest'
  10. import fc from 'fast-check'
  11. import { createUserMessage, CallId , createMessage, createToolResultMessage } from '@deepseek-ai/dsh-llm'
  12. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  13. import type { SessionEventMap, SessionEventType, SurfaceIntent } from '@deepseek-ai/dsh-session'
  14. // Each arbitrary supplies its own surface intent; `build` must not synthesize
  15. // one or the property would fail to exercise malformed fixture choices.
  16. type Appendable = {
  17. [T in SessionEventType]: { type: T; data: SessionEventMap[T]; intent?: SurfaceIntent }
  18. }[SessionEventType]
  19. const textContentArb = fc.array(
  20. fc.record({ type: fc.constant<'text'>('text'), text: fc.string() }),
  21. { maxLength: 3 },
  22. )
  23. // A message-producing event (these DO affect derived history). Each carries an
  24. // explicit `surfaceOp: 'append'` intent — the marker the real loop passes.
  25. const messageEventArb: fc.Arbitrary<Appendable> = fc.oneof(
  26. textContentArb.map((content): Appendable => ({ type: 'user/message', data: createUserMessage({
  27. content, source: { kind: 'user' },
  28. }), intent: { surfaceOp: 'append' } })),
  29. textContentArb.map((content): Appendable => ({
  30. type: 'assistant/message',
  31. data: {
  32. turn: 1,
  33. step: 1,
  34. message: createMessage({
  35. role: 'assistant',
  36. content,
  37. source: { kind: 'model', provider: 'mock', model: 'mock' },
  38. }),
  39. },
  40. intent: { surfaceOp: 'append' },
  41. })),
  42. textContentArb.map((content): Appendable => ({
  43. type: 'assistant/message',
  44. data: {
  45. turn: 1,
  46. step: 1,
  47. message: createMessage({
  48. role: 'assistant',
  49. content,
  50. source: { kind: 'model', provider: 'mock', model: 'mock' },
  51. }),
  52. usage: { inputTokens: 1, outputTokens: 1 },
  53. },
  54. intent: { surfaceOp: 'append' },
  55. })),
  56. fc.record({ id: fc.string({ minLength: 1 }), content: textContentArb, isError: fc.boolean() })
  57. .map((r): Appendable => ({ type: 'tool/result', data: {
  58. turn: 1, step: 1,
  59. message: createToolResultMessage({
  60. callId: CallId(r.id),
  61. content: r.content,
  62. isError: r.isError,
  63. }),
  64. }, intent: { surfaceOp: 'append' } })),
  65. )
  66. // A non-message event (trace/replay data — must NOT affect derived history).
  67. const nonMessageEventArb: fc.Arbitrary<Appendable> = fc.oneof(
  68. fc.constant<Appendable>({ type: 'turn/start', data: { turn: 1 } }),
  69. fc.constant<Appendable>({ type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } }),
  70. fc.constant<Appendable>({ type: 'step/start', data: { turn: 1, step: 1 } }),
  71. fc.constant<Appendable>({ type: 'step/end', data: { turn: 1, step: 1 } }),
  72. fc.string().map((text): Appendable => ({ type: 'assistant/chunk', data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text } } })),
  73. )
  74. const anyEventArb = fc.oneof(messageEventArb, nonMessageEventArb)
  75. const logArb = fc.array(anyEventArb, { maxLength: 25 })
  76. let counter = 0
  77. function build(events: Appendable[]): Session {
  78. const session = Session.create(SessionId(`prop-${counter++}`))
  79. for (const e of events) {
  80. // Forward the generated intent verbatim; non-surface events carry none.
  81. if (e.intent !== undefined) session.append(e.type, e.data, e.intent)
  82. else session.append(e.type, e.data)
  83. }
  84. return session
  85. }
  86. describe('Session properties', () => {
  87. it('deriveMessages is deterministic (same log → identical derivation)', () => {
  88. fc.assert(fc.property(logArb, (events) => {
  89. const a = build(events)
  90. expect(a.deriveMessages()).toEqual(a.deriveMessages())
  91. }))
  92. })
  93. it('seq is strictly monotonic and zero-based contiguous', () => {
  94. fc.assert(fc.property(logArb, (events) => {
  95. const session = build(events)
  96. session.events.forEach((event, i) => { expect(event.seq).toBe(i) })
  97. expect(session.seq).toBe(events.length)
  98. }))
  99. })
  100. it('replay-from-seed reproduces the derivation identically', () => {
  101. fc.assert(fc.property(logArb, (events) => {
  102. const original = build(events)
  103. const replayed = Session.create(SessionId(`replay-${counter++}`), [...original.events])
  104. expect(replayed.deriveMessages()).toEqual(original.deriveMessages())
  105. // Every explicit replay grows by exactly one log-only boundary.
  106. expect(replayed.events.slice(0, original.seq)).toEqual(original.events)
  107. expect(replayed.seq).toBe(original.seq + 1)
  108. }))
  109. })
  110. it('replaying a log that already ends in end-seed adds no further marker', () => {
  111. fc.assert(fc.property(logArb, (events) => {
  112. const original = build(events)
  113. const once = Session.create(SessionId(`idem-a-${counter++}`), [...original.events])
  114. const twice = Session.create(SessionId(`idem-b-${counter++}`), [...once.events])
  115. // Lazy resume makes browsing a pickup, so this must not grow per open.
  116. expect(twice.events).toEqual(once.events)
  117. }))
  118. })
  119. it('non-message events never affect derived history (any interleaving)', () => {
  120. fc.assert(fc.property(
  121. fc.array(messageEventArb, { maxLength: 12 }),
  122. fc.array(nonMessageEventArb, { maxLength: 12 }),
  123. // An arbitrary merge of the two streams that PRESERVES each stream's
  124. // relative order (a random interleaving, not a fixed alternation).
  125. fc.infiniteStream(fc.boolean()),
  126. (messages, noise, pick) => {
  127. const clean = build(messages).deriveMessages()
  128. const interleaved: Appendable[] = []
  129. let mi = 0
  130. let ni = 0
  131. const picker = pick[Symbol.iterator]()
  132. while (mi < messages.length || ni < noise.length) {
  133. // take from noise when chosen and available, else from messages
  134. const takeNoise = ni < noise.length && (mi >= messages.length || picker.next().value === true)
  135. if (takeNoise) { interleaved.push(noise[ni]!); ni++ }
  136. else { interleaved.push(messages[mi]!); mi++ }
  137. }
  138. const withNoise = build(interleaved).deriveMessages()
  139. expect(withNoise).toEqual(clean)
  140. },
  141. ))
  142. })
  143. it('every derived message has a known role and is frozen (append-only contract)', () => {
  144. fc.assert(fc.property(logArb, (events) => {
  145. const session = build(events)
  146. const messages = session.deriveMessages()
  147. const before = structuredClone(session.events)
  148. for (const m of messages) {
  149. expect(['user', 'assistant', 'system']).toContain(m.role)
  150. // Derived messages are frozen shared projections: mutation THROWS
  151. // (strict mode) instead of relying on per-call clones for isolation.
  152. expect(Object.isFrozen(m)).toBe(true)
  153. expect(() => { m.content.push({ type: 'text', text: 'mutation' }) }).toThrow(TypeError)
  154. }
  155. expect(session.events).toEqual(before)
  156. }))
  157. })
  158. })