properties.spec.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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, ToolCallId , 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. stream: [],
  35. message: createMessage({
  36. role: 'assistant',
  37. content,
  38. source: { kind: 'model', provider: 'mock', model: 'mock' },
  39. }),
  40. },
  41. intent: { surfaceOp: 'append' },
  42. })),
  43. textContentArb.map((content): Appendable => ({
  44. type: 'assistant/message',
  45. data: {
  46. turn: 1,
  47. step: 1,
  48. stream: [],
  49. message: createMessage({
  50. role: 'assistant',
  51. content,
  52. source: { kind: 'model', provider: 'mock', model: 'mock' },
  53. }),
  54. usage: { inputTokens: 1, outputTokens: 1 },
  55. },
  56. intent: { surfaceOp: 'append' },
  57. })),
  58. fc.record({ id: fc.string({ minLength: 1 }), content: textContentArb, isError: fc.boolean() })
  59. .map((r): Appendable => ({ type: 'tool/result', data: {
  60. turn: 1, step: 1,
  61. message: createToolResultMessage({
  62. callId: ToolCallId(r.id),
  63. content: r.content,
  64. isError: r.isError,
  65. }),
  66. }, intent: { surfaceOp: 'append' } })),
  67. )
  68. // A non-message event (trace/replay data — must NOT affect derived history).
  69. const nonMessageEventArb: fc.Arbitrary<Appendable> = fc.oneof(
  70. fc.constant<Appendable>({ type: 'turn/start', data: { turn: 1 } }),
  71. fc.constant<Appendable>({ type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } }),
  72. fc.constant<Appendable>({ type: 'step/start', data: { turn: 1, step: 1 } }),
  73. fc.constant<Appendable>({ type: 'step/end', data: { turn: 1, step: 1 } }),
  74. fc.string().map((text): Appendable => ({
  75. type: 'assistant/attempt',
  76. data: { turn: 1, step: 1, stream: [{ type: 'text-chunks', time0: 1, index: 0, dt: [], texts: [text] }] },
  77. })),
  78. )
  79. const anyEventArb = fc.oneof(messageEventArb, nonMessageEventArb)
  80. const logArb = fc.array(anyEventArb, { maxLength: 25 })
  81. let counter = 0
  82. function build(events: Appendable[]): Session {
  83. const session = Session.create(SessionId(`prop-${counter++}`))
  84. for (const e of events) {
  85. // Forward the generated intent verbatim; non-surface events carry none.
  86. if (e.intent !== undefined) session.append(e.type, e.data, e.intent)
  87. else session.append(e.type, e.data)
  88. }
  89. return session
  90. }
  91. describe('Session properties', () => {
  92. it('deriveMessages is deterministic (same log → identical derivation)', () => {
  93. fc.assert(fc.property(logArb, (events) => {
  94. const a = build(events)
  95. expect(a.deriveMessages()).toEqual(a.deriveMessages())
  96. }))
  97. })
  98. it('seq is strictly monotonic and zero-based contiguous', () => {
  99. fc.assert(fc.property(logArb, (events) => {
  100. const session = build(events)
  101. session.snapshotEvents().forEach((event, i) => { expect(event.seq).toBe(i) })
  102. expect(session.seq).toBe(events.length)
  103. }))
  104. })
  105. it('replay-from-seed reproduces the derivation identically', () => {
  106. fc.assert(fc.property(logArb, (events) => {
  107. const original = build(events)
  108. const replayed = Session.create(SessionId(`replay-${counter++}`), original.snapshotEvents())
  109. expect(replayed.deriveMessages()).toEqual(original.deriveMessages())
  110. // Every explicit replay grows by exactly one log-only boundary.
  111. expect(replayed.snapshotEvents().slice(0, original.seq)).toEqual(original.snapshotEvents())
  112. expect(replayed.seq).toBe(original.seq + 1)
  113. }))
  114. })
  115. it('replaying a log that already ends in end-seed adds no further marker', () => {
  116. fc.assert(fc.property(logArb, (events) => {
  117. const original = build(events)
  118. const once = Session.create(SessionId(`idem-a-${counter++}`), original.snapshotEvents())
  119. const twice = Session.create(SessionId(`idem-b-${counter++}`), once.snapshotEvents())
  120. // Lazy resume makes browsing a pickup, so this must not grow per open.
  121. expect(twice.snapshotEvents()).toEqual(once.snapshotEvents())
  122. }))
  123. })
  124. it('non-message events never affect derived history (any interleaving)', () => {
  125. fc.assert(fc.property(
  126. fc.array(messageEventArb, { maxLength: 12 }),
  127. fc.array(nonMessageEventArb, { maxLength: 12 }),
  128. // An arbitrary merge of the two streams that PRESERVES each stream's
  129. // relative order (a random interleaving, not a fixed alternation).
  130. fc.infiniteStream(fc.boolean()),
  131. (messages, noise, pick) => {
  132. const clean = build(messages).deriveMessages()
  133. const interleaved: Appendable[] = []
  134. let mi = 0
  135. let ni = 0
  136. const picker = pick[Symbol.iterator]()
  137. while (mi < messages.length || ni < noise.length) {
  138. // take from noise when chosen and available, else from messages
  139. const takeNoise = ni < noise.length && (mi >= messages.length || picker.next().value === true)
  140. if (takeNoise) { interleaved.push(noise[ni]!); ni++ }
  141. else { interleaved.push(messages[mi]!); mi++ }
  142. }
  143. const withNoise = build(interleaved).deriveMessages()
  144. expect(withNoise).toEqual(clean)
  145. },
  146. ))
  147. })
  148. it('every derived message has a known role and is frozen (append-only contract)', () => {
  149. fc.assert(fc.property(logArb, (events) => {
  150. const session = build(events)
  151. const messages = session.deriveMessages()
  152. const before = structuredClone(session.snapshotEvents())
  153. for (const m of messages) {
  154. expect(['user', 'assistant', 'system']).toContain(m.role)
  155. // Derived messages are frozen shared projections: mutation THROWS
  156. // (strict mode) instead of relying on per-call clones for isolation.
  157. expect(Object.isFrozen(m)).toBe(true)
  158. expect(() => { m.content.push({ type: 'text', text: 'mutation' }) }).toThrow(TypeError)
  159. }
  160. expect(session.snapshotEvents()).toEqual(before)
  161. }))
  162. })
  163. })