projection-store.spec.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /**
  2. * Projection value store (push model; session-projection subsystem page:
  3. * docs/subsystems/session-projection.md): the single
  4. * higher-seq-wins rule on both paths (a stale baseline cannot overwrite a
  5. * newer push frame; a replayed frame cannot regress), capability absence as
  6. * undefined, generation truncation, and the Session/manager wiring (tail-page
  7. * seeding, session/projection frame routing pre- and post-instantiation, the
  8. * list rows' title projection).
  9. */
  10. import { describe, expect, it } from 'vitest'
  11. import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
  12. import { ProjectionValueStore } from '../src/client/sessions/projection-store.ts'
  13. import { Session } from '../src/client/sessions/session.ts'
  14. import { SessionManager } from '../src/client/sessions/manager.ts'
  15. import { FakeApiClient, ok } from './fake-api.ts'
  16. import { entries, plainTurn } from './event-script.ts'
  17. // Test-domain keys merged into the projection map (the Service Definition package's
  18. // pure-type outlet), the same way domain host plugins merge theirs.
  19. declare module '@deepseek-ai/dsh-session-projection/types' {
  20. interface SessionProjectionMap {
  21. 'test/marks': { marks: string[] }
  22. }
  23. }
  24. const SID = 'fk-s1' as SessionId
  25. describe('ProjectionValueStore semantics', () => {
  26. it('reads undefined until a value lands (capability absence)', () => {
  27. const store = new ProjectionValueStore()
  28. expect(store.get('test/marks')).toBeUndefined()
  29. expect(store.faceOf('test/marks').getSnapshot()).toBeUndefined()
  30. })
  31. it('applies frames last-wins by seq: replayed and stale frames drop', () => {
  32. const store = new ProjectionValueStore()
  33. store.apply('test/marks', { marks: ['a'] }, 5)
  34. store.apply('test/marks', { marks: ['a', 'b'] }, 9)
  35. expect(store.get('test/marks')).toEqual({ marks: ['a', 'b'] })
  36. store.apply('test/marks', { marks: ['stale'] }, 5)
  37. store.apply('test/marks', { marks: ['equal'] }, 9)
  38. expect(store.get('test/marks')).toEqual({ marks: ['a', 'b'] })
  39. })
  40. it('a stale baseline can neither overwrite nor clear a newer frame; a fresh one reseeds and clears', () => {
  41. const store = new ProjectionValueStore()
  42. store.apply('test/marks', { marks: ['frame-20'] }, 20)
  43. // Stale cut: carried key loses to the newer frame; omitted key survives.
  44. store.seed({ asOfSeq: 10, values: { 'test/marks': { marks: ['baseline-10'] } } })
  45. expect(store.get('test/marks')).toEqual({ marks: ['frame-20'] })
  46. store.seed({ asOfSeq: 15, values: {} })
  47. expect(store.get('test/marks')).toEqual({ marks: ['frame-20'] })
  48. // Fresh cut: carried key reseeds…
  49. store.seed({ asOfSeq: 30, values: { 'test/marks': { marks: ['baseline-30'] } } })
  50. expect(store.get('test/marks')).toEqual({ marks: ['baseline-30'] })
  51. // …and an omitting fresh cut clears (capability absent as of the cut).
  52. store.seed({ asOfSeq: 40, values: {} })
  53. expect(store.get('test/marks')).toBeUndefined()
  54. })
  55. it('truncate drops rows past the durable baseline and keeps the rest', () => {
  56. const store = new ProjectionValueStore()
  57. store.apply('test/marks', { marks: ['durable'] }, 5)
  58. store.apply('other', 'phantom', 50)
  59. store.truncate(10)
  60. expect(store.get('test/marks')).toEqual({ marks: ['durable'] })
  61. expect(store.get('other')).toBeUndefined()
  62. })
  63. it('notifies the key face on change (batched) and not on dropped applications', async () => {
  64. const store = new ProjectionValueStore()
  65. let keyTicks = 0
  66. let anyTicks = 0
  67. store.faceOf('test/marks').subscribe(() => { keyTicks += 1 })
  68. store.subscribeAny(() => { anyTicks += 1 })
  69. store.apply('test/marks', { marks: ['a'] }, 5)
  70. await Promise.resolve()
  71. expect(keyTicks).toBe(1)
  72. expect(anyTicks).toBe(1)
  73. store.apply('test/marks', { marks: ['replay'] }, 3)
  74. await Promise.resolve()
  75. expect(keyTicks).toBe(1)
  76. expect(anyTicks).toBe(1)
  77. })
  78. it('faces are identity-stable per key (the React binding cache premise)', () => {
  79. const store = new ProjectionValueStore()
  80. expect(store.faceOf('test/marks')).toBe(store.faceOf('test/marks'))
  81. })
  82. it('publishes one reference-stable whole-value snapshot until a row changes', () => {
  83. const store = new ProjectionValueStore()
  84. const empty = store.values()
  85. expect(store.values()).toBe(empty)
  86. store.apply('test/marks', { marks: ['a'] }, 1)
  87. const populated = store.values()
  88. expect(populated).toEqual({ 'test/marks': { marks: ['a'] } })
  89. expect(populated).not.toBe(empty)
  90. expect(store.values()).toBe(populated)
  91. })
  92. })
  93. describe('Session tail-page seeding', () => {
  94. it('seeds the store from a history response carrying a projections block', async () => {
  95. const api = new FakeApiClient()
  96. const session = new Session(SID, api)
  97. api.onHistory = () => Promise.resolve(ok({
  98. events: entries(plainTurn(0, 0, '问', '答')) as never[], hasMore: false,
  99. projections: { asOfSeq: 5, values: { 'test/marks': { marks: ['from-baseline'] } } },
  100. } as never))
  101. await session.open()
  102. expect(session.projections.get('test/marks')).toEqual({ marks: ['from-baseline'] })
  103. })
  104. it('a resync serving a stale block keeps the newer pushed value (seq rule end to end)', async () => {
  105. const api = new FakeApiClient()
  106. const session = new Session(SID, api)
  107. api.onHistory = () => Promise.resolve(ok({
  108. events: entries(plainTurn(0, 0, 'a', 'b')) as never[], hasMore: false,
  109. projections: { asOfSeq: 5, values: { 'test/marks': { marks: ['baseline'] } } },
  110. } as never))
  111. await session.open()
  112. session.projections.apply('test/marks', { marks: ['pushed-9'] }, 9)
  113. await session.resync()
  114. expect(session.projections.get('test/marks')).toEqual({ marks: ['pushed-9'] })
  115. })
  116. it('treats a blockless response as no reset: pushed values survive', async () => {
  117. const api = new FakeApiClient()
  118. const session = new Session(SID, api)
  119. api.onHistory = () => Promise.resolve(ok({ events: entries(plainTurn(0, 0, 'a', 'b')) as never[], hasMore: false }))
  120. await session.open()
  121. session.projections.apply('test/marks', { marks: ['pushed'] }, 9)
  122. await session.resync()
  123. expect(session.projections.get('test/marks')).toEqual({ marks: ['pushed'] })
  124. })
  125. })
  126. describe('manager frame routing', () => {
  127. const sid = (s: string): SessionId => s as SessionId
  128. it('lands session/projection frames before instantiation and the Session adopts the same store', async () => {
  129. const api = new FakeApiClient()
  130. const manager = new SessionManager(api)
  131. manager.handleMuxEnvelope({
  132. rpcId: 'p1' as never,
  133. payload: { type: 'session/projection', sessionId: sid('s1'), key: 'test/marks', value: { marks: ['early'] }, seq: 7 } as never,
  134. })
  135. const session = manager.get(sid('s1'))
  136. expect(session.projections.get('test/marks')).toEqual({ marks: ['early'] })
  137. // Frames after instantiation land in the same store.
  138. manager.handleMuxEnvelope({
  139. rpcId: 'p2' as never,
  140. payload: { type: 'session/projection', sessionId: sid('s1'), key: 'test/marks', value: { marks: ['later'] }, seq: 9 } as never,
  141. })
  142. expect(session.projections.get('test/marks')).toEqual({ marks: ['later'] })
  143. })
  144. it('projects the title key into list rows and truncates phantom rows on the subscribed baseline', async () => {
  145. const api = new FakeApiClient()
  146. const manager = new SessionManager(api)
  147. api.onList = () => Promise.resolve(ok({
  148. items: [{ sessionId: sid('s1'), updatedAt: 1, running: false, blank: false }],
  149. }) as never)
  150. await manager.refreshList()
  151. manager.handleMuxEnvelope({
  152. rpcId: 't1' as never,
  153. payload: { type: 'session/projection', sessionId: sid('s1'), key: 'title', value: 'Projected title', seq: 4 } as never,
  154. })
  155. await Promise.resolve()
  156. expect(manager.getListSnapshot().items[0]?.title).toBe('Projected title')
  157. // The durable baseline says the host only knows up to seq 2: the row rode
  158. // lost state and must drop (the un-flushed title precedent).
  159. manager.handleMuxEnvelope({
  160. rpcId: 'sub' as never,
  161. payload: { type: 'session/subscribed', sessionId: sid('s1'), lastSeq: 2 } as never,
  162. })
  163. await Promise.resolve()
  164. expect(manager.getListSnapshot().items[0]?.title).toBeUndefined()
  165. })
  166. it('projects every retained value into list rows with stable snapshot identity', async () => {
  167. const api = new FakeApiClient()
  168. const manager = new SessionManager(api)
  169. api.onList = () => Promise.resolve(ok({
  170. items: [{
  171. sessionId: sid('s1'), updatedAt: 1, running: false, blank: false,
  172. projections: {
  173. asOfSeq: 2,
  174. values: { 'test/marks': { marks: ['baseline'] } },
  175. },
  176. }],
  177. }) as never)
  178. await manager.refreshList()
  179. const baseline = manager.getListSnapshot().items[0]?.projectionValues
  180. expect(baseline).toEqual({ 'test/marks': { marks: ['baseline'] } })
  181. expect(manager.getListSnapshot().items[0]?.projectionValues).toBe(baseline)
  182. manager.handleMuxEnvelope({
  183. rpcId: 'p2' as never,
  184. payload: {
  185. type: 'session/projection', sessionId: sid('s1'), key: 'test/marks',
  186. value: { marks: ['live'] }, seq: 3,
  187. } as never,
  188. })
  189. await Promise.resolve()
  190. expect(manager.getListSnapshot().items[0]?.projectionValues)
  191. .toEqual({ 'test/marks': { marks: ['live'] } })
  192. expect(manager.getListSnapshot().items[0]?.projectionValues).not.toBe(baseline)
  193. })
  194. it('drops the projection store with the removed session', async () => {
  195. const api = new FakeApiClient()
  196. const manager = new SessionManager(api)
  197. api.onList = () => Promise.resolve(ok({
  198. items: [{ sessionId: sid('s1'), updatedAt: 1, running: false, blank: false }],
  199. }) as never)
  200. await manager.refreshList()
  201. manager.handleMuxEnvelope({
  202. rpcId: 't1' as never,
  203. payload: { type: 'session/projection', sessionId: sid('s1'), key: 'title', value: 'Doomed', seq: 4 } as never,
  204. })
  205. manager.handleHostEnvelope({
  206. rpcId: 'rm' as never,
  207. payload: { type: 'host/session-removed', sessionId: sid('s1') } as never,
  208. })
  209. expect(manager.get(sid('s1')).projections.get('title')).toBeUndefined()
  210. })
  211. })