@webex/plugin-meetings 3.12.0-next.17 → 3.12.0-next.170

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/.sdd/manifest.json +1312 -0
  2. package/.sdd/templates/.source.json +30 -0
  3. package/.sdd/templates/component-repo/module-docs/module-spec-quality.md +111 -0
  4. package/.sdd/templates/component-repo/module-docs/module-spec.template.md +321 -0
  5. package/.sdd/templates/component-repo/reference-docs/adr/_adr-example.md +59 -0
  6. package/.sdd/templates/component-repo/reference-docs/patterns/_pattern-example.md +49 -0
  7. package/.sdd/templates/component-repo/reference-docs/rules/_rule-example.md +42 -0
  8. package/.sdd/templates/component-repo/standing-docs/AGENTS.template.md +120 -0
  9. package/.sdd/templates/component-repo/standing-docs/ARCHITECTURE.template.md +206 -0
  10. package/.sdd/templates/component-repo/standing-docs/CONTRACTS.template.md +90 -0
  11. package/.sdd/templates/component-repo/standing-docs/DATA_MODEL.template.md +68 -0
  12. package/.sdd/templates/component-repo/standing-docs/GETTING_STARTED.template.md +111 -0
  13. package/.sdd/templates/component-repo/standing-docs/GLOSSARY.template.md +57 -0
  14. package/.sdd/templates/component-repo/standing-docs/REVIEW_CHECKLIST.template.md +69 -0
  15. package/.sdd/templates/component-repo/standing-docs/RULES.template.md +96 -0
  16. package/.sdd/templates/component-repo/standing-docs/SECURITY.template.md +84 -0
  17. package/.sdd/templates/component-repo/standing-docs/SERVICE_STATE.template.md +82 -0
  18. package/.sdd/templates/component-repo/standing-docs/SPEC_INDEX.template.md +94 -0
  19. package/.sdd/templates/component-repo/standing-docs/TEST_INDEX.template.md +64 -0
  20. package/.sdd/templates/component-repo/template-map.json +112 -0
  21. package/AGENTS.md +135 -0
  22. package/ai-docs/ARCHITECTURE.md +207 -0
  23. package/ai-docs/CONTRACTS.md +267 -0
  24. package/ai-docs/DATA_MODEL.md +64 -0
  25. package/ai-docs/GETTING_STARTED.md +73 -0
  26. package/ai-docs/GLOSSARY.md +56 -0
  27. package/ai-docs/REVIEW_CHECKLIST.md +45 -0
  28. package/ai-docs/RULES.md +79 -0
  29. package/ai-docs/SECURITY.md +74 -0
  30. package/ai-docs/SERVICE_STATE.md +59 -0
  31. package/ai-docs/SPEC_INDEX.md +85 -0
  32. package/ai-docs/TEST_INDEX.md +45 -0
  33. package/ai-docs/adr/0001-migrate-existing-docs-into-sdd.md +61 -0
  34. package/ai-docs/patterns/defensive-error-propagation.md +55 -0
  35. package/ai-docs/patterns/event-scope-emission.md +46 -0
  36. package/ai-docs/patterns/source-to-test-path-mirroring.md +45 -0
  37. package/ai-docs/patterns/stateless-plugin-request-classes.md +53 -0
  38. package/ai-docs/patterns/typed-constants-and-enum-values.md +47 -0
  39. package/dist/aiEnableRequest/index.js +15 -2
  40. package/dist/aiEnableRequest/index.js.map +1 -1
  41. package/dist/annotation/index.js +2 -2
  42. package/dist/annotation/index.js.map +1 -1
  43. package/dist/breakouts/breakout.js +8 -3
  44. package/dist/breakouts/breakout.js.map +1 -1
  45. package/dist/breakouts/events.js +29 -14
  46. package/dist/breakouts/events.js.map +1 -1
  47. package/dist/breakouts/index.js +99 -4
  48. package/dist/breakouts/index.js.map +1 -1
  49. package/dist/common/errors/webex-errors.js +49 -5
  50. package/dist/common/errors/webex-errors.js.map +1 -1
  51. package/dist/config.js +2 -2
  52. package/dist/config.js.map +1 -1
  53. package/dist/constants.js +37 -10
  54. package/dist/constants.js.map +1 -1
  55. package/dist/controls-options-manager/index.js +46 -10
  56. package/dist/controls-options-manager/index.js.map +1 -1
  57. package/dist/hashTree/constants.js +4 -1
  58. package/dist/hashTree/constants.js.map +1 -1
  59. package/dist/hashTree/hashTreeParser.js +1096 -391
  60. package/dist/hashTree/hashTreeParser.js.map +1 -1
  61. package/dist/hashTree/utils.js +20 -0
  62. package/dist/hashTree/utils.js.map +1 -1
  63. package/dist/index.js +7 -0
  64. package/dist/index.js.map +1 -1
  65. package/dist/interceptors/dataChannelAuthToken.js +75 -15
  66. package/dist/interceptors/dataChannelAuthToken.js.map +1 -1
  67. package/dist/interceptors/locusRetry.js +24 -9
  68. package/dist/interceptors/locusRetry.js.map +1 -1
  69. package/dist/interpretation/index.js +55 -12
  70. package/dist/interpretation/index.js.map +1 -1
  71. package/dist/interpretation/interpretation.types.js +7 -0
  72. package/dist/interpretation/interpretation.types.js.map +1 -0
  73. package/dist/interpretation/siLanguage.js +1 -1
  74. package/dist/locus-info/controlsUtils.js +4 -1
  75. package/dist/locus-info/controlsUtils.js.map +1 -1
  76. package/dist/locus-info/index.js +615 -176
  77. package/dist/locus-info/index.js.map +1 -1
  78. package/dist/locus-info/infoUtils.js +36 -5
  79. package/dist/locus-info/infoUtils.js.map +1 -1
  80. package/dist/locus-info/types.js +20 -0
  81. package/dist/locus-info/types.js.map +1 -1
  82. package/dist/media/MediaConnectionAwaiter.js +15 -2
  83. package/dist/media/MediaConnectionAwaiter.js.map +1 -1
  84. package/dist/media/index.js +8 -2
  85. package/dist/media/index.js.map +1 -1
  86. package/dist/media/properties.js +4 -5
  87. package/dist/media/properties.js.map +1 -1
  88. package/dist/meeting/in-meeting-actions.js +5 -1
  89. package/dist/meeting/in-meeting-actions.js.map +1 -1
  90. package/dist/meeting/index.js +1684 -835
  91. package/dist/meeting/index.js.map +1 -1
  92. package/dist/meeting/locusMediaRequest.js +229 -82
  93. package/dist/meeting/locusMediaRequest.js.map +1 -1
  94. package/dist/meeting/muteState.js +10 -1
  95. package/dist/meeting/muteState.js.map +1 -1
  96. package/dist/meeting/request.js +5 -2
  97. package/dist/meeting/request.js.map +1 -1
  98. package/dist/meeting/util.js +37 -3
  99. package/dist/meeting/util.js.map +1 -1
  100. package/dist/meeting/voicea-meeting.js +2 -1
  101. package/dist/meeting/voicea-meeting.js.map +1 -1
  102. package/dist/meeting-info/meeting-info-v2.js +12 -5
  103. package/dist/meeting-info/meeting-info-v2.js.map +1 -1
  104. package/dist/meetings/index.js +300 -128
  105. package/dist/meetings/index.js.map +1 -1
  106. package/dist/meetings/meetings.types.js +6 -1
  107. package/dist/meetings/meetings.types.js.map +1 -1
  108. package/dist/meetings/request.js +39 -0
  109. package/dist/meetings/request.js.map +1 -1
  110. package/dist/meetings/util.js +116 -18
  111. package/dist/meetings/util.js.map +1 -1
  112. package/dist/member/index.js +10 -0
  113. package/dist/member/index.js.map +1 -1
  114. package/dist/member/types.js.map +1 -1
  115. package/dist/member/util.js +30 -0
  116. package/dist/member/util.js.map +1 -1
  117. package/dist/members/index.js +101 -43
  118. package/dist/members/index.js.map +1 -1
  119. package/dist/members/util.js +8 -1
  120. package/dist/members/util.js.map +1 -1
  121. package/dist/metrics/constants.js +7 -1
  122. package/dist/metrics/constants.js.map +1 -1
  123. package/dist/multistream/codec/constants.js +63 -0
  124. package/dist/multistream/codec/constants.js.map +1 -0
  125. package/dist/multistream/mediaRequestManager.js +62 -15
  126. package/dist/multistream/mediaRequestManager.js.map +1 -1
  127. package/dist/multistream/receiveSlot.js +9 -0
  128. package/dist/multistream/receiveSlot.js.map +1 -1
  129. package/dist/multistream/remoteMediaManager.js +32 -4
  130. package/dist/multistream/remoteMediaManager.js.map +1 -1
  131. package/dist/reachability/clusterReachability.js.map +1 -1
  132. package/dist/reachability/index.js +121 -83
  133. package/dist/reachability/index.js.map +1 -1
  134. package/dist/reachability/reachability.types.js +2 -0
  135. package/dist/reachability/reachability.types.js.map +1 -1
  136. package/dist/reachability/util.js +45 -0
  137. package/dist/reachability/util.js.map +1 -1
  138. package/dist/reactions/reactions.type.js.map +1 -1
  139. package/dist/recording-controller/index.js +1 -3
  140. package/dist/recording-controller/index.js.map +1 -1
  141. package/dist/roap/turnDiscovery.js +8 -1
  142. package/dist/roap/turnDiscovery.js.map +1 -1
  143. package/dist/types/common/errors/webex-errors.d.ts +32 -2
  144. package/dist/types/config.d.ts +2 -2
  145. package/dist/types/constants.d.ts +13 -1
  146. package/dist/types/controls-options-manager/index.d.ts +16 -0
  147. package/dist/types/hashTree/constants.d.ts +1 -0
  148. package/dist/types/hashTree/hashTreeParser.d.ts +201 -22
  149. package/dist/types/hashTree/utils.d.ts +7 -0
  150. package/dist/types/index.d.ts +3 -0
  151. package/dist/types/interceptors/locusRetry.d.ts +4 -4
  152. package/dist/types/interpretation/interpretation.types.d.ts +10 -0
  153. package/dist/types/locus-info/index.d.ts +106 -8
  154. package/dist/types/locus-info/infoUtils.d.ts +8 -0
  155. package/dist/types/locus-info/types.d.ts +22 -1
  156. package/dist/types/media/MediaConnectionAwaiter.d.ts +10 -1
  157. package/dist/types/media/properties.d.ts +6 -2
  158. package/dist/types/meeting/in-meeting-actions.d.ts +4 -0
  159. package/dist/types/meeting/index.d.ts +178 -11
  160. package/dist/types/meeting/locusMediaRequest.d.ts +12 -0
  161. package/dist/types/meeting/request.d.ts +1 -0
  162. package/dist/types/meeting/util.d.ts +9 -0
  163. package/dist/types/meeting-info/meeting-info-v2.d.ts +1 -0
  164. package/dist/types/meetings/index.d.ts +40 -19
  165. package/dist/types/meetings/meetings.types.d.ts +15 -0
  166. package/dist/types/meetings/request.d.ts +14 -0
  167. package/dist/types/member/index.d.ts +1 -0
  168. package/dist/types/member/types.d.ts +1 -0
  169. package/dist/types/member/util.d.ts +9 -0
  170. package/dist/types/members/index.d.ts +15 -2
  171. package/dist/types/members/util.d.ts +1 -5
  172. package/dist/types/metrics/constants.d.ts +6 -0
  173. package/dist/types/multistream/codec/constants.d.ts +7 -0
  174. package/dist/types/multistream/mediaRequestManager.d.ts +22 -5
  175. package/dist/types/multistream/remoteMediaManager.d.ts +18 -0
  176. package/dist/types/reachability/clusterReachability.d.ts +3 -3
  177. package/dist/types/reachability/index.d.ts +10 -3
  178. package/dist/types/reachability/reachability.types.d.ts +7 -0
  179. package/dist/types/reachability/util.d.ts +17 -0
  180. package/dist/types/reactions/reactions.type.d.ts +3 -0
  181. package/dist/webinar/index.js +307 -161
  182. package/dist/webinar/index.js.map +1 -1
  183. package/package.json +23 -23
  184. package/src/aiEnableRequest/ai-docs/ai-enable-request-spec.md +223 -0
  185. package/src/aiEnableRequest/index.ts +16 -0
  186. package/src/annotation/ai-docs/annotation-spec.md +236 -0
  187. package/src/annotation/index.ts +6 -4
  188. package/src/breakouts/ai-docs/breakouts-spec.md +324 -0
  189. package/src/breakouts/breakout.ts +3 -1
  190. package/src/breakouts/events.ts +33 -11
  191. package/src/breakouts/index.ts +122 -2
  192. package/src/common/errors/webex-errors.ts +50 -3
  193. package/src/config.ts +2 -2
  194. package/src/constants.ts +21 -3
  195. package/src/controls-options-manager/ai-docs/controls-options-manager-spec.md +243 -0
  196. package/src/controls-options-manager/index.ts +62 -10
  197. package/src/hashTree/ai-docs/hash-tree-spec.md +267 -0
  198. package/src/hashTree/constants.ts +7 -0
  199. package/src/hashTree/hashTreeParser.ts +861 -193
  200. package/src/hashTree/utils.ts +19 -0
  201. package/src/index.ts +6 -0
  202. package/src/interceptors/ai-docs/interceptors-spec.md +247 -0
  203. package/src/interceptors/dataChannelAuthToken.ts +88 -12
  204. package/src/interceptors/locusRetry.ts +26 -5
  205. package/src/interpretation/ai-docs/interpretation-spec.md +256 -0
  206. package/src/interpretation/index.ts +65 -10
  207. package/src/interpretation/interpretation.types.ts +11 -0
  208. package/src/locus-info/ai-docs/locus-info-spec.md +293 -0
  209. package/src/locus-info/controlsUtils.ts +3 -1
  210. package/src/locus-info/index.ts +566 -164
  211. package/src/locus-info/infoUtils.ts +41 -6
  212. package/src/locus-info/types.ts +26 -1
  213. package/src/media/MediaConnectionAwaiter.ts +21 -4
  214. package/src/media/ai-docs/media-spec.md +267 -0
  215. package/src/media/index.ts +10 -1
  216. package/src/media/properties.ts +8 -3
  217. package/src/meeting/ai-docs/meeting-spec.md +401 -0
  218. package/src/meeting/in-meeting-actions.ts +8 -0
  219. package/src/meeting/index.ts +944 -120
  220. package/src/meeting/locusMediaRequest.ts +106 -6
  221. package/src/meeting/muteState.ts +10 -1
  222. package/src/meeting/request.ts +11 -0
  223. package/src/meeting/util.ts +51 -7
  224. package/src/meeting/voicea-meeting.ts +1 -1
  225. package/src/meeting-info/ai-docs/meeting-info-spec.md +261 -0
  226. package/src/meeting-info/meeting-info-v2.ts +11 -4
  227. package/src/meetings/ai-docs/meetings-spec.md +296 -0
  228. package/src/meetings/index.ts +200 -80
  229. package/src/meetings/meetings.types.ts +19 -0
  230. package/src/meetings/request.ts +43 -0
  231. package/src/meetings/util.ts +117 -4
  232. package/src/member/ai-docs/member-spec.md +196 -0
  233. package/src/member/index.ts +10 -0
  234. package/src/member/types.ts +1 -0
  235. package/src/member/util.ts +29 -0
  236. package/src/members/ai-docs/members-spec.md +256 -0
  237. package/src/members/index.ts +70 -7
  238. package/src/members/util.ts +12 -4
  239. package/src/metrics/ai-docs/metrics-spec.md +185 -0
  240. package/src/metrics/constants.ts +6 -0
  241. package/src/multistream/ai-docs/multistream-spec.md +292 -0
  242. package/src/multistream/codec/constants.ts +58 -0
  243. package/src/multistream/mediaRequestManager.ts +119 -28
  244. package/src/multistream/receiveSlot.ts +18 -0
  245. package/src/multistream/remoteMediaManager.ts +23 -1
  246. package/src/personal-meeting-room/ai-docs/personal-meeting-room-spec.md +234 -0
  247. package/src/reachability/ai-docs/reachability-spec.md +261 -0
  248. package/src/reachability/clusterReachability.ts +3 -2
  249. package/src/reachability/index.ts +47 -16
  250. package/src/reachability/reachability.types.ts +11 -0
  251. package/src/reachability/util.ts +36 -0
  252. package/src/reactions/ai-docs/reactions-spec.md +198 -0
  253. package/src/reactions/reactions.type.ts +3 -0
  254. package/src/reconnection-manager/ai-docs/reconnection-manager-spec.md +272 -0
  255. package/src/recording-controller/ai-docs/recording-controller-spec.md +223 -0
  256. package/src/recording-controller/index.ts +1 -2
  257. package/src/roap/ai-docs/roap-spec.md +241 -0
  258. package/src/roap/turnDiscovery.ts +9 -1
  259. package/src/webinar/ai-docs/webinar-spec.md +243 -0
  260. package/src/webinar/index.ts +216 -38
  261. package/test/unit/spec/aiEnableRequest/index.ts +86 -0
  262. package/test/unit/spec/annotation/index.ts +3 -3
  263. package/test/unit/spec/breakouts/breakout.ts +9 -3
  264. package/test/unit/spec/breakouts/events.ts +120 -2
  265. package/test/unit/spec/breakouts/index.ts +223 -3
  266. package/test/unit/spec/common/errors/webex-errors.ts +78 -0
  267. package/test/unit/spec/controls-options-manager/index.js +139 -32
  268. package/test/unit/spec/hashTree/hashTreeParser.ts +2451 -184
  269. package/test/unit/spec/hashTree/utils.ts +37 -0
  270. package/test/unit/spec/interceptors/dataChannelAuthToken.ts +196 -0
  271. package/test/unit/spec/interceptors/locusRetry.ts +234 -5
  272. package/test/unit/spec/interpretation/index.ts +119 -4
  273. package/test/unit/spec/locus-info/controlsUtils.js +172 -57
  274. package/test/unit/spec/locus-info/index.js +1014 -58
  275. package/test/unit/spec/locus-info/infoUtils.js +184 -1
  276. package/test/unit/spec/media/MediaConnectionAwaiter.ts +55 -0
  277. package/test/unit/spec/media/index.ts +92 -0
  278. package/test/unit/spec/media/properties.ts +23 -23
  279. package/test/unit/spec/meeting/in-meeting-actions.ts +4 -0
  280. package/test/unit/spec/meeting/index.js +2834 -110
  281. package/test/unit/spec/meeting/locusMediaRequest.ts +406 -4
  282. package/test/unit/spec/meeting/muteState.js +81 -0
  283. package/test/unit/spec/meeting/request.js +12 -0
  284. package/test/unit/spec/meeting/utils.js +189 -17
  285. package/test/unit/spec/meeting/voicea-meeting.ts +85 -1
  286. package/test/unit/spec/meeting-info/meetinginfov2.js +88 -11
  287. package/test/unit/spec/meetings/index.js +544 -49
  288. package/test/unit/spec/meetings/request.js +141 -0
  289. package/test/unit/spec/meetings/utils.js +402 -51
  290. package/test/unit/spec/member/index.js +7 -0
  291. package/test/unit/spec/member/util.js +89 -0
  292. package/test/unit/spec/members/index.js +216 -0
  293. package/test/unit/spec/members/request.js +37 -1
  294. package/test/unit/spec/members/utils.js +63 -0
  295. package/test/unit/spec/multistream/mediaRequestManager.ts +501 -37
  296. package/test/unit/spec/multistream/remoteMediaManager.ts +46 -0
  297. package/test/unit/spec/reachability/index.ts +128 -46
  298. package/test/unit/spec/reachability/util.ts +31 -0
  299. package/test/unit/spec/recording-controller/index.js +9 -8
  300. package/test/unit/spec/roap/turnDiscovery.ts +20 -0
  301. package/test/unit/spec/webinar/index.ts +332 -31
@@ -1,12 +1,19 @@
1
1
  import HashTreeParser, {
2
2
  LocusInfoUpdateType,
3
3
  MeetingEndedError,
4
+ LocusNotFoundError,
5
+ SyncAllBackoffType,
4
6
  } from '@webex/plugin-meetings/src/hashTree/hashTreeParser';
5
7
  import HashTree from '@webex/plugin-meetings/src/hashTree/hashTree';
6
8
  import {expect} from '@webex/test-helper-chai';
7
9
  import sinon from 'sinon';
8
10
  import {assert} from '@webex/test-helper-chai';
9
11
  import {EMPTY_HASH} from '@webex/plugin-meetings/src/hashTree/constants';
12
+ import testUtils from '@webex/plugin-meetings/test/utils/testUtils';
13
+ import { some } from 'lodash';
14
+ import Metrics from '@webex/plugin-meetings/src/metrics';
15
+ import BEHAVIORAL_METRICS from '@webex/plugin-meetings/src/metrics/constants';
16
+ import LoggerProxy from '@webex/plugin-meetings/src/common/logs/logger-proxy';
10
17
 
11
18
  const visibleDataSetsUrl = 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/visibleDataSets';
12
19
 
@@ -111,6 +118,7 @@ function createDataSet(name: string, leafCount: number, version = 1) {
111
118
  name,
112
119
  idleMs: 1000,
113
120
  backoff: {maxMs: 1000, exponent: 2},
121
+ heartbeatIntervalMs: 5000,
114
122
  };
115
123
  }
116
124
 
@@ -151,31 +159,47 @@ describe('HashTreeParser', () => {
151
159
  let webexRequest: sinon.SinonStub;
152
160
  let callback: sinon.SinonStub;
153
161
  let mathRandomStub: sinon.SinonStub;
162
+ let metricsStub: sinon.SinonStub;
163
+ let loggerInfoStub: sinon.SinonStub;
154
164
 
155
165
  beforeEach(() => {
156
166
  clock = sinon.useFakeTimers();
157
167
  webexRequest = sinon.stub();
158
168
  callback = sinon.stub();
159
169
  mathRandomStub = sinon.stub(Math, 'random').returns(0);
170
+ metricsStub = sinon.stub(Metrics, 'sendBehavioralMetric');
171
+ loggerInfoStub = sinon.stub(LoggerProxy.logger, 'info');
160
172
  });
161
173
  afterEach(() => {
162
174
  clock.restore();
163
175
  mathRandomStub.restore();
176
+ metricsStub.restore();
177
+ loggerInfoStub.restore();
164
178
  });
165
179
 
166
180
  // Helper to create a HashTreeParser instance with common defaults
167
181
  function createHashTreeParser(
168
182
  initialLocus: any = exampleInitialLocus,
169
183
  metadata: any = exampleMetadata,
170
- excludedDataSets?: string[]
184
+ excludedDataSets?: string[],
185
+ syncLatencyTracker?: any,
186
+ syncLatencyMeetingId = 'meeting-1',
187
+ generateTrackingId?: any,
188
+ isLlmExpected?: () => boolean
171
189
  ) {
172
190
  return new HashTreeParser({
173
191
  initialLocus,
174
192
  metadata,
175
193
  webexRequest,
176
- locusInfoUpdateCallback: callback,
194
+ callbacks: {
195
+ locusInfoUpdateCallback: callback,
196
+ syncLatencyTracker,
197
+ generateTrackingId,
198
+ isLlmExpected,
199
+ },
177
200
  debugId: 'test',
178
201
  excludedDataSets,
202
+ syncLatencyMeetingId,
179
203
  });
180
204
  }
181
205
 
@@ -216,7 +240,7 @@ describe('HashTreeParser', () => {
216
240
  }
217
241
 
218
242
  // Helper to mock sendSyncRequestToLocus response
219
- function mockSendSyncRequestResponse(dataSetUrl: string, response: any) {
243
+ function mockSendSyncRequestResponse(dataSetUrl: string, response: any, headers?: any) {
220
244
  webexRequest
221
245
  .withArgs(
222
246
  sinon.match({
@@ -226,6 +250,7 @@ describe('HashTreeParser', () => {
226
250
  )
227
251
  .resolves({
228
252
  body: response,
253
+ headers,
229
254
  });
230
255
  }
231
256
 
@@ -566,6 +591,11 @@ describe('HashTreeParser', () => {
566
591
  },
567
592
  data: {info: {id: 'some-fake-locus-info'}},
568
593
  },
594
+ ],
595
+ });
596
+
597
+ assert.calledWith(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
598
+ updatedObjects: [
569
599
  {
570
600
  htMeta: {
571
601
  elementId: {
@@ -631,6 +661,32 @@ describe('HashTreeParser', () => {
631
661
  expect(syncCalls[2].args[0].uri).to.equal(`${atdActiveDataSet.url}/sync`);
632
662
  });
633
663
 
664
+ it('sends leafCount=1 with a single empty leaf for initialization sync, regardless of actual dataset leafCount', async () => {
665
+ const parser = createHashTreeParser({dataSets: [], locus: null}, null);
666
+
667
+ // Use a dataset with leafCount=16 to verify the initialization sync always uses leafCount=1
668
+ const mainDataSet = createDataSet('main', 16, 1100);
669
+
670
+ mockGetAllDataSetsMetadata(webexRequest, visibleDataSetsUrl, [mainDataSet]);
671
+ mockSyncRequest(webexRequest, mainDataSet.url);
672
+
673
+ await parser.initializeFromMessage({
674
+ dataSets: [],
675
+ visibleDataSetsUrl,
676
+ locusUrl,
677
+ });
678
+
679
+ assert.calledWith(webexRequest, {
680
+ method: 'POST',
681
+ uri: `${mainDataSet.url}/sync`,
682
+ qs: {rootHash: sinon.match.string},
683
+ body: {
684
+ leafCount: 1,
685
+ leafDataEntries: [{leafIndex: 0, elementIds: []}],
686
+ },
687
+ });
688
+ });
689
+
634
690
  it('handles sync response that has locusStateElements undefined', async () => {
635
691
  const minimalInitialLocus = {
636
692
  dataSets: [],
@@ -671,8 +727,11 @@ describe('HashTreeParser', () => {
671
727
  assert.notCalled(callback);
672
728
  });
673
729
 
674
- [404, 409].forEach((errorCode) => {
675
- it(`emits MeetingEndedError if getting visible datasets returns ${errorCode}`, async () => {
730
+ [
731
+ {errorCode: 404, expectedError: LocusNotFoundError},
732
+ {errorCode: 409, expectedError: MeetingEndedError},
733
+ ].forEach(({errorCode, expectedError}) => {
734
+ it(`throws ${expectedError.name} if getting visible datasets returns ${errorCode}`, async () => {
676
735
  const minimalInitialLocus = {
677
736
  dataSets: [],
678
737
  locus: null,
@@ -695,7 +754,6 @@ describe('HashTreeParser', () => {
695
754
  )
696
755
  .rejects(error);
697
756
 
698
- // initializeFromMessage should throw MeetingEndedError
699
757
  let thrownError;
700
758
  try {
701
759
  await parser.initializeFromMessage({
@@ -707,7 +765,7 @@ describe('HashTreeParser', () => {
707
765
  thrownError = e;
708
766
  }
709
767
 
710
- expect(thrownError).to.be.instanceOf(MeetingEndedError);
768
+ expect(thrownError).to.be.instanceOf(expectedError);
711
769
  });
712
770
  });
713
771
  });
@@ -1729,12 +1787,122 @@ describe('HashTreeParser', () => {
1729
1787
  });
1730
1788
  });
1731
1789
 
1732
- describe('emits MEETING_ENDED', () => {
1733
- [404, 409].forEach((statusCode) => {
1734
- it(`when /hashtree returns ${statusCode}`, async () => {
1790
+ it('filters a "main" sync response down to the requested dataset, ignoring shared datasets like "unjoined"', async () => {
1791
+ // Set up a parser where both "main" and "unjoined" are visible and share the core locus
1792
+ // element (they always advance to the same version on the server).
1793
+ const sharedInitialLocus = {
1794
+ dataSets: [createDataSet('main', 16, 1000), createDataSet('unjoined', 16, 1000)],
1795
+ locus: {
1796
+ url: locusUrl,
1797
+ htMeta: {
1798
+ elementId: {type: 'locus', id: 0, version: 200},
1799
+ dataSetNames: ['main', 'unjoined'],
1800
+ },
1801
+ links: {resources: {visibleDataSets: {url: visibleDataSetsUrl}}},
1802
+ participants: [],
1803
+ },
1804
+ };
1805
+ const sharedMetadata = {
1806
+ htMeta: {elementId: {type: 'metadata', id: 5, version: 50}, dataSetNames: ['self']},
1807
+ visibleDataSets: [
1808
+ {name: 'main', url: `${locusUrl}/datasets/main`},
1809
+ {name: 'unjoined', url: `${locusUrl}/datasets/unjoined`},
1810
+ ],
1811
+ };
1812
+
1813
+ const parser = createHashTreeParser(sharedInitialLocus, sharedMetadata);
1814
+
1815
+ // both datasets have their own hash tree, sharing the locus element
1816
+ assert.exists(parser.dataSets.main.hashTree);
1817
+ assert.exists(parser.dataSets.unjoined.hashTree);
1818
+
1819
+ // start the sync timer with a normal "main" message (mismatched root hash)
1820
+ const message = {
1821
+ dataSets: [{...createDataSet('main', 16, 1100), root: 'a'.repeat(32)}],
1822
+ visibleDataSetsUrl,
1823
+ locusUrl,
1824
+ locusStateElements: [
1825
+ {
1826
+ htMeta: {
1827
+ elementId: {type: 'locus' as const, id: 0, version: 201},
1828
+ dataSetNames: ['main'],
1829
+ },
1830
+ data: {info: {id: 'initial-update'}},
1831
+ },
1832
+ ],
1833
+ };
1834
+ parser.handleMessage(message, 'initial message');
1835
+ assert.calledOnce(callback);
1836
+ callback.resetHistory();
1837
+
1838
+ const mainDataSetUrl = parser.dataSets.main.url;
1839
+
1840
+ mockGetHashesFromLocusResponse(
1841
+ mainDataSetUrl,
1842
+ new Array(16).fill('0'.repeat(32)),
1843
+ createDataSet('main', 16, 1101)
1844
+ );
1845
+
1846
+ // The sync response for "main" also carries the "unjoined" dataset, the shared locus
1847
+ // element tagged with both datasets, and an "unjoined"-only element - all of which must
1848
+ // be filtered out so that only the requested "main" data is processed.
1849
+ const mainSyncDataSet = createDataSet('main', 16, 1101);
1850
+ mainSyncDataSet.root = parser.dataSets.main.hashTree.getRootHash();
1851
+ mockSendSyncRequestResponse(mainDataSetUrl, {
1852
+ dataSets: [mainSyncDataSet, createDataSet('unjoined', 16, 1101)],
1853
+ visibleDataSetsUrl,
1854
+ locusUrl,
1855
+ locusStateElements: [
1856
+ {
1857
+ htMeta: {
1858
+ elementId: {type: 'locus' as const, id: 0, version: 202},
1859
+ dataSetNames: ['main', 'unjoined'],
1860
+ },
1861
+ data: {info: {id: 'synced-shared-locus'}},
1862
+ },
1863
+ {
1864
+ htMeta: {
1865
+ elementId: {type: 'participant' as const, id: 99, version: 500},
1866
+ dataSetNames: ['unjoined'],
1867
+ },
1868
+ data: {person: {name: 'unjoined-only'}},
1869
+ },
1870
+ ],
1871
+ });
1872
+
1873
+ await clock.tickAsync(1000);
1874
+
1875
+ // the "unjoined" dataset info must NOT be updated from a "main" sync response
1876
+ expect(parser.dataSets.unjoined.version).to.equal(1000);
1877
+
1878
+ // the shared locus element is reported exactly once (not once per dataset), and the
1879
+ // "unjoined"-only element is not reported at all
1880
+ assert.calledOnceWithExactly(callback, {
1881
+ updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
1882
+ updatedObjects: [
1883
+ {
1884
+ htMeta: {
1885
+ elementId: {type: 'locus', id: 0, version: 202},
1886
+ dataSetNames: ['main', 'unjoined'],
1887
+ },
1888
+ data: {info: {id: 'synced-shared-locus'}},
1889
+ },
1890
+ ],
1891
+ });
1892
+
1893
+ // the filtered-out dataset and element are logged
1894
+ assert.calledWith(
1895
+ loggerInfoStub,
1896
+ sinon.match(
1897
+ 'keeping only dataset "main", filtering out datasets: [unjoined:1101], elements: [participant:99:500]'
1898
+ )
1899
+ );
1900
+ });
1901
+
1902
+ describe('emits MEETING_ENDED when 409/2403004 is returned', () => {
1903
+ it('when /hashtree returns 409', async () => {
1735
1904
  const parser = createHashTreeParser();
1736
1905
 
1737
- // Send a message to trigger sync algorithm
1738
1906
  const message = {
1739
1907
  dataSets: [createDataSet('main', 16, 1100)],
1740
1908
  visibleDataSetsUrl,
@@ -1759,12 +1927,9 @@ describe('HashTreeParser', () => {
1759
1927
 
1760
1928
  const mainDataSetUrl = parser.dataSets.main.url;
1761
1929
 
1762
- // Mock getHashesFromLocus to reject with the sentinel error
1763
- const error: any = new Error(`Request failed with status ${statusCode}`);
1764
- error.statusCode = statusCode;
1765
- if (statusCode === 409) {
1766
- error.body = {errorCode: 2403004};
1767
- }
1930
+ const error: any = new Error('Request failed with status 409');
1931
+ error.statusCode = 409;
1932
+ error.body = {errorCode: 2403004};
1768
1933
  webexRequest
1769
1934
  .withArgs(
1770
1935
  sinon.match({
@@ -1774,23 +1939,22 @@ describe('HashTreeParser', () => {
1774
1939
  )
1775
1940
  .rejects(error);
1776
1941
 
1777
- // Trigger sync by advancing time
1778
1942
  await clock.tickAsync(1000);
1779
1943
 
1780
- // Verify callback was called with MEETING_ENDED
1781
1944
  assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1782
1945
 
1783
- // Verify all timers are stopped
1784
1946
  Object.values(parser.dataSets).forEach((ds: any) => {
1785
1947
  assert.isUndefined(ds.timer);
1786
1948
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1787
1949
  });
1950
+
1951
+ // Verify no sync failure metric was sent for end-meeting sentinel
1952
+ assert.notCalled(metricsStub);
1788
1953
  });
1789
1954
 
1790
- it(`when /sync returns ${statusCode}`, async () => {
1955
+ it('when /sync returns 409', async () => {
1791
1956
  const parser = createHashTreeParser();
1792
1957
 
1793
- // Send a message to trigger sync algorithm
1794
1958
  const message = {
1795
1959
  dataSets: [createDataSet('main', 16, 1100)],
1796
1960
  visibleDataSetsUrl,
@@ -1815,19 +1979,15 @@ describe('HashTreeParser', () => {
1815
1979
 
1816
1980
  const mainDataSetUrl = parser.dataSets.main.url;
1817
1981
 
1818
- // Mock getHashesFromLocus to succeed
1819
1982
  mockGetHashesFromLocusResponse(
1820
1983
  mainDataSetUrl,
1821
1984
  new Array(16).fill('00000000000000000000000000000000'),
1822
1985
  createDataSet('main', 16, 1101)
1823
1986
  );
1824
1987
 
1825
- // Mock sendSyncRequestToLocus to reject with the sentinel error
1826
- const error: any = new Error(`Request failed with status ${statusCode}`);
1827
- error.statusCode = statusCode;
1828
- if (statusCode === 409) {
1829
- error.body = {errorCode: 2403004};
1830
- }
1988
+ const error: any = new Error('Request failed with status 409');
1989
+ error.statusCode = 409;
1990
+ error.body = {errorCode: 2403004};
1831
1991
  webexRequest
1832
1992
  .withArgs(
1833
1993
  sinon.match({
@@ -1837,19 +1997,130 @@ describe('HashTreeParser', () => {
1837
1997
  )
1838
1998
  .rejects(error);
1839
1999
 
1840
- // Trigger sync by advancing time
1841
2000
  await clock.tickAsync(1000);
1842
2001
 
1843
- // Verify callback was called with MEETING_ENDED
1844
2002
  assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1845
2003
 
2004
+ Object.values(parser.dataSets).forEach((ds: any) => {
2005
+ assert.isUndefined(ds.timer);
2006
+ assert.isUndefined(ds.heartbeatWatchdogTimer);
2007
+ });
2008
+ });
2009
+ });
2010
+
2011
+ describe('emits LOCUS_NOT_FOUND and stops parser when 404 is returned', () => {
2012
+ it('when /hashtree returns 404', async () => {
2013
+ const parser = createHashTreeParser();
2014
+
2015
+ const message = {
2016
+ dataSets: [createDataSet('main', 16, 1100)],
2017
+ visibleDataSetsUrl,
2018
+ locusUrl,
2019
+ locusStateElements: [
2020
+ {
2021
+ htMeta: {
2022
+ elementId: {
2023
+ type: 'locus' as const,
2024
+ id: 0,
2025
+ version: 201,
2026
+ },
2027
+ dataSetNames: ['main'],
2028
+ },
2029
+ data: {info: {id: 'initial-update'}},
2030
+ },
2031
+ ],
2032
+ };
2033
+
2034
+ parser.handleMessage(message, 'initial message');
2035
+ callback.resetHistory();
2036
+
2037
+ const mainDataSetUrl = parser.dataSets.main.url;
2038
+
2039
+ const error: any = new Error('Request failed with status 404');
2040
+ error.statusCode = 404;
2041
+ webexRequest
2042
+ .withArgs(
2043
+ sinon.match({
2044
+ method: 'GET',
2045
+ uri: `${mainDataSetUrl}/hashtree`,
2046
+ })
2047
+ )
2048
+ .rejects(error);
2049
+
2050
+ await clock.tickAsync(1000);
2051
+
2052
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
2053
+
2054
+ // Verify parser is stopped
2055
+ expect(parser.state).to.equal('stopped');
2056
+
1846
2057
  // Verify all timers are stopped
1847
2058
  Object.values(parser.dataSets).forEach((ds: any) => {
1848
2059
  assert.isUndefined(ds.timer);
1849
2060
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1850
2061
  });
1851
2062
  });
1852
- });
2063
+
2064
+ it('when /sync returns 404', async () => {
2065
+ const parser = createHashTreeParser();
2066
+
2067
+ const message = {
2068
+ dataSets: [createDataSet('main', 16, 1100)],
2069
+ visibleDataSetsUrl,
2070
+ locusUrl,
2071
+ locusStateElements: [
2072
+ {
2073
+ htMeta: {
2074
+ elementId: {
2075
+ type: 'locus' as const,
2076
+ id: 0,
2077
+ version: 201,
2078
+ },
2079
+ dataSetNames: ['main'],
2080
+ },
2081
+ data: {info: {id: 'initial-update'}},
2082
+ },
2083
+ ],
2084
+ };
2085
+
2086
+ parser.handleMessage(message, 'initial message');
2087
+ callback.resetHistory();
2088
+
2089
+ const mainDataSetUrl = parser.dataSets.main.url;
2090
+
2091
+ mockGetHashesFromLocusResponse(
2092
+ mainDataSetUrl,
2093
+ new Array(16).fill('00000000000000000000000000000000'),
2094
+ createDataSet('main', 16, 1101)
2095
+ );
2096
+
2097
+ const error: any = new Error('Request failed with status 404');
2098
+ error.statusCode = 404;
2099
+ webexRequest
2100
+ .withArgs(
2101
+ sinon.match({
2102
+ method: 'POST',
2103
+ uri: `${mainDataSetUrl}/sync`,
2104
+ })
2105
+ )
2106
+ .rejects(error);
2107
+
2108
+ await clock.tickAsync(1000);
2109
+
2110
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
2111
+
2112
+ // Verify parser is stopped
2113
+ expect(parser.state).to.equal('stopped');
2114
+
2115
+ // Verify all timers are stopped
2116
+ Object.values(parser.dataSets).forEach((ds: any) => {
2117
+ assert.isUndefined(ds.timer);
2118
+ assert.isUndefined(ds.heartbeatWatchdogTimer);
2119
+ });
2120
+
2121
+ // Verify no sync failure metric was sent for end-meeting sentinel
2122
+ assert.notCalled(metricsStub);
2123
+ });
1853
2124
  });
1854
2125
 
1855
2126
  it('requests only mismatched hashes during sync', async () => {
@@ -2020,63 +2291,284 @@ describe('HashTreeParser', () => {
2020
2291
  },
2021
2292
  });
2022
2293
  });
2023
- });
2024
2294
 
2025
- describe('handles visible data sets changes correctly', () => {
2026
- it('handles addition of visible data set (one that does not require async initialization)', async () => {
2027
- // Create a parser with visible datasets
2295
+ it('restarts the sync timer when sync response is empty so that a future sync can be triggered', async () => {
2028
2296
  const parser = createHashTreeParser();
2029
2297
 
2030
- // Stub updateItems on self hash tree to return true
2031
- sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2032
-
2033
- // Send a message with Metadata object that has a new visibleDataSets list
2034
- const message = {
2035
- dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
2036
- visibleDataSetsUrl,
2037
- locusUrl,
2038
- locusStateElements: [
2298
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2299
+ const heartbeatMessage = {
2300
+ dataSets: [
2039
2301
  {
2040
- htMeta: {
2041
- elementId: {
2042
- type: 'metadata' as const,
2043
- id: 5,
2044
- version: 51,
2045
- },
2046
- dataSetNames: ['self'],
2047
- },
2048
- data: {
2049
- visibleDataSets: [
2050
- {
2051
- name: 'main',
2052
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2053
- },
2054
- {
2055
- name: 'self',
2056
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2057
- },
2058
- {
2059
- name: 'atd-unmuted',
2060
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2061
- },
2062
- {
2063
- name: 'attendees',
2064
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2065
- },
2066
- ], // added 'attendees'
2067
- },
2302
+ ...createDataSet('main', 16, 1100),
2303
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
2068
2304
  },
2069
2305
  ],
2306
+ visibleDataSetsUrl,
2307
+ locusUrl,
2070
2308
  };
2071
2309
 
2072
- parser.handleMessage(message, 'add visible dataset');
2310
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2073
2311
 
2074
- // Verify that 'attendees' was added to visibleDataSets
2075
- expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2312
+ // The sync timer should be set
2313
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2076
2314
 
2077
- // Verify that a hash tree was created for 'attendees'
2078
- assert.exists(parser.dataSets.attendees.hashTree);
2079
- assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2315
+ // Mock responses for the first sync - return null (204/empty body)
2316
+ const mainDataSetUrl = parser.dataSets.main.url;
2317
+ mockGetHashesFromLocusResponse(
2318
+ mainDataSetUrl,
2319
+ new Array(16).fill('00000000000000000000000000000000'),
2320
+ {
2321
+ ...createDataSet('main', 16, 1101),
2322
+ root: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', // still mismatched
2323
+ }
2324
+ );
2325
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
2326
+
2327
+ // Advance time to fire the sync timer (idleMs=1000 + backoff=0)
2328
+ await clock.tickAsync(1000);
2329
+
2330
+ // Verify sync was triggered
2331
+ assert.calledWith(
2332
+ webexRequest,
2333
+ sinon.match({
2334
+ method: 'POST',
2335
+ uri: `${mainDataSetUrl}/sync`,
2336
+ })
2337
+ );
2338
+
2339
+ // After empty response, runSyncAlgorithm should have been called,
2340
+ // setting a new sync timer as a safety net
2341
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2342
+
2343
+ // Reset and set up mocks for the second sync
2344
+ webexRequest.resetHistory();
2345
+ mockGetHashesFromLocusResponse(
2346
+ mainDataSetUrl,
2347
+ new Array(16).fill('00000000000000000000000000000000'),
2348
+ {
2349
+ ...createDataSet('main', 16, 1102),
2350
+ root: 'cccccccccccccccccccccccccccccccc', // still mismatched
2351
+ }
2352
+ );
2353
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
2354
+
2355
+ // Advance time again to fire the second sync timer
2356
+ await clock.tickAsync(1000);
2357
+
2358
+ // Verify a second sync was triggered
2359
+ assert.calledWith(
2360
+ webexRequest,
2361
+ sinon.match({
2362
+ method: 'POST',
2363
+ uri: `${mainDataSetUrl}/sync`,
2364
+ })
2365
+ );
2366
+ });
2367
+
2368
+ it('updates dataSet.leafCount when hash tree is resized during sync so that the sync request has the correct leafCount', async () => {
2369
+ const parser = createHashTreeParser();
2370
+
2371
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2372
+ const heartbeatMessage = {
2373
+ dataSets: [
2374
+ {
2375
+ ...createDataSet('main', 16, 1100),
2376
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
2377
+ },
2378
+ ],
2379
+ visibleDataSetsUrl,
2380
+ locusUrl,
2381
+ };
2382
+
2383
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2384
+
2385
+ // The sync timer should be set
2386
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2387
+
2388
+ const mainDataSetUrl = parser.dataSets.main.url;
2389
+ const newLeafCount = 32;
2390
+
2391
+ // Mock getHashesFromLocus response with a DIFFERENT leafCount (32 instead of 16)
2392
+ mockGetHashesFromLocusResponse(
2393
+ mainDataSetUrl,
2394
+ new Array(newLeafCount).fill('00000000000000000000000000000000'),
2395
+ createDataSet('main', newLeafCount, 1101)
2396
+ );
2397
+
2398
+ // Mock the sync request - use matching root hash
2399
+ const syncResponseDataSet = createDataSet('main', newLeafCount, 1102);
2400
+ syncResponseDataSet.root = parser.dataSets.main.hashTree.getRootHash();
2401
+ mockSendSyncRequestResponse(mainDataSetUrl, {
2402
+ dataSets: [syncResponseDataSet],
2403
+ visibleDataSetsUrl,
2404
+ locusUrl,
2405
+ locusStateElements: [],
2406
+ });
2407
+
2408
+ // Advance time to fire the sync timer (idleMs=1000 + backoff=0)
2409
+ await clock.tickAsync(1000);
2410
+
2411
+ // Verify the sync request was sent with the NEW leafCount (32), not the old one (16)
2412
+ assert.calledWith(
2413
+ webexRequest,
2414
+ sinon.match({
2415
+ method: 'POST',
2416
+ uri: `${mainDataSetUrl}/sync`,
2417
+ body: sinon.match({
2418
+ leafCount: newLeafCount,
2419
+ }),
2420
+ })
2421
+ );
2422
+ });
2423
+
2424
+ it('sends HASH_TREE_SYNC_FAILURE metric when GET /hashtree request fails', async () => {
2425
+ const parser = createHashTreeParser();
2426
+
2427
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2428
+ const heartbeatMessage = {
2429
+ dataSets: [
2430
+ {
2431
+ ...createDataSet('main', 16, 1100),
2432
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
2433
+ },
2434
+ ],
2435
+ visibleDataSetsUrl,
2436
+ locusUrl,
2437
+ };
2438
+
2439
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2440
+
2441
+ const mainDataSetUrl = parser.dataSets.main.url;
2442
+ const hashTreeError = new Error('server error') as any;
2443
+ hashTreeError.statusCode = 500;
2444
+
2445
+ webexRequest
2446
+ .withArgs(
2447
+ sinon.match({
2448
+ method: 'GET',
2449
+ uri: `${mainDataSetUrl}/hashtree`,
2450
+ })
2451
+ )
2452
+ .rejects(hashTreeError);
2453
+
2454
+ await clock.tickAsync(1000);
2455
+
2456
+ assert.calledOnceWithExactly(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2457
+ debugId: 'test',
2458
+ dataSetName: 'main',
2459
+ request: 'GET /hashtree',
2460
+ statusCode: 500,
2461
+ reason: 'server error',
2462
+ });
2463
+ });
2464
+
2465
+ it('sends HASH_TREE_SYNC_FAILURE metric when POST /sync request fails', async () => {
2466
+ const parser = createHashTreeParser();
2467
+
2468
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2469
+ const heartbeatMessage = {
2470
+ dataSets: [
2471
+ {
2472
+ ...createDataSet('main', 16, 1100),
2473
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
2474
+ },
2475
+ ],
2476
+ visibleDataSetsUrl,
2477
+ locusUrl,
2478
+ };
2479
+
2480
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2481
+
2482
+ const mainDataSetUrl = parser.dataSets.main.url;
2483
+
2484
+ // Mock getHashesFromLocus to succeed
2485
+ mockGetHashesFromLocusResponse(
2486
+ mainDataSetUrl,
2487
+ new Array(16).fill('00000000000000000000000000000000'),
2488
+ createDataSet('main', 16, 1101)
2489
+ );
2490
+
2491
+ // Mock sendSyncRequestToLocus to fail
2492
+ const syncError = new Error('sync failed') as any;
2493
+ syncError.statusCode = 500;
2494
+
2495
+ webexRequest
2496
+ .withArgs(
2497
+ sinon.match({
2498
+ method: 'POST',
2499
+ uri: `${mainDataSetUrl}/sync`,
2500
+ })
2501
+ )
2502
+ .rejects(syncError);
2503
+
2504
+ await clock.tickAsync(1000);
2505
+
2506
+ assert.calledOnceWithExactly(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_SYNC_FAILURE, {
2507
+ debugId: 'test',
2508
+ dataSetName: 'main',
2509
+ request: 'POST /sync',
2510
+ statusCode: 500,
2511
+ reason: 'sync failed',
2512
+ });
2513
+ });
2514
+
2515
+ });
2516
+
2517
+ describe('handles visible data sets changes correctly', () => {
2518
+ it('handles addition of visible data set (one that does not require async initialization)', async () => {
2519
+ // Create a parser with visible datasets
2520
+ const parser = createHashTreeParser();
2521
+
2522
+ // Stub updateItems on self hash tree to return true
2523
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2524
+
2525
+ // Send a message with Metadata object that has a new visibleDataSets list
2526
+ const message = {
2527
+ dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
2528
+ visibleDataSetsUrl,
2529
+ locusUrl,
2530
+ locusStateElements: [
2531
+ {
2532
+ htMeta: {
2533
+ elementId: {
2534
+ type: 'metadata' as const,
2535
+ id: 5,
2536
+ version: 51,
2537
+ },
2538
+ dataSetNames: ['self'],
2539
+ },
2540
+ data: {
2541
+ visibleDataSets: [
2542
+ {
2543
+ name: 'main',
2544
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2545
+ },
2546
+ {
2547
+ name: 'self',
2548
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2549
+ },
2550
+ {
2551
+ name: 'atd-unmuted',
2552
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2553
+ },
2554
+ {
2555
+ name: 'attendees',
2556
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2557
+ },
2558
+ ], // added 'attendees'
2559
+ },
2560
+ },
2561
+ ],
2562
+ };
2563
+
2564
+ parser.handleMessage(message, 'add visible dataset');
2565
+
2566
+ // Verify that 'attendees' was added to visibleDataSets
2567
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2568
+
2569
+ // Verify that a hash tree was created for 'attendees'
2570
+ assert.exists(parser.dataSets.attendees.hashTree);
2571
+ assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2080
2572
 
2081
2573
  // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
2082
2574
  assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
@@ -2291,7 +2783,7 @@ describe('HashTreeParser', () => {
2291
2783
  expect(syncCalls[1].args[0].uri).to.equal(`${newAtdActiveDataSet.url}/sync`);
2292
2784
  });
2293
2785
 
2294
- it('emits MEETING_ENDED if async init of a new visible dataset fails with 404', async () => {
2786
+ it('emits LOCUS_NOT_FOUND if async init of a new visible dataset fails with 404', async () => {
2295
2787
  const parser = createHashTreeParser();
2296
2788
 
2297
2789
  // Stub updateItems on self hash tree to return true
@@ -2356,8 +2848,8 @@ describe('HashTreeParser', () => {
2356
2848
  // Wait for the async initialization (queueMicrotask) to complete
2357
2849
  await clock.tickAsync(0);
2358
2850
 
2359
- // Verify callback was called with MEETING_ENDED
2360
- assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
2851
+ // Verify callback was called with LOCUS_NOT_FOUND (404 means locus URL is stale, not necessarily meeting ended)
2852
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.LOCUS_NOT_FOUND});
2361
2853
  });
2362
2854
 
2363
2855
  it('handles removal of visible data set', async () => {
@@ -2517,58 +3009,208 @@ describe('HashTreeParser', () => {
2517
3009
  // Verify callback was NOT called (no updates for non-visible datasets)
2518
3010
  assert.notCalled(callback);
2519
3011
  });
2520
- });
2521
3012
 
2522
- describe('heartbeat watchdog', () => {
2523
- it('initiates sync immediately only for the specific data set whose heartbeat watchdog fires', async () => {
2524
- const parser = createHashTreeParser();
2525
- const heartbeatIntervalMs = 5000;
3013
+ it('reports update for object that moves from removed visible dataset to new visible dataset even if version is unchanged', async () => {
3014
+ // The purpose of this test is to verify that when an object
3015
+ // moves from one visible dataset to another without version change,
3016
+ // the parser still reports it as an update.
3017
+ // Locus has some additional signalling for this - the "view" property in htMeta.elementId.
3018
+ // When a view changes, the contents of the object may change even if version doesn't.
3019
+ // HashTreeParser doesn't use the "view" property, because it doesn't need to -
3020
+ // the same functionality is achieved thanks to the fact that a new visible data set means
3021
+ // a new hash tree is created, so HashTreeParser still detects the change as new
3022
+ // object is added to the new hash tree.
3023
+
3024
+ // Setup: parser with visible datasets "self" and "unjoined"
3025
+ const unjoinedDataSet = createDataSet('unjoined', 4, 3000);
3026
+ const selfDataSet = createDataSet('self', 1, 2000);
3027
+
3028
+ // start with Locus that has "info" in both "unjoined" and "main" datasets,
3029
+ // but only "unjoined" is visible.
3030
+ const initialLocus = {
3031
+ dataSets: [selfDataSet, unjoinedDataSet],
3032
+ locus: {
3033
+ url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f',
3034
+ links: {resources: {visibleDataSets: {url: visibleDataSetsUrl}}},
3035
+ // info object in "unjoined" dataset with version 500
3036
+ info: {
3037
+ htMeta: {
3038
+ elementId: {
3039
+ type: 'info',
3040
+ id: 42,
3041
+ version: 500,
3042
+ view: ['unjoined'], // not used by our code, but here for completeness - that's what real Locus would send
3043
+ },
3044
+ dataSetNames: ['main', 'unjoined'],
3045
+ },
3046
+ someField: 'some-initial-value',
3047
+ },
3048
+ self: {
3049
+ htMeta: {
3050
+ elementId: {
3051
+ type: 'self',
3052
+ id: 4,
3053
+ version: 100,
3054
+ },
3055
+ dataSetNames: ['self'],
3056
+ },
3057
+ },
3058
+ },
3059
+ };
2526
3060
 
2527
- // Send initial heartbeat message for 'main' only
2528
- const heartbeatMessage = {
2529
- dataSets: [
2530
- {
2531
- ...createDataSet('main', 16, 1100),
2532
- root: parser.dataSets.main.hashTree.getRootHash(),
3061
+ const metadata = {
3062
+ htMeta: {
3063
+ elementId: {
3064
+ type: 'metadata',
3065
+ id: 5,
3066
+ version: 50,
2533
3067
  },
3068
+ dataSetNames: ['self'],
3069
+ },
3070
+ visibleDataSets: [
3071
+ {name: 'self', url: selfDataSet.url},
3072
+ {name: 'unjoined', url: unjoinedDataSet.url},
2534
3073
  ],
2535
- visibleDataSetsUrl,
2536
- locusUrl,
2537
- heartbeatIntervalMs,
2538
3074
  };
2539
3075
 
2540
- parser.handleMessage(heartbeatMessage, 'initial heartbeat');
2541
-
2542
- // Verify only 'main' watchdog timer is set
2543
- expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
2544
- expect(parser.dataSets.self.heartbeatWatchdogTimer).to.be.undefined;
2545
- expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3076
+ const parser = createHashTreeParser(initialLocus, metadata);
2546
3077
 
2547
- // Mock responses for performSync (GET hashtree then POST sync for leafCount > 1)
2548
- const mainDataSetUrl = parser.dataSets.main.url;
2549
- mockGetHashesFromLocusResponse(
2550
- mainDataSetUrl,
2551
- new Array(16).fill('00000000000000000000000000000000'),
2552
- createDataSet('main', 16, 1101)
2553
- );
2554
- mockSendSyncRequestResponse(mainDataSetUrl, null);
3078
+ // Verify initial state: unjoined is visible and has the info object
3079
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'unjoined')).to.be.true;
3080
+ assert.exists(parser.dataSets.unjoined.hashTree);
3081
+ assert.equal(parser.dataSets.unjoined.hashTree?.getItemVersion(42, 'info'), 500);
2555
3082
 
2556
- // Advance time past heartbeatIntervalMs + backoff (Math.random returns 0, so backoff = 0)
2557
- // performSync is called immediately when the watchdog fires - no additional delay
2558
- await clock.tickAsync(heartbeatIntervalMs);
3083
+ // Stub updateItems on self hash tree to return true for metadata update
3084
+ sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2559
3085
 
2560
- // Verify sync request was sent immediately for 'main' (GET hashtree + POST sync)
2561
- assert.calledWith(
2562
- webexRequest,
2563
- sinon.match({
2564
- method: 'GET',
2565
- uri: `${mainDataSetUrl}/hashtree`,
2566
- })
2567
- );
3086
+ // Now send a message that:
3087
+ // 1. Changes visible datasets: removes "unjoined", adds "main"
3088
+ // 2. Contains the same info object (same id=42, same version=500) but we see the view from "main" dataset
3089
+ const mainDataSet = createDataSet('main', 16, 1000);
2568
3090
 
2569
- // Verify no sync requests were sent for other datasets
2570
- assert.neverCalledWith(
2571
- webexRequest,
3091
+ const message = {
3092
+ dataSets: [selfDataSet, mainDataSet],
3093
+ visibleDataSetsUrl,
3094
+ locusUrl,
3095
+ locusStateElements: [
3096
+ {
3097
+ htMeta: {
3098
+ elementId: {
3099
+ type: 'metadata' as const,
3100
+ id: 5,
3101
+ version: 51,
3102
+ },
3103
+ dataSetNames: ['self'],
3104
+ },
3105
+ data: {
3106
+ visibleDataSets: [
3107
+ {name: 'self', url: selfDataSet.url},
3108
+ {name: 'main', url: mainDataSet.url},
3109
+ // "unjoined" is no longer here
3110
+ ],
3111
+ },
3112
+ },
3113
+ {
3114
+ htMeta: {
3115
+ elementId: {
3116
+ type: 'info' as const,
3117
+ id: 42,
3118
+ version: 500, // same version as before
3119
+ view: ['main'], // now points to "main" instead of "unjoined"
3120
+ },
3121
+ dataSetNames: ['main', 'unjoined'], // still in both datasets, but only "main" is visible now
3122
+ },
3123
+ data: {someNewField: 'some-value'},
3124
+ },
3125
+ ],
3126
+ };
3127
+
3128
+ parser.handleMessage(message, 'visible dataset swap with same-version object');
3129
+
3130
+ // Verify "unjoined" is no longer visible and "main" is now visible
3131
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'unjoined')).to.be.false;
3132
+ expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
3133
+
3134
+ // Verify the info object is now in the "main" hash tree
3135
+ assert.exists(parser.dataSets.main.hashTree);
3136
+ assert.equal(parser.dataSets.main.hashTree?.getItemVersion(42, 'info'), 500);
3137
+
3138
+ // The key assertion: callback should be called with the info object update even though
3139
+ // its version hasn't changed - because visible datasets changed (moved from unjoined to main)
3140
+ assert.calledOnce(callback);
3141
+ const callbackArgs = callback.firstCall.args[0];
3142
+ assert.equal(callbackArgs.updateType, LocusInfoUpdateType.OBJECTS_UPDATED);
3143
+
3144
+ // Should contain the info object update (with data)
3145
+ const infoUpdate = callbackArgs.updatedObjects.find(
3146
+ (obj) => obj.htMeta.elementId.type === 'info' && obj.htMeta.elementId.id === 42
3147
+ );
3148
+ assert.exists(infoUpdate);
3149
+ assert.deepEqual(infoUpdate.htMeta.elementId, {
3150
+ type: 'info',
3151
+ id: 42,
3152
+ version: 500,
3153
+ view: ['main'],
3154
+ });
3155
+ assert.deepEqual(infoUpdate.data, {someNewField: 'some-value'});
3156
+ });
3157
+ });
3158
+
3159
+ describe('heartbeat watchdog', () => {
3160
+ it('initiates sync immediately only for the specific data set whose heartbeat watchdog fires', async () => {
3161
+ const parser = createHashTreeParser();
3162
+ const heartbeatIntervalMs = 5000;
3163
+
3164
+ // Send initial heartbeat message for 'main' only
3165
+ const heartbeatMessage = {
3166
+ dataSets: [
3167
+ {
3168
+ ...createDataSet('main', 16, 1100),
3169
+ root: parser.dataSets.main.hashTree.getRootHash(),
3170
+ },
3171
+ ],
3172
+ visibleDataSetsUrl,
3173
+ locusUrl,
3174
+ };
3175
+
3176
+ parser.handleMessage(heartbeatMessage, 'initial heartbeat');
3177
+
3178
+ // Verify only 'main' watchdog timer is set
3179
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3180
+ expect(parser.dataSets.self.heartbeatWatchdogTimer).to.be.undefined;
3181
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3182
+
3183
+ // Mock responses for performSync (GET hashtree then POST sync for leafCount > 1)
3184
+ const mainDataSetUrl = parser.dataSets.main.url;
3185
+ mockGetHashesFromLocusResponse(
3186
+ mainDataSetUrl,
3187
+ new Array(16).fill('00000000000000000000000000000000'),
3188
+ createDataSet('main', 16, 1101)
3189
+ );
3190
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3191
+
3192
+ // Advance time past heartbeatIntervalMs + backoff (Math.random returns 0, so backoff = 0)
3193
+ // performSync is called immediately when the watchdog fires - no additional delay
3194
+ await clock.tickAsync(heartbeatIntervalMs);
3195
+
3196
+ // Verify sync request was sent immediately for 'main' (GET hashtree + POST sync)
3197
+ assert.calledWith(
3198
+ webexRequest,
3199
+ sinon.match({
3200
+ method: 'GET',
3201
+ uri: `${mainDataSetUrl}/hashtree`,
3202
+ })
3203
+ );
3204
+
3205
+ // Verify behavioral metric was sent for the watchdog expiration
3206
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
3207
+ debugId: 'test',
3208
+ dataSetName: 'main',
3209
+ });
3210
+
3211
+ // Verify no sync requests were sent for other datasets
3212
+ assert.neverCalledWith(
3213
+ webexRequest,
2572
3214
  sinon.match({
2573
3215
  method: 'POST',
2574
3216
  uri: `${parser.dataSets.self.url}/sync`,
@@ -2583,6 +3225,106 @@ describe('HashTreeParser', () => {
2583
3225
  );
2584
3226
  });
2585
3227
 
3228
+ it('uses the watchdog random backoff when reporting sync metrics', async () => {
3229
+ const syncLatencyTracker = {
3230
+ saveLatency: sinon.stub(),
3231
+ saveTimestamp: sinon.stub(),
3232
+ getLocusSyncLatency: sinon.stub(),
3233
+ clearLocusSyncLatency: sinon.stub(),
3234
+ completeLocusSyncLatency: sinon.stub(),
3235
+ };
3236
+ const parser = createHashTreeParser(
3237
+ undefined,
3238
+ undefined,
3239
+ undefined,
3240
+ syncLatencyTracker
3241
+ );
3242
+ const heartbeatIntervalMs = 5000;
3243
+ const mainDataSetUrl = parser.dataSets.main.url;
3244
+
3245
+ mathRandomStub.onFirstCall().returns(0.1); // root-hash timer backoff = 10ms
3246
+ mathRandomStub.onSecondCall().returns(0.5); // watchdog backoff = 250ms
3247
+ mathRandomStub.returns(0);
3248
+
3249
+ parser.handleMessage(
3250
+ {
3251
+ dataSets: [
3252
+ {
3253
+ ...createDataSet('main', 16, 1100),
3254
+ root: parser.dataSets.main.hashTree.getRootHash(),
3255
+ },
3256
+ ],
3257
+ visibleDataSetsUrl,
3258
+ locusUrl,
3259
+ },
3260
+ 'initial heartbeat'
3261
+ );
3262
+
3263
+ mockGetHashesFromLocusResponse(
3264
+ mainDataSetUrl,
3265
+ new Array(16).fill('00000000000000000000000000000000'),
3266
+ createDataSet('main', 16, 1101)
3267
+ );
3268
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3269
+
3270
+ await clock.tickAsync(heartbeatIntervalMs + 250);
3271
+
3272
+ assert.calledWithExactly(
3273
+ syncLatencyTracker.saveLatency,
3274
+ 'internal.client.locus.sync.random.backoff',
3275
+ 250,
3276
+ {
3277
+ meetingId: 'meeting-1',
3278
+ dataSetName: 'main',
3279
+ }
3280
+ );
3281
+ });
3282
+
3283
+ it('uses the root sync random backoff when root timer fires before watchdog', async () => {
3284
+ const syncLatencyTracker = {
3285
+ saveLatency: sinon.stub(),
3286
+ saveTimestamp: sinon.stub(),
3287
+ getLocusSyncLatency: sinon.stub(),
3288
+ clearLocusSyncLatency: sinon.stub(),
3289
+ completeLocusSyncLatency: sinon.stub(),
3290
+ };
3291
+ const parser = createHashTreeParser(
3292
+ undefined,
3293
+ undefined,
3294
+ undefined,
3295
+ syncLatencyTracker
3296
+ );
3297
+ const mainDataSetUrl = parser.dataSets.main.url;
3298
+
3299
+ mathRandomStub.onFirstCall().returns(0.1); // root-hash timer backoff = 10ms
3300
+ mathRandomStub.onSecondCall().returns(0.5); // watchdog backoff = 250ms
3301
+ mathRandomStub.returns(0);
3302
+
3303
+ parser.handleMessage(
3304
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
3305
+ 'root mismatch heartbeat'
3306
+ );
3307
+
3308
+ mockGetHashesFromLocusResponse(
3309
+ mainDataSetUrl,
3310
+ new Array(16).fill('00000000000000000000000000000000'),
3311
+ createDataSet('main', 16, 1101)
3312
+ );
3313
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3314
+
3315
+ await clock.tickAsync(1010);
3316
+
3317
+ assert.calledWithExactly(
3318
+ syncLatencyTracker.saveLatency,
3319
+ 'internal.client.locus.sync.random.backoff',
3320
+ 10,
3321
+ {
3322
+ meetingId: 'meeting-1',
3323
+ dataSetName: 'main',
3324
+ }
3325
+ );
3326
+ });
3327
+
2586
3328
  it('calls POST sync directly for leafCount === 1 data sets', async () => {
2587
3329
  const parser = createHashTreeParser();
2588
3330
  const heartbeatIntervalMs = 5000;
@@ -2598,7 +3340,6 @@ describe('HashTreeParser', () => {
2598
3340
  ],
2599
3341
  visibleDataSetsUrl,
2600
3342
  locusUrl,
2601
- heartbeatIntervalMs,
2602
3343
  };
2603
3344
 
2604
3345
  parser.handleMessage(heartbeatMessage, 'self heartbeat');
@@ -2609,6 +3350,12 @@ describe('HashTreeParser', () => {
2609
3350
  // Advance time past watchdog delay
2610
3351
  await clock.tickAsync(heartbeatIntervalMs);
2611
3352
 
3353
+ // Verify behavioral metric was sent for the watchdog expiration
3354
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_HEARTBEAT_WATCHDOG_EXPIRED, {
3355
+ debugId: 'test',
3356
+ dataSetName: 'self',
3357
+ });
3358
+
2612
3359
  // For leafCount === 1, performSync skips GET hashtree and goes straight to POST sync
2613
3360
  assert.neverCalledWith(
2614
3361
  webexRequest,
@@ -2628,7 +3375,6 @@ describe('HashTreeParser', () => {
2628
3375
 
2629
3376
  it('sets watchdog timers for each data set in the message', async () => {
2630
3377
  const parser = createHashTreeParser();
2631
- const heartbeatIntervalMs = 5000;
2632
3378
 
2633
3379
  // Send heartbeat with multiple datasets
2634
3380
  const heartbeatMessage = {
@@ -2645,7 +3391,6 @@ describe('HashTreeParser', () => {
2645
3391
  ],
2646
3392
  visibleDataSetsUrl,
2647
3393
  locusUrl,
2648
- heartbeatIntervalMs,
2649
3394
  };
2650
3395
 
2651
3396
  parser.handleMessage(heartbeatMessage, 'multi-dataset heartbeat');
@@ -2659,7 +3404,6 @@ describe('HashTreeParser', () => {
2659
3404
 
2660
3405
  it('resets the watchdog timer for a specific data set when a new heartbeat for it is received', async () => {
2661
3406
  const parser = createHashTreeParser();
2662
- const heartbeatIntervalMs = 5000;
2663
3407
 
2664
3408
  // Send first heartbeat for 'main'
2665
3409
  const heartbeat1 = {
@@ -2671,7 +3415,6 @@ describe('HashTreeParser', () => {
2671
3415
  ],
2672
3416
  visibleDataSetsUrl,
2673
3417
  locusUrl,
2674
- heartbeatIntervalMs,
2675
3418
  };
2676
3419
 
2677
3420
  parser.handleMessage(heartbeat1, 'first heartbeat');
@@ -2692,7 +3435,6 @@ describe('HashTreeParser', () => {
2692
3435
  ],
2693
3436
  visibleDataSetsUrl,
2694
3437
  locusUrl,
2695
- heartbeatIntervalMs,
2696
3438
  };
2697
3439
 
2698
3440
  parser.handleMessage(heartbeat2, 'second heartbeat');
@@ -2711,7 +3453,6 @@ describe('HashTreeParser', () => {
2711
3453
 
2712
3454
  it('resets the watchdog timer when a normal message (with locusStateElements) is received', async () => {
2713
3455
  const parser = createHashTreeParser();
2714
- const heartbeatIntervalMs = 5000;
2715
3456
 
2716
3457
  // Send initial heartbeat to start the watchdog for 'main'
2717
3458
  const heartbeat = {
@@ -2723,7 +3464,6 @@ describe('HashTreeParser', () => {
2723
3464
  ],
2724
3465
  visibleDataSetsUrl,
2725
3466
  locusUrl,
2726
- heartbeatIntervalMs,
2727
3467
  };
2728
3468
 
2729
3469
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2751,7 +3491,6 @@ describe('HashTreeParser', () => {
2751
3491
  data: {someData: 'value'},
2752
3492
  },
2753
3493
  ],
2754
- heartbeatIntervalMs,
2755
3494
  };
2756
3495
 
2757
3496
  parser.handleMessage(normalMessage, 'normal message');
@@ -2765,21 +3504,212 @@ describe('HashTreeParser', () => {
2765
3504
  const parser = createHashTreeParser();
2766
3505
 
2767
3506
  // Send a heartbeat message without heartbeatIntervalMs
2768
- const heartbeatMessage = createHeartbeatMessage(
2769
- 'main',
2770
- 16,
2771
- 1100,
2772
- parser.dataSets.main.hashTree.getRootHash()
2773
- );
3507
+ const heartbeatMessage = {
3508
+ dataSets: [
3509
+ {
3510
+ ...createDataSet('main', 16, 1100),
3511
+ root: parser.dataSets.main.hashTree.getRootHash(),
3512
+ heartbeatIntervalMs: undefined,
3513
+ },
3514
+ ],
3515
+ visibleDataSetsUrl,
3516
+ locusUrl,
3517
+ };
2774
3518
 
2775
3519
  parser.handleMessage(heartbeatMessage, 'heartbeat without interval');
2776
3520
 
2777
3521
  expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
2778
3522
  });
2779
3523
 
3524
+ it('skips watchdog timers for LLM datasets when current meeting LLM is not expected', async () => {
3525
+ const parser = createHashTreeParser(
3526
+ undefined,
3527
+ undefined,
3528
+ undefined,
3529
+ undefined,
3530
+ 'meeting-1',
3531
+ undefined,
3532
+ () => false
3533
+ );
3534
+
3535
+ const heartbeatMessage = {
3536
+ dataSets: [
3537
+ {
3538
+ ...createDataSet('main', 16, 1100),
3539
+ root: parser.dataSets.main.hashTree.getRootHash(),
3540
+ },
3541
+ {
3542
+ ...createDataSet('self', 1, 2100),
3543
+ url: parser.dataSets.self.url,
3544
+ root: parser.dataSets.self.hashTree.getRootHash(),
3545
+ },
3546
+ {
3547
+ ...createDataSet('atd-unmuted', 16, 3100),
3548
+ url: parser.dataSets['atd-unmuted'].url,
3549
+ root: parser.dataSets['atd-unmuted'].hashTree.getRootHash(),
3550
+ },
3551
+ ],
3552
+ visibleDataSetsUrl,
3553
+ locusUrl,
3554
+ };
3555
+
3556
+ parser.handleMessage(heartbeatMessage, 'heartbeat with meeting-scoped llm not expected');
3557
+
3558
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3559
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3560
+ expect(parser.dataSets.self.heartbeatWatchdogTimer).to.not.be.undefined;
3561
+ });
3562
+
3563
+ it('arms skipped LLM watchdog timers when reevaluateLlmWatchdogs is called after LLM becomes expected', async () => {
3564
+ let llmExpected = false;
3565
+ const parser = createHashTreeParser(
3566
+ undefined,
3567
+ undefined,
3568
+ undefined,
3569
+ undefined,
3570
+ 'meeting-1',
3571
+ undefined,
3572
+ () => llmExpected
3573
+ );
3574
+
3575
+ const heartbeatMessage = {
3576
+ dataSets: [
3577
+ {
3578
+ ...createDataSet('main', 16, 1100),
3579
+ root: parser.dataSets.main.hashTree.getRootHash(),
3580
+ },
3581
+ {
3582
+ ...createDataSet('self', 1, 2100),
3583
+ url: parser.dataSets.self.url,
3584
+ root: parser.dataSets.self.hashTree.getRootHash(),
3585
+ },
3586
+ {
3587
+ ...createDataSet('atd-unmuted', 16, 3100),
3588
+ url: parser.dataSets['atd-unmuted'].url,
3589
+ root: parser.dataSets['atd-unmuted'].hashTree.getRootHash(),
3590
+ },
3591
+ ],
3592
+ visibleDataSetsUrl,
3593
+ locusUrl,
3594
+ };
3595
+
3596
+ // LLM data set messages arrive before LLM is expected, so their watchdogs are skipped
3597
+ parser.handleMessage(heartbeatMessage, 'heartbeat before llm expected');
3598
+
3599
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3600
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3601
+ const selfTimerBefore = parser.dataSets.self.heartbeatWatchdogTimer;
3602
+ expect(selfTimerBefore).to.not.be.undefined;
3603
+
3604
+ // LLM becomes expected and we re-evaluate the watchdogs
3605
+ llmExpected = true;
3606
+ parser.reevaluateLlmWatchdogs();
3607
+
3608
+ // the previously skipped LLM watchdogs are now armed
3609
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3610
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.not.be.undefined;
3611
+ // the self (non-LLM) watchdog timer is left untouched
3612
+ expect(parser.dataSets.self.heartbeatWatchdogTimer).to.equal(selfTimerBefore);
3613
+
3614
+ // the pending set is consumed, so a second call after clearing the timers is a no-op
3615
+ clearTimeout(parser.dataSets.main.heartbeatWatchdogTimer);
3616
+ clearTimeout(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer);
3617
+ parser.dataSets.main.heartbeatWatchdogTimer = undefined;
3618
+ parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer = undefined;
3619
+
3620
+ parser.reevaluateLlmWatchdogs();
3621
+
3622
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3623
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3624
+ });
3625
+
3626
+ it('only arms watchdogs for LLM data sets that were actually received in a message', async () => {
3627
+ let llmExpected = false;
3628
+ const parser = createHashTreeParser(
3629
+ undefined,
3630
+ undefined,
3631
+ undefined,
3632
+ undefined,
3633
+ 'meeting-1',
3634
+ undefined,
3635
+ () => llmExpected
3636
+ );
3637
+
3638
+ // only 'main' is received in a message (atd-unmuted exists in this.dataSets with a hash
3639
+ // tree but is never received in any message)
3640
+ const heartbeatMessage = {
3641
+ dataSets: [
3642
+ {
3643
+ ...createDataSet('main', 16, 1100),
3644
+ root: parser.dataSets.main.hashTree.getRootHash(),
3645
+ },
3646
+ ],
3647
+ visibleDataSetsUrl,
3648
+ locusUrl,
3649
+ };
3650
+
3651
+ parser.handleMessage(heartbeatMessage, 'only main received before llm expected');
3652
+
3653
+ // sanity: atd-unmuted has a hash tree but was never received
3654
+ expect(parser.dataSets['atd-unmuted'].hashTree).to.not.be.undefined;
3655
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3656
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3657
+
3658
+ llmExpected = true;
3659
+ parser.reevaluateLlmWatchdogs();
3660
+
3661
+ // 'main' was received, so its watchdog is armed
3662
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3663
+ // 'atd-unmuted' was never received, so no watchdog is armed even though it has a hash tree
3664
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3665
+ });
3666
+
3667
+ it('does not re-arm or reset an already active LLM watchdog timer when reevaluateLlmWatchdogs is called', async () => {
3668
+ const parser = createHashTreeParser(
3669
+ undefined,
3670
+ undefined,
3671
+ undefined,
3672
+ undefined,
3673
+ 'meeting-1',
3674
+ undefined,
3675
+ () => true
3676
+ );
3677
+
3678
+ parser.handleMessage(
3679
+ createHeartbeatMessage('main', 16, 1100, parser.dataSets.main.hashTree.getRootHash()),
3680
+ 'heartbeat with llm expected'
3681
+ );
3682
+
3683
+ const mainTimerBefore = parser.dataSets.main.heartbeatWatchdogTimer;
3684
+ expect(mainTimerBefore).to.not.be.undefined;
3685
+
3686
+ parser.reevaluateLlmWatchdogs();
3687
+
3688
+ // existing active timer must not be cleared/reset (that would extend its deadline)
3689
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.equal(mainTimerBefore);
3690
+ });
3691
+
3692
+ it('does nothing when reevaluateLlmWatchdogs is called on a stopped parser', async () => {
3693
+ const parser = createHashTreeParser(
3694
+ undefined,
3695
+ undefined,
3696
+ undefined,
3697
+ undefined,
3698
+ 'meeting-1',
3699
+ undefined,
3700
+ () => true
3701
+ );
3702
+
3703
+ parser.stop();
3704
+
3705
+ parser.reevaluateLlmWatchdogs();
3706
+
3707
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3708
+ expect(parser.dataSets['atd-unmuted'].heartbeatWatchdogTimer).to.be.undefined;
3709
+ });
3710
+
2780
3711
  it('stops all watchdog timers when meeting ends via sentinel message', async () => {
2781
3712
  const parser = createHashTreeParser();
2782
- const heartbeatIntervalMs = 5000;
2783
3713
 
2784
3714
  // Send heartbeat for multiple datasets
2785
3715
  const heartbeat = {
@@ -2796,7 +3726,6 @@ describe('HashTreeParser', () => {
2796
3726
  ],
2797
3727
  visibleDataSetsUrl,
2798
3728
  locusUrl,
2799
- heartbeatIntervalMs,
2800
3729
  };
2801
3730
 
2802
3731
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2847,7 +3776,6 @@ describe('HashTreeParser', () => {
2847
3776
  };
2848
3777
 
2849
3778
  const parser = createHashTreeParser(initialLocus, metadata);
2850
- const heartbeatIntervalMs = 5000;
2851
3779
 
2852
3780
  // Set Math.random to return 1 so that backoff = 1^exponent * maxMs = maxMs
2853
3781
  mathRandomStub.returns(1);
@@ -2869,7 +3797,6 @@ describe('HashTreeParser', () => {
2869
3797
  ],
2870
3798
  visibleDataSetsUrl,
2871
3799
  locusUrl,
2872
- heartbeatIntervalMs,
2873
3800
  };
2874
3801
 
2875
3802
  parser.handleMessage(heartbeat, 'heartbeat');
@@ -2919,7 +3846,6 @@ describe('HashTreeParser', () => {
2919
3846
 
2920
3847
  it('does not set watchdog for data sets without a hash tree', async () => {
2921
3848
  const parser = createHashTreeParser();
2922
- const heartbeatIntervalMs = 5000;
2923
3849
 
2924
3850
  // 'atd-active' is in the initial locus but is not visible (no hash tree)
2925
3851
  // Send heartbeat mentioning a non-visible dataset
@@ -2933,7 +3859,6 @@ describe('HashTreeParser', () => {
2933
3859
  ],
2934
3860
  visibleDataSetsUrl,
2935
3861
  locusUrl,
2936
- heartbeatIntervalMs,
2937
3862
  };
2938
3863
 
2939
3864
  parser.handleMessage(heartbeatMessage, 'heartbeat with non-visible dataset');
@@ -2942,10 +3867,217 @@ describe('HashTreeParser', () => {
2942
3867
  expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
2943
3868
  expect(parser.dataSets['atd-active']?.heartbeatWatchdogTimer).to.be.undefined;
2944
3869
  });
2945
- });
2946
- });
2947
3870
 
2948
- describe('#callLocusInfoUpdateCallback filtering', () => {
3871
+ it('does not set watchdog for a data set that has a hash tree but is not in visibleDataSets', async () => {
3872
+ const parser = createHashTreeParser();
3873
+
3874
+ // simulate a dataset that still has a hash tree but is no longer visible
3875
+ parser.visibleDataSets = parser.visibleDataSets.filter((vds) => vds.name !== 'main');
3876
+
3877
+ const heartbeatMessage = {
3878
+ dataSets: [
3879
+ {
3880
+ ...createDataSet('main', 16, 1100),
3881
+ root: parser.dataSets.main.hashTree.getRootHash(),
3882
+ },
3883
+ ],
3884
+ visibleDataSetsUrl,
3885
+ locusUrl,
3886
+ };
3887
+
3888
+ parser.handleMessage(heartbeatMessage, 'heartbeat for non-visible dataset with hash tree');
3889
+
3890
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3891
+ });
3892
+
3893
+ it('restarts the watchdog timer after it fires so that future missed heartbeats still trigger syncs', async () => {
3894
+ const parser = createHashTreeParser();
3895
+ const heartbeatIntervalMs = 5000;
3896
+
3897
+ // Send initial heartbeat for 'main'
3898
+ const heartbeatMessage = {
3899
+ dataSets: [
3900
+ {
3901
+ ...createDataSet('main', 16, 1100),
3902
+ root: parser.dataSets.main.hashTree.getRootHash(),
3903
+ },
3904
+ ],
3905
+ visibleDataSetsUrl,
3906
+ locusUrl,
3907
+ };
3908
+
3909
+ parser.handleMessage(heartbeatMessage, 'initial heartbeat');
3910
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3911
+
3912
+ // Mock responses for performSync - return null (204/empty body)
3913
+ const mainDataSetUrl = parser.dataSets.main.url;
3914
+ mockGetHashesFromLocusResponse(
3915
+ mainDataSetUrl,
3916
+ new Array(16).fill('00000000000000000000000000000000'),
3917
+ createDataSet('main', 16, 1101)
3918
+ );
3919
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3920
+
3921
+ // Advance time past heartbeatIntervalMs to fire the watchdog
3922
+ await clock.tickAsync(heartbeatIntervalMs);
3923
+
3924
+ // Verify sync was triggered
3925
+ assert.calledWith(
3926
+ webexRequest,
3927
+ sinon.match({
3928
+ method: 'GET',
3929
+ uri: `${mainDataSetUrl}/hashtree`,
3930
+ })
3931
+ );
3932
+
3933
+ // The watchdog timer should have been restarted after firing
3934
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3935
+
3936
+ // Reset call history and set up new mock responses for the second sync
3937
+ webexRequest.resetHistory();
3938
+ mockGetHashesFromLocusResponse(
3939
+ mainDataSetUrl,
3940
+ new Array(16).fill('00000000000000000000000000000000'),
3941
+ createDataSet('main', 16, 1102)
3942
+ );
3943
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3944
+
3945
+ // Advance time again to fire the watchdog a second time
3946
+ await clock.tickAsync(heartbeatIntervalMs);
3947
+
3948
+ // Verify a second sync was triggered
3949
+ assert.calledWith(
3950
+ webexRequest,
3951
+ sinon.match({
3952
+ method: 'GET',
3953
+ uri: `${mainDataSetUrl}/hashtree`,
3954
+ })
3955
+ );
3956
+
3957
+ // And the watchdog should still be running
3958
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3959
+ });
3960
+
3961
+ it('uses dataset-level heartbeatIntervalMs over top-level value', async () => {
3962
+ const parser = createHashTreeParser();
3963
+ const datasetLevelInterval = 3000;
3964
+ const topLevelInterval = 8000;
3965
+
3966
+ // Send heartbeat with both top-level and dataset-level heartbeatIntervalMs
3967
+ const heartbeatMessage = {
3968
+ dataSets: [
3969
+ {
3970
+ ...createDataSet('main', 16, 1100),
3971
+ root: parser.dataSets.main.hashTree.getRootHash(),
3972
+ heartbeatIntervalMs: datasetLevelInterval,
3973
+ },
3974
+ ],
3975
+ visibleDataSetsUrl,
3976
+ locusUrl,
3977
+ heartbeatIntervalMs: topLevelInterval,
3978
+ };
3979
+
3980
+ parser.handleMessage(heartbeatMessage, 'heartbeat with both levels');
3981
+
3982
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3983
+
3984
+ // Mock sync responses
3985
+ const mainDataSetUrl = parser.dataSets.main.url;
3986
+ mockGetHashesFromLocusResponse(
3987
+ mainDataSetUrl,
3988
+ new Array(16).fill('00000000000000000000000000000000'),
3989
+ createDataSet('main', 16, 1101)
3990
+ );
3991
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
3992
+
3993
+ // Watchdog should NOT fire at the top-level interval (8000ms)
3994
+ // It should fire at the dataset-level interval (3000ms)
3995
+ await clock.tickAsync(datasetLevelInterval - 1);
3996
+ assert.notCalled(webexRequest);
3997
+
3998
+ await clock.tickAsync(1);
3999
+ // Now at datasetLevelInterval, watchdog should have fired
4000
+ assert.calledWith(
4001
+ webexRequest,
4002
+ sinon.match({
4003
+ method: 'GET',
4004
+ uri: `${mainDataSetUrl}/hashtree`,
4005
+ })
4006
+ );
4007
+ });
4008
+
4009
+ it('falls back to top-level heartbeatIntervalMs when dataset-level is missing', async () => {
4010
+ const parser = createHashTreeParser();
4011
+ const topLevelInterval = 7000;
4012
+
4013
+ // Send heartbeat with top-level heartbeatIntervalMs but no dataset-level
4014
+ const heartbeatMessage = {
4015
+ dataSets: [
4016
+ {
4017
+ ...createDataSet('main', 16, 1100),
4018
+ root: parser.dataSets.main.hashTree.getRootHash(),
4019
+ heartbeatIntervalMs: undefined,
4020
+ },
4021
+ ],
4022
+ visibleDataSetsUrl,
4023
+ locusUrl,
4024
+ heartbeatIntervalMs: topLevelInterval,
4025
+ };
4026
+
4027
+ parser.handleMessage(heartbeatMessage, 'heartbeat with top-level only');
4028
+
4029
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
4030
+
4031
+ // Mock sync responses
4032
+ const mainDataSetUrl = parser.dataSets.main.url;
4033
+ mockGetHashesFromLocusResponse(
4034
+ mainDataSetUrl,
4035
+ new Array(16).fill('00000000000000000000000000000000'),
4036
+ createDataSet('main', 16, 1101)
4037
+ );
4038
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
4039
+
4040
+ // Should fire at the top-level interval
4041
+ await clock.tickAsync(topLevelInterval - 1);
4042
+ assert.notCalled(webexRequest);
4043
+
4044
+ await clock.tickAsync(1);
4045
+ assert.calledWith(
4046
+ webexRequest,
4047
+ sinon.match({
4048
+ method: 'GET',
4049
+ uri: `${mainDataSetUrl}/hashtree`,
4050
+ })
4051
+ );
4052
+ });
4053
+
4054
+ it('does not start watchdog when dataset-level heartbeatIntervalMs is 0 even if top-level is set', async () => {
4055
+ const parser = createHashTreeParser();
4056
+
4057
+ // Send heartbeat with dataset-level 0 and a top-level value
4058
+ const heartbeatMessage = {
4059
+ dataSets: [
4060
+ {
4061
+ ...createDataSet('main', 16, 1100),
4062
+ root: parser.dataSets.main.hashTree.getRootHash(),
4063
+ heartbeatIntervalMs: 0,
4064
+ },
4065
+ ],
4066
+ visibleDataSetsUrl,
4067
+ locusUrl,
4068
+ heartbeatIntervalMs: 5000,
4069
+ };
4070
+
4071
+ parser.handleMessage(heartbeatMessage, 'heartbeat with dataset-level 0');
4072
+
4073
+ // Dataset-level 0 means no watchdog, should NOT fall back to top-level
4074
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
4075
+ });
4076
+ });
4077
+
4078
+ });
4079
+
4080
+ describe('#callLocusInfoUpdateCallback filtering', () => {
2949
4081
  // Helper to setup parser with initial objects and reset callback history
2950
4082
  function setupParserWithObjects(locusStateElements: any[]) {
2951
4083
  const parser = createHashTreeParser();
@@ -3399,6 +4531,9 @@ describe('HashTreeParser', () => {
3399
4531
  parser.handleMessage(emptyMessage, 'empty elements');
3400
4532
 
3401
4533
  assert.notCalled(callback);
4534
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_EMPTY_LOCUS_STATE_ELEMENTS, {
4535
+ debugId: 'test',
4536
+ });
3402
4537
  });
3403
4538
 
3404
4539
  it('always calls callback for MEETING_ENDED regardless of filtering', () => {
@@ -3629,7 +4764,7 @@ describe('HashTreeParser', () => {
3629
4764
  });
3630
4765
  });
3631
4766
 
3632
- describe('#resume', () => {
4767
+ describe('#resumeFromMessage', () => {
3633
4768
  const createResumeMessage = (visibleDataSets?, dataSets?) => ({
3634
4769
  locusUrl,
3635
4770
  visibleDataSetsUrl,
@@ -3656,7 +4791,7 @@ describe('HashTreeParser', () => {
3656
4791
 
3657
4792
  expect(parser.state).to.equal('stopped');
3658
4793
 
3659
- parser.resume(createResumeMessage());
4794
+ parser.resumeFromMessage(createResumeMessage());
3660
4795
 
3661
4796
  expect(parser.state).to.equal('active');
3662
4797
  });
@@ -3665,7 +4800,7 @@ describe('HashTreeParser', () => {
3665
4800
  const parser = createHashTreeParser();
3666
4801
  parser.stop();
3667
4802
 
3668
- parser.resume({
4803
+ parser.resumeFromMessage({
3669
4804
  locusUrl,
3670
4805
  visibleDataSetsUrl,
3671
4806
  dataSets: [createDataSet('main', 16, 2000)],
@@ -3684,7 +4819,7 @@ describe('HashTreeParser', () => {
3684
4819
  createDataSet('self', 2, 6000),
3685
4820
  ];
3686
4821
 
3687
- parser.resume(createResumeMessage(undefined, newDataSets));
4822
+ parser.resumeFromMessage(createResumeMessage(undefined, newDataSets));
3688
4823
 
3689
4824
  expect(Object.keys(parser.dataSets)).to.have.lengthOf(2);
3690
4825
  expect(parser.dataSets.main.leafCount).to.equal(8);
@@ -3706,7 +4841,7 @@ describe('HashTreeParser', () => {
3706
4841
  {name: 'self', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self'},
3707
4842
  ];
3708
4843
 
3709
- parser.resume(createResumeMessage(visibleDataSets, dataSets));
4844
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
3710
4845
 
3711
4846
  expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
3712
4847
  expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
@@ -3720,7 +4855,7 @@ describe('HashTreeParser', () => {
3720
4855
  const handleMessageStub = sinon.stub(parser, 'handleMessage');
3721
4856
 
3722
4857
  const message = createResumeMessage();
3723
- parser.resume(message);
4858
+ parser.resumeFromMessage(message);
3724
4859
 
3725
4860
  assert.calledOnceWithExactly(handleMessageStub, message, 'on resume');
3726
4861
  });
@@ -3740,7 +4875,7 @@ describe('HashTreeParser', () => {
3740
4875
  {name: 'atd-unmuted', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted'},
3741
4876
  ];
3742
4877
 
3743
- parser.resume(createResumeMessage(visibleDataSets, dataSets));
4878
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
3744
4879
 
3745
4880
  expect(parser.visibleDataSets.some((vds) => vds.name === 'atd-unmuted')).to.be.false;
3746
4881
  expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
@@ -3748,6 +4883,67 @@ describe('HashTreeParser', () => {
3748
4883
  });
3749
4884
  });
3750
4885
 
4886
+ describe('#resumeFromApiResponse', () => {
4887
+ const exampleLocus = {
4888
+ participants: [],
4889
+ } as any;
4890
+
4891
+ it('should set state to active', async () => {
4892
+ const parser = createHashTreeParser();
4893
+ parser.stop();
4894
+
4895
+ expect(parser.state).to.equal('stopped');
4896
+
4897
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4898
+
4899
+ await parser.resumeFromApiResponse(exampleLocus);
4900
+
4901
+ expect(parser.state).to.equal('active');
4902
+ });
4903
+
4904
+ it('should reset dataSets to empty', async () => {
4905
+ const parser = createHashTreeParser();
4906
+
4907
+ expect(Object.keys(parser.dataSets).length).to.be.greaterThan(0);
4908
+
4909
+ parser.stop();
4910
+
4911
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4912
+
4913
+ await parser.resumeFromApiResponse(exampleLocus);
4914
+
4915
+ expect(parser.dataSets).to.deep.equal({});
4916
+ });
4917
+
4918
+ it('should call initializeFromGetLociResponse with the provided locus', async () => {
4919
+ const parser = createHashTreeParser();
4920
+ parser.stop();
4921
+
4922
+ const initStub = sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4923
+
4924
+ await parser.resumeFromApiResponse(exampleLocus);
4925
+
4926
+ assert.calledOnceWithExactly(initStub, exampleLocus);
4927
+ });
4928
+
4929
+ it('should propagate errors from initializeFromGetLociResponse', async () => {
4930
+ const parser = createHashTreeParser();
4931
+ parser.stop();
4932
+
4933
+ const error = new Error('initialization failed');
4934
+ const initStub = sinon.stub(parser, 'initializeFromGetLociResponse').rejects(error);
4935
+
4936
+ let caughtError: Error | undefined;
4937
+ try {
4938
+ await parser.resumeFromApiResponse(exampleLocus);
4939
+ } catch (e) {
4940
+ caughtError = e;
4941
+ }
4942
+
4943
+ expect(caughtError).to.equal(error);
4944
+ });
4945
+ });
4946
+
3751
4947
  describe('#handleLocusUpdate when stopped', () => {
3752
4948
  it('should return early without processing when parser is stopped', () => {
3753
4949
  const parser = createHashTreeParser();
@@ -3783,43 +4979,1114 @@ describe('HashTreeParser', () => {
3783
4979
  });
3784
4980
  });
3785
4981
 
3786
- describe('#cleanUp', () => {
3787
- it('should stop the parser, clear all timers and clear all dataSets', () => {
4982
+ describe('#syncAllDatasets', () => {
4983
+ it('should sync all datasets that have hash trees in priority order', async () => {
3788
4984
  const parser = createHashTreeParser();
3789
4985
 
3790
- // Send a message to set up sync timers via runSyncAlgorithm
3791
- const message = {
3792
- dataSets: [
3793
- {
3794
- ...createDataSet('main', 16, 1100),
3795
- root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
3796
- },
3797
- ],
4986
+ // parser starts with main (leafCount=16) and self (leafCount=1) as visible datasets with hash trees
4987
+ // atd-unmuted has no hash tree (not visible)
4988
+ expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
4989
+ expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
4990
+
4991
+ const mainUrl = parser.dataSets.main.url;
4992
+ const selfUrl = parser.dataSets.self.url;
4993
+
4994
+ // Mock GET hashtree for main (leafCount > 1, so it does GET first)
4995
+ mockGetHashesFromLocusResponse(
4996
+ mainUrl,
4997
+ new Array(16).fill(EMPTY_HASH),
4998
+ createDataSet('main', 16, 1100)
4999
+ );
5000
+
5001
+ // Mock POST sync for main - return matching root hash so no further sync needed
5002
+ const mainSyncDataSet = createDataSet('main', 16, 1100);
5003
+ mainSyncDataSet.root = parser.dataSets.main.hashTree.getRootHash();
5004
+ mockSendSyncRequestResponse(mainUrl, {
5005
+ dataSets: [mainSyncDataSet],
3798
5006
  visibleDataSetsUrl,
3799
5007
  locusUrl,
3800
- heartbeatIntervalMs: 5000,
3801
- locusStateElements: [
3802
- {
3803
- htMeta: {
3804
- elementId: {type: 'locus' as const, id: 0, version: 201},
3805
- dataSetNames: ['main'],
3806
- },
3807
- data: {someData: 'value'},
3808
- },
3809
- ],
3810
- };
5008
+ locusStateElements: [],
5009
+ });
3811
5010
 
3812
- parser.handleMessage(message, 'setup timers');
5011
+ // Mock POST sync for self (leafCount=1, skips GET hashtree)
5012
+ const selfSyncDataSet = createDataSet('self', 1, 2100);
5013
+ selfSyncDataSet.root = parser.dataSets.self.hashTree.getRootHash();
5014
+ mockSendSyncRequestResponse(selfUrl, {
5015
+ dataSets: [selfSyncDataSet],
5016
+ visibleDataSetsUrl,
5017
+ locusUrl,
5018
+ locusStateElements: [],
5019
+ });
3813
5020
 
3814
- // Verify timers were set by handleMessage
3815
- expect(parser.dataSets.main.timer).to.not.be.undefined;
3816
- expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
5021
+ await parser.syncAllDatasets();
3817
5022
 
3818
- parser.cleanUp();
5023
+ // Verify GET hashtree was called for main only (not self, because leafCount=1)
5024
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5025
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
3819
5026
 
3820
- expect(parser.state).to.equal('stopped');
3821
- expect(parser.visibleDataSets).to.deep.equal([]);
3822
- expect(parser.dataSets).to.deep.equal({});
5027
+ // Verify POST sync was called for both
5028
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5029
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5030
+
5031
+ // Verify main was synced before self (priority order)
5032
+ const mainSyncCallIndex = webexRequest.args.findIndex(
5033
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
5034
+ );
5035
+ const selfSyncCallIndex = webexRequest.args.findIndex(
5036
+ (args) => args[0]?.method === 'POST' && args[0]?.uri === `${selfUrl}/sync`
5037
+ );
5038
+ expect(mainSyncCallIndex).to.be.lessThan(selfSyncCallIndex);
5039
+
5040
+ // Verify syncAllBackoffType is reset
5041
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.NONE);
3823
5042
  });
5043
+
5044
+ it('should return immediately when state is stopped', async () => {
5045
+ const parser = createHashTreeParser();
5046
+ parser.stop();
5047
+
5048
+ await parser.syncAllDatasets();
5049
+
5050
+ // No sync requests should have been made (only the initial sync from constructor)
5051
+ // Reset history to clear constructor calls then verify
5052
+ const callCountBefore = webexRequest.callCount;
5053
+ await parser.syncAllDatasets();
5054
+ assert.equal(webexRequest.callCount, callCountBefore);
5055
+ });
5056
+
5057
+ it('should guard against concurrent calls', async () => {
5058
+ const parser = createHashTreeParser();
5059
+
5060
+ const mainUrl = parser.dataSets.main.url;
5061
+ const selfUrl = parser.dataSets.self.url;
5062
+
5063
+ // Use a deferred promise for the main sync to control timing
5064
+ let resolveMainSync;
5065
+ webexRequest
5066
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5067
+ .returns(new Promise((resolve) => { resolveMainSync = resolve; }));
5068
+
5069
+ mockSendSyncRequestResponse(mainUrl, {
5070
+ dataSets: [createDataSet('main', 16, 1100)],
5071
+ visibleDataSetsUrl,
5072
+ locusUrl,
5073
+ locusStateElements: [],
5074
+ });
5075
+
5076
+ mockSendSyncRequestResponse(selfUrl, {
5077
+ dataSets: [createDataSet('self', 1, 2100)],
5078
+ visibleDataSetsUrl,
5079
+ locusUrl,
5080
+ locusStateElements: [],
5081
+ });
5082
+
5083
+ // Start first call
5084
+ const promise1 = parser.syncAllDatasets();
5085
+ // Start second call while first is in progress
5086
+ const promise2 = parser.syncAllDatasets();
5087
+
5088
+ // Resolve the pending request
5089
+ resolveMainSync({
5090
+ body: {
5091
+ hashes: new Array(16).fill(EMPTY_HASH),
5092
+ dataSet: createDataSet('main', 16, 1100),
5093
+ },
5094
+ });
5095
+
5096
+ await promise1;
5097
+ await promise2;
5098
+
5099
+ // GET hashtree for main should only be called once (second syncAllDatasets returned immediately)
5100
+ const getHashtreeCalls = webexRequest.args.filter(
5101
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
5102
+ );
5103
+ expect(getHashtreeCalls).to.have.lengthOf(1);
5104
+ });
5105
+
5106
+ it('should sync only LLM datasets when onlyLLM=true', async () => {
5107
+ const parser = createHashTreeParser();
5108
+
5109
+ const mainUrl = parser.dataSets.main.url;
5110
+ const selfUrl = parser.dataSets.self.url;
5111
+
5112
+ mockGetHashesFromLocusResponse(
5113
+ mainUrl,
5114
+ new Array(16).fill(EMPTY_HASH),
5115
+ createDataSet('main', 16, 1100)
5116
+ );
5117
+
5118
+ const mainSyncDs = createDataSet('main', 16, 1100);
5119
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5120
+ mockSendSyncRequestResponse(mainUrl, {
5121
+ dataSets: [mainSyncDs],
5122
+ visibleDataSetsUrl,
5123
+ locusUrl,
5124
+ locusStateElements: [],
5125
+ });
5126
+
5127
+ await parser.syncAllDatasets({onlyLLM: true});
5128
+
5129
+ // main is an LLM dataset, so it should have been synced
5130
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5131
+
5132
+ // self is NOT an LLM dataset, so it should NOT have been synced
5133
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5134
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5135
+ });
5136
+
5137
+ it('uses the syncAll random backoff when reporting sync metrics', async () => {
5138
+ mathRandomStub.returns(0.5); // syncAll backoff = 0.5^2 * 1000 = 250ms
5139
+
5140
+ const syncLatencyTracker = {
5141
+ saveLatency: sinon.stub(),
5142
+ saveTimestamp: sinon.stub(),
5143
+ getLocusSyncLatency: sinon.stub(),
5144
+ clearLocusSyncLatency: sinon.stub(),
5145
+ completeLocusSyncLatency: sinon.stub(),
5146
+ };
5147
+ const parser = createHashTreeParser(
5148
+ undefined,
5149
+ undefined,
5150
+ ['atd-unmuted'],
5151
+ syncLatencyTracker
5152
+ );
5153
+ const mainUrl = parser.dataSets.main.url;
5154
+
5155
+ mockGetHashesFromLocusResponse(
5156
+ mainUrl,
5157
+ new Array(16).fill('00000000000000000000000000000000'),
5158
+ createDataSet('main', 16, 1100)
5159
+ );
5160
+ mockSendSyncRequestResponse(mainUrl, null);
5161
+
5162
+ const syncAllPromise = parser.syncAllDatasets({onlyLLM: true});
5163
+
5164
+ await clock.tickAsync(250);
5165
+ await syncAllPromise;
5166
+
5167
+ assert.calledWithExactly(
5168
+ syncLatencyTracker.saveLatency,
5169
+ 'internal.client.locus.sync.random.backoff',
5170
+ 250,
5171
+ {
5172
+ meetingId: 'meeting-1',
5173
+ dataSetName: 'main',
5174
+ }
5175
+ );
5176
+ });
5177
+
5178
+ it('should upgrade scope from onlyLLM=true to all datasets when onlyLLM=false call arrives during backoff', async () => {
5179
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms (non-zero delay for interleaving)
5180
+ mathRandomStub.returns(1);
5181
+
5182
+ const parser = createHashTreeParser();
5183
+
5184
+ const mainUrl = parser.dataSets.main.url;
5185
+ const selfUrl = parser.dataSets.self.url;
5186
+
5187
+ mockGetHashesFromLocusResponse(
5188
+ mainUrl,
5189
+ new Array(16).fill(EMPTY_HASH),
5190
+ createDataSet('main', 16, 1100)
5191
+ );
5192
+
5193
+ const mainSyncDs = createDataSet('main', 16, 1100);
5194
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5195
+ mockSendSyncRequestResponse(mainUrl, {
5196
+ dataSets: [mainSyncDs],
5197
+ visibleDataSetsUrl,
5198
+ locusUrl,
5199
+ locusStateElements: [],
5200
+ });
5201
+
5202
+ const selfSyncDs = createDataSet('self', 1, 2100);
5203
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
5204
+ mockSendSyncRequestResponse(selfUrl, {
5205
+ dataSets: [selfSyncDs],
5206
+ visibleDataSetsUrl,
5207
+ locusUrl,
5208
+ locusStateElements: [],
5209
+ });
5210
+
5211
+ // First call with onlyLLM=true starts backoff
5212
+ const promise1 = parser.syncAllDatasets({onlyLLM: true});
5213
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ONLY_LLM);
5214
+
5215
+ // Second call with onlyLLM=false upgrades the scope during backoff
5216
+ const promise2 = parser.syncAllDatasets({onlyLLM: false});
5217
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
5218
+
5219
+ // Advance clock past the backoff delay (1000ms)
5220
+ await clock.tickAsync(1000);
5221
+
5222
+ await promise1;
5223
+ await promise2;
5224
+
5225
+ // Both main (LLM) and self (non-LLM) should have been synced
5226
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5227
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5228
+ });
5229
+
5230
+ it('should not downgrade scope from onlyLLM=false when onlyLLM=true call arrives during backoff', async () => {
5231
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms (non-zero delay for interleaving)
5232
+ mathRandomStub.returns(1);
5233
+
5234
+ const parser = createHashTreeParser();
5235
+
5236
+ const mainUrl = parser.dataSets.main.url;
5237
+ const selfUrl = parser.dataSets.self.url;
5238
+
5239
+ mockGetHashesFromLocusResponse(
5240
+ mainUrl,
5241
+ new Array(16).fill(EMPTY_HASH),
5242
+ createDataSet('main', 16, 1100)
5243
+ );
5244
+
5245
+ const mainSyncDs = createDataSet('main', 16, 1100);
5246
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5247
+ mockSendSyncRequestResponse(mainUrl, {
5248
+ dataSets: [mainSyncDs],
5249
+ visibleDataSetsUrl,
5250
+ locusUrl,
5251
+ locusStateElements: [],
5252
+ });
5253
+
5254
+ const selfSyncDs = createDataSet('self', 1, 2100);
5255
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
5256
+ mockSendSyncRequestResponse(selfUrl, {
5257
+ dataSets: [selfSyncDs],
5258
+ visibleDataSetsUrl,
5259
+ locusUrl,
5260
+ locusStateElements: [],
5261
+ });
5262
+
5263
+ // First call with onlyLLM=false starts backoff with all-datasets scope
5264
+ const promise1 = parser.syncAllDatasets({onlyLLM: false});
5265
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
5266
+
5267
+ // Second call with onlyLLM=true should NOT downgrade the scope
5268
+ const promise2 = parser.syncAllDatasets({onlyLLM: true});
5269
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
5270
+
5271
+ // Advance clock past the backoff delay (1000ms)
5272
+ await clock.tickAsync(1000);
5273
+
5274
+ await promise1;
5275
+ await promise2;
5276
+
5277
+ // Both main (LLM) and self (non-LLM) should have been synced (scope was not downgraded)
5278
+ assert.calledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5279
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5280
+ });
5281
+
5282
+ it('should skip datasets that received messages during the backoff sleep', async () => {
5283
+ // Make Math.random return 1 so backoff = 1^2 * 1000 = 1000ms
5284
+ mathRandomStub.returns(1);
5285
+
5286
+ const parser = createHashTreeParser();
5287
+
5288
+ const mainUrl = parser.dataSets.main.url;
5289
+ const selfUrl = parser.dataSets.self.url;
5290
+ const atdUnmutedUrl = parser.dataSets['atd-unmuted'].url;
5291
+
5292
+ // Setup mocks only for self (main and atd-unmuted should be skipped)
5293
+ mockSendSyncRequestResponse(selfUrl, {
5294
+ dataSets: [createDataSet('self', 1, 2100)],
5295
+ visibleDataSetsUrl,
5296
+ locusUrl,
5297
+ locusStateElements: [],
5298
+ });
5299
+
5300
+ // Start syncAllDatasets - begins backoff sleep
5301
+ const promise = parser.syncAllDatasets();
5302
+ expect(parser.syncAllBackoffType).to.equal(SyncAllBackoffType.ALL);
5303
+
5304
+ // Simulate a normal message arriving for "main" during the backoff sleep
5305
+ parser.handleMessage({
5306
+ dataSets: [createDataSet('main', 16, 1100)],
5307
+ visibleDataSetsUrl,
5308
+ locusUrl,
5309
+ locusStateElements: [
5310
+ {
5311
+ htMeta: {
5312
+ elementId: {type: 'locus' as const, id: 0, version: 201},
5313
+ dataSetNames: ['main'],
5314
+ },
5315
+ data: {someData: 'value'},
5316
+ },
5317
+ ],
5318
+ });
5319
+
5320
+ // Simulate a heartbeat message arriving for "atd-unmuted" during the backoff sleep
5321
+ parser.handleMessage(
5322
+ createHeartbeatMessage('atd-unmuted', 1, 1100, parser.dataSets['atd-unmuted'].root)
5323
+ );
5324
+
5325
+ // Advance clock past the backoff delay
5326
+ await clock.tickAsync(1000);
5327
+ await promise;
5328
+
5329
+ // main should NOT have been synced (it received a normal message during backoff)
5330
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}));
5331
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5332
+
5333
+ // atd-unmuted should NOT have been synced (it received a heartbeat during backoff)
5334
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${atdUnmutedUrl}/hashtree`}));
5335
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${atdUnmutedUrl}/sync`}));
5336
+
5337
+ // self SHOULD have been synced (no messages received for it during backoff)
5338
+ assert.calledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5339
+ });
5340
+
5341
+ it('should skip datasets that do not have a hash tree', async () => {
5342
+ // Create parser with metadata that only has main and self as visible (not atd-unmuted)
5343
+ const metadataWithoutAtd = {
5344
+ ...exampleMetadata,
5345
+ visibleDataSets: exampleMetadata.visibleDataSets.filter((ds) => ds.name !== 'atd-unmuted'),
5346
+ };
5347
+ const parser = createHashTreeParser(exampleInitialLocus, metadataWithoutAtd);
5348
+
5349
+ // atd-unmuted is in dataSets but has no hashTree (not visible)
5350
+ expect(parser.dataSets['atd-unmuted']).to.exist;
5351
+ expect(parser.dataSets['atd-unmuted'].hashTree).to.be.undefined;
5352
+
5353
+ const atdUrl = parser.dataSets['atd-unmuted'].url;
5354
+ const mainUrl = parser.dataSets.main.url;
5355
+ const selfUrl = parser.dataSets.self.url;
5356
+
5357
+ mockGetHashesFromLocusResponse(
5358
+ mainUrl,
5359
+ new Array(16).fill(EMPTY_HASH),
5360
+ createDataSet('main', 16, 1100)
5361
+ );
5362
+
5363
+ const mainSyncDs = createDataSet('main', 16, 1100);
5364
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5365
+ mockSendSyncRequestResponse(mainUrl, {
5366
+ dataSets: [mainSyncDs],
5367
+ visibleDataSetsUrl,
5368
+ locusUrl,
5369
+ locusStateElements: [],
5370
+ });
5371
+
5372
+ const selfSyncDs = createDataSet('self', 1, 2100);
5373
+ selfSyncDs.root = parser.dataSets.self.hashTree.getRootHash();
5374
+ mockSendSyncRequestResponse(selfUrl, {
5375
+ dataSets: [selfSyncDs],
5376
+ visibleDataSetsUrl,
5377
+ locusUrl,
5378
+ locusStateElements: [],
5379
+ });
5380
+
5381
+ await parser.syncAllDatasets();
5382
+
5383
+ // No requests should have been made for atd-unmuted
5384
+ assert.neverCalledWith(webexRequest, sinon.match({uri: sinon.match(atdUrl)}));
5385
+ });
5386
+ });
5387
+
5388
+ describe('#handleMessage sync queue', () => {
5389
+ it('should deduplicate: not sync the same dataset twice when enqueued multiple times', async () => {
5390
+ const parser = createHashTreeParser();
5391
+
5392
+ const mainUrl = parser.dataSets.main.url;
5393
+
5394
+ // Setup mocks before triggering syncs
5395
+ mockGetHashesFromLocusResponse(
5396
+ mainUrl,
5397
+ new Array(16).fill(EMPTY_HASH),
5398
+ createDataSet('main', 16, 1101)
5399
+ );
5400
+
5401
+ const mainSyncDs = createDataSet('main', 16, 1101);
5402
+ mainSyncDs.root = parser.dataSets.main.hashTree.getRootHash();
5403
+ mockSendSyncRequestResponse(mainUrl, {
5404
+ dataSets: [mainSyncDs],
5405
+ visibleDataSetsUrl,
5406
+ locusUrl,
5407
+ locusStateElements: [],
5408
+ });
5409
+
5410
+ // Send two heartbeat messages (no locusStateElements) with different root hashes for main
5411
+ parser.handleMessage(createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'), 'first');
5412
+ parser.handleMessage(createHeartbeatMessage('main', 16, 1101, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa2'), 'second');
5413
+
5414
+ // The second call resets the timer. After 1000ms, only one sync fires.
5415
+ await clock.tickAsync(1000);
5416
+
5417
+ // Only one GET hashtree call should have been made for main
5418
+ const getHashtreeCalls = webexRequest.args.filter(
5419
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${mainUrl}/hashtree`
5420
+ );
5421
+ expect(getHashtreeCalls).to.have.lengthOf(1);
5422
+ });
5423
+
5424
+ it('should stop processing the sync queue when parser is stopped mid-queue', async () => {
5425
+ const parser = createHashTreeParser();
5426
+
5427
+ const mainUrl = parser.dataSets.main.url;
5428
+ const selfUrl = parser.dataSets.self.url;
5429
+
5430
+ // Mock main GET hashtree with a deferred promise so we can control when it resolves
5431
+ let resolveMainHashtree;
5432
+ webexRequest
5433
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5434
+ .callsFake(() => new Promise((resolve) => { resolveMainHashtree = resolve; }));
5435
+
5436
+ // Send a heartbeat message that triggers sync timers for both main and self
5437
+ parser.handleMessage(
5438
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5439
+ 'trigger main sync'
5440
+ );
5441
+ parser.handleMessage(
5442
+ createHeartbeatMessage('self', 1, 2100, 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1'),
5443
+ 'trigger self sync'
5444
+ );
5445
+
5446
+ // Fire the timers - main sync starts (calls GET hashtree, which blocks)
5447
+ await clock.tickAsync(1000);
5448
+
5449
+ // Stop the parser while main sync is in progress
5450
+ parser.stop();
5451
+
5452
+ // Resolve the pending main GET request
5453
+ resolveMainHashtree({
5454
+ body: {
5455
+ hashes: new Array(16).fill(EMPTY_HASH),
5456
+ dataSet: createDataSet('main', 16, 1100),
5457
+ },
5458
+ });
5459
+
5460
+ await clock.tickAsync(0);
5461
+
5462
+ // Self sync should NOT have been triggered because parser was stopped
5463
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5464
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5465
+ });
5466
+ });
5467
+
5468
+ describe('#stop sync queue', () => {
5469
+ it('should clear the syncQueue when stopped so remaining queued items are not processed', async () => {
5470
+ const parser = createHashTreeParser();
5471
+
5472
+ const mainUrl = parser.dataSets.main.url;
5473
+ const selfUrl = parser.dataSets.self.url;
5474
+
5475
+ // Mock main GET hashtree with a deferred promise so we can control when it resolves
5476
+ let resolveMainHashtree;
5477
+ webexRequest
5478
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5479
+ .callsFake(() => new Promise((resolve) => { resolveMainHashtree = resolve; }));
5480
+
5481
+ // Enqueue syncs for both main and self by sending heartbeat messages
5482
+ parser.handleMessage(
5483
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5484
+ 'trigger main sync'
5485
+ );
5486
+ parser.handleMessage(
5487
+ createHeartbeatMessage('self', 1, 2100, 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1'),
5488
+ 'trigger self sync'
5489
+ );
5490
+
5491
+ // Fire the timers - main sync starts and blocks on GET hashtree
5492
+ await clock.tickAsync(1000);
5493
+
5494
+ // Verify that self is still in the queue (main is being processed, self is waiting)
5495
+ // Now stop the parser - this should clear the syncQueue
5496
+ parser.stop();
5497
+
5498
+ // Resolve the pending main GET request so the in-flight sync can finish
5499
+ resolveMainHashtree({
5500
+ body: {
5501
+ hashes: new Array(16).fill(EMPTY_HASH),
5502
+ dataSet: createDataSet('main', 16, 1100),
5503
+ },
5504
+ });
5505
+
5506
+ await clock.tickAsync(0);
5507
+
5508
+ // Self should never have been synced because stop() cleared the queue
5509
+ const selfGetCalls = webexRequest.args.filter(
5510
+ (args) => args[0]?.method === 'GET' && args[0]?.uri === `${selfUrl}/hashtree`
5511
+ );
5512
+ expect(selfGetCalls).to.have.lengthOf(0);
5513
+ });
5514
+ });
5515
+
5516
+ describe('#performSync abort controller', () => {
5517
+ it('should reuse an existing syncAbortController if one is already set on the dataset', async () => {
5518
+ const parser = createHashTreeParser();
5519
+ const mainUrl = parser.dataSets.main.url;
5520
+
5521
+ // Pre-set an AbortController on the dataset before sync starts
5522
+ const existingController = new AbortController();
5523
+ parser.dataSets.main.syncAbortController = existingController;
5524
+
5525
+ // Use a deferred promise for GET hashtree so we can inspect the controller mid-sync
5526
+ let resolveGetHashtree;
5527
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5528
+ () =>
5529
+ new Promise((resolve) => {
5530
+ resolveGetHashtree = resolve;
5531
+ })
5532
+ );
5533
+
5534
+ // Trigger sync for main
5535
+ parser.handleMessage(
5536
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5537
+ 'trigger main sync'
5538
+ );
5539
+
5540
+ await clock.tickAsync(1000);
5541
+
5542
+ // While sync is in-flight, verify the controller is the same one we pre-set
5543
+ expect(parser.dataSets.main.syncAbortController).to.equal(existingController);
5544
+
5545
+ // Resolve GET hashtree with matching hashes (no sync needed)
5546
+ resolveGetHashtree({body: {}});
5547
+ await testUtils.flushPromises();
5548
+
5549
+ // After sync completes, syncAbortController is cleared in finally
5550
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5551
+ });
5552
+
5553
+ it('should abort the sync before /sync request when the controller is aborted during getHashesFromLocus', async () => {
5554
+ const parser = createHashTreeParser();
5555
+ const mainUrl = parser.dataSets.main.url;
5556
+
5557
+ // Use a deferred promise for GET hashtree so we can abort while it's pending
5558
+ let resolveGetHashtree;
5559
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5560
+ () =>
5561
+ new Promise((resolve) => {
5562
+ resolveGetHashtree = resolve;
5563
+ })
5564
+ );
5565
+
5566
+ // Mock POST sync - should NOT be called if abort works
5567
+ mockSendSyncRequestResponse(mainUrl, null);
5568
+
5569
+ // Trigger sync for main via heartbeat with mismatched root hash
5570
+ parser.handleMessage(
5571
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5572
+ 'trigger main sync'
5573
+ );
5574
+
5575
+ // Fire the timer to start the sync
5576
+ await clock.tickAsync(1000);
5577
+
5578
+ // Now abort the controller while getHashesFromLocus is pending
5579
+ expect(parser.dataSets.main.syncAbortController).to.not.be.undefined;
5580
+ parser.dataSets.main.syncAbortController.abort();
5581
+
5582
+ // Resolve GET hashtree with mismatched hashes so the code would normally proceed to /sync
5583
+ resolveGetHashtree({
5584
+ body: {
5585
+ hashes: new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5586
+ dataSet: createDataSet('main', 16, 1100),
5587
+ },
5588
+ });
5589
+
5590
+ await testUtils.flushPromises();
5591
+
5592
+ // POST sync should NOT have been called because the controller was aborted
5593
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5594
+ });
5595
+
5596
+ it('should abort the sync before /sync request when the controller is aborted for leafCount === 1 datasets', async () => {
5597
+ const parser = createHashTreeParser();
5598
+ const selfUrl = parser.dataSets.self.url;
5599
+
5600
+ // Pre-set an already-aborted controller so performSync picks it up via ??
5601
+ const abortedController = new AbortController();
5602
+ abortedController.abort();
5603
+ parser.dataSets.self.syncAbortController = abortedController;
5604
+
5605
+ // Mock POST sync - should NOT be called
5606
+ mockSendSyncRequestResponse(selfUrl, null);
5607
+
5608
+ // Trigger sync for self via heartbeat with mismatched root hash
5609
+ parser.handleMessage(
5610
+ {
5611
+ dataSets: [
5612
+ {
5613
+ ...createDataSet('self', 1, 2100),
5614
+ url: parser.dataSets.self.url,
5615
+ root: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb1',
5616
+ },
5617
+ ],
5618
+ visibleDataSetsUrl,
5619
+ locusUrl,
5620
+ },
5621
+ 'trigger self sync'
5622
+ );
5623
+
5624
+ // Fire the timer to start the sync
5625
+ await clock.tickAsync(1000);
5626
+
5627
+ // GET hashtree should NOT have been called (leafCount === 1 skips it)
5628
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'GET', uri: `${selfUrl}/hashtree`}));
5629
+
5630
+ // POST sync should NOT have been called because the controller was already aborted
5631
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${selfUrl}/sync`}));
5632
+ });
5633
+
5634
+ it('should unconditionally clear syncAbortController in the finally block', async () => {
5635
+ const parser = createHashTreeParser();
5636
+ const mainUrl = parser.dataSets.main.url;
5637
+
5638
+ // Mock GET hashtree to return matching hashes (early return, no sync needed)
5639
+ webexRequest
5640
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5641
+ .resolves({body: {}});
5642
+
5643
+ // Trigger sync for main
5644
+ parser.handleMessage(
5645
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5646
+ 'trigger main sync'
5647
+ );
5648
+
5649
+ await clock.tickAsync(1000);
5650
+
5651
+ // After sync completes (even via early return), syncAbortController should be cleared
5652
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5653
+ });
5654
+
5655
+ it('should unconditionally clear syncAbortController even when sync throws an error', async () => {
5656
+ const parser = createHashTreeParser();
5657
+ const mainUrl = parser.dataSets.main.url;
5658
+
5659
+ // Mock GET hashtree to reject with a non-409 error
5660
+ webexRequest
5661
+ .withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`}))
5662
+ .rejects({statusCode: 500, message: 'Internal Server Error'});
5663
+
5664
+ // Trigger sync for main
5665
+ parser.handleMessage(
5666
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5667
+ 'trigger main sync'
5668
+ );
5669
+
5670
+ await clock.tickAsync(1000);
5671
+
5672
+ // After sync completes with error, syncAbortController should still be cleared
5673
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5674
+ });
5675
+
5676
+ it('should reuse a pre-existing abort controller and respect its aborted state', async () => {
5677
+ const parser = createHashTreeParser();
5678
+ const mainUrl = parser.dataSets.main.url;
5679
+
5680
+ // Pre-set an AbortController and abort it before sync starts
5681
+ const preAbortedController = new AbortController();
5682
+ preAbortedController.abort();
5683
+ parser.dataSets.main.syncAbortController = preAbortedController;
5684
+
5685
+ // Mock GET hashtree to return mismatched hashes
5686
+ mockGetHashesFromLocusResponse(
5687
+ mainUrl,
5688
+ new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5689
+ createDataSet('main', 16, 1100)
5690
+ );
5691
+
5692
+ // Mock POST sync - should NOT be called
5693
+ mockSendSyncRequestResponse(mainUrl, null);
5694
+
5695
+ // Trigger sync for main
5696
+ parser.handleMessage(
5697
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5698
+ 'trigger main sync'
5699
+ );
5700
+
5701
+ await clock.tickAsync(1000);
5702
+
5703
+ // POST sync should NOT have been called because the reused controller was already aborted
5704
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5705
+
5706
+ // syncAbortController should be cleaned up
5707
+ expect(parser.dataSets.main.syncAbortController).to.be.undefined;
5708
+ });
5709
+
5710
+ it('should allow cancelPendingSyncsForDataSets to abort an in-flight sync via the shared controller', async () => {
5711
+ const parser = createHashTreeParser();
5712
+ const mainUrl = parser.dataSets.main.url;
5713
+
5714
+ // Use a deferred promise for GET hashtree
5715
+ let resolveGetHashtree;
5716
+ webexRequest.withArgs(sinon.match({method: 'GET', uri: `${mainUrl}/hashtree`})).callsFake(
5717
+ () =>
5718
+ new Promise((resolve) => {
5719
+ resolveGetHashtree = resolve;
5720
+ })
5721
+ );
5722
+
5723
+ mockSendSyncRequestResponse(mainUrl, null);
5724
+
5725
+ // Trigger sync for main
5726
+ parser.handleMessage(
5727
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5728
+ 'trigger main sync'
5729
+ );
5730
+
5731
+ // Fire the timer to start sync
5732
+ await clock.tickAsync(1000);
5733
+
5734
+ // Verify controller is set
5735
+ expect(parser.dataSets.main.syncAbortController).to.not.be.undefined;
5736
+
5737
+ // Simulate a new heartbeat arriving that cancels the in-flight sync
5738
+ // (this is what happens in production via parseMessage -> cancelPendingSyncsForDataSets)
5739
+ parser.handleMessage(
5740
+ {
5741
+ dataSets: [
5742
+ {
5743
+ ...createDataSet('main', 16, 1101),
5744
+ root: parser.dataSets.main.hashTree.getRootHash(), // matching hash so no new sync
5745
+ },
5746
+ ],
5747
+ visibleDataSetsUrl,
5748
+ locusUrl,
5749
+ },
5750
+ 'new heartbeat cancels sync'
5751
+ );
5752
+
5753
+ // Resolve the pending GET hashtree with mismatched hashes
5754
+ resolveGetHashtree({
5755
+ body: {
5756
+ hashes: new Array(16).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5757
+ dataSet: createDataSet('main', 16, 1101),
5758
+ },
5759
+ });
5760
+
5761
+ await testUtils.flushPromises();
5762
+
5763
+ // POST sync should NOT have been called because cancelPendingSyncsForDataSets aborted the controller
5764
+ assert.neverCalledWith(webexRequest, sinon.match({method: 'POST', uri: `${mainUrl}/sync`}));
5765
+ });
5766
+ });
5767
+
5768
+ describe('#cleanUp', () => {
5769
+ it('should stop the parser, clear all timers and clear all dataSets', () => {
5770
+ const parser = createHashTreeParser();
5771
+
5772
+ // Send a message to set up sync timers via runSyncAlgorithm
5773
+ const message = {
5774
+ dataSets: [
5775
+ {
5776
+ ...createDataSet('main', 16, 1100),
5777
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1',
5778
+ },
5779
+ ],
5780
+ visibleDataSetsUrl,
5781
+ locusUrl,
5782
+ locusStateElements: [
5783
+ {
5784
+ htMeta: {
5785
+ elementId: {type: 'locus' as const, id: 0, version: 201},
5786
+ dataSetNames: ['main'],
5787
+ },
5788
+ data: {someData: 'value'},
5789
+ },
5790
+ ],
5791
+ };
5792
+
5793
+ parser.handleMessage(message, 'setup timers');
5794
+
5795
+ // Verify timers were set by handleMessage
5796
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
5797
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
5798
+
5799
+ parser.cleanUp();
5800
+
5801
+ expect(parser.state).to.equal('stopped');
5802
+ expect(parser.visibleDataSets).to.deep.equal([]);
5803
+ expect(parser.dataSets).to.deep.equal({});
5804
+ });
5805
+ });
5806
+
5807
+ describe('#syncMetrics', () => {
5808
+ it('records sync latency timestamps when sync response has empty body', async () => {
5809
+ const syncLatencyTracker = {
5810
+ saveLatency: sinon.stub(),
5811
+ saveTimestamp: sinon.stub(),
5812
+ getLocusSyncLatency: sinon.stub(),
5813
+ clearLocusSyncLatency: sinon.stub(),
5814
+ completeLocusSyncLatency: sinon.stub(),
5815
+ };
5816
+ const parser = createHashTreeParser(
5817
+ undefined,
5818
+ undefined,
5819
+ undefined,
5820
+ syncLatencyTracker
5821
+ );
5822
+ const mainDataSetUrl = parser.dataSets.main.url;
5823
+
5824
+ mockGetHashesFromLocusResponse(
5825
+ mainDataSetUrl,
5826
+ new Array(16).fill('00000000000000000000000000000000'),
5827
+ createDataSet('main', 16, 1101)
5828
+ );
5829
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
5830
+
5831
+ parser.handleMessage(
5832
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5833
+ 'trigger sync metrics'
5834
+ );
5835
+
5836
+ await clock.tickAsync(1000);
5837
+
5838
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5839
+ key: 'internal.client.locus.sync.start',
5840
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5841
+ });
5842
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5843
+ key: 'internal.client.locus.hashtree.request',
5844
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5845
+ });
5846
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5847
+ key: 'internal.client.locus.hashtree.response',
5848
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5849
+ });
5850
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5851
+ key: 'internal.client.locus.sync.request',
5852
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5853
+ });
5854
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5855
+ key: 'internal.client.locus.sync.response',
5856
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: undefined},
5857
+ });
5858
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
5859
+ });
5860
+
5861
+ it('clears only the failed sync record (by tracking id) when the /sync request errors', async () => {
5862
+ const syncLatencyTracker = {
5863
+ saveLatency: sinon.stub(),
5864
+ saveTimestamp: sinon.stub(),
5865
+ getLocusSyncLatency: sinon.stub(),
5866
+ clearLocusSyncLatency: sinon.stub(),
5867
+ completeLocusSyncLatency: sinon.stub(),
5868
+ };
5869
+ const generateTrackingId = sinon.stub().returns('our-sync-tracking-id');
5870
+ const parser = createHashTreeParser(
5871
+ undefined,
5872
+ undefined,
5873
+ undefined,
5874
+ syncLatencyTracker,
5875
+ undefined,
5876
+ generateTrackingId
5877
+ );
5878
+ const mainDataSetUrl = parser.dataSets.main.url;
5879
+
5880
+ // Mismatched hashes so the flow proceeds to POST /sync, which then fails.
5881
+ mockGetHashesFromLocusResponse(
5882
+ mainDataSetUrl,
5883
+ new Array(16).fill('00000000000000000000000000000000'),
5884
+ createDataSet('main', 16, 1101)
5885
+ );
5886
+ webexRequest
5887
+ .withArgs(sinon.match({method: 'POST', uri: `${mainDataSetUrl}/sync`}))
5888
+ .rejects(new Error('sync failed'));
5889
+
5890
+ parser.handleMessage(
5891
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5892
+ 'trigger sync metrics'
5893
+ );
5894
+
5895
+ await clock.tickAsync(1000);
5896
+
5897
+ // Because /sync failed, syncRequestSent stays false and the finally block drops the record,
5898
+ // passing the tracking id so only this in-progress record is removed (native onSyncError parity).
5899
+ assert.calledWithExactly(
5900
+ syncLatencyTracker.clearLocusSyncLatency,
5901
+ 'main',
5902
+ 'meeting-1',
5903
+ 'our-sync-tracking-id'
5904
+ );
5905
+ });
5906
+
5907
+ it('forces a pre-generated tracking id onto the sync request and records it', async () => {
5908
+ const syncLatencyTracker = {
5909
+ saveLatency: sinon.stub(),
5910
+ saveTimestamp: sinon.stub(),
5911
+ getLocusSyncLatency: sinon.stub(),
5912
+ clearLocusSyncLatency: sinon.stub(),
5913
+ completeLocusSyncLatency: sinon.stub(),
5914
+ };
5915
+ // two distinct tracking ids are generated: the first for the /hashtree request and the
5916
+ // second for the /sync request (which is also stored in metrics and used for LLM matching)
5917
+ const generateTrackingId = sinon.stub();
5918
+ generateTrackingId.onFirstCall().returns('our-hashtree-tracking-id');
5919
+ generateTrackingId.onSecondCall().returns('our-sync-tracking-id');
5920
+ const parser = createHashTreeParser(
5921
+ undefined,
5922
+ undefined,
5923
+ undefined,
5924
+ syncLatencyTracker,
5925
+ undefined,
5926
+ generateTrackingId
5927
+ );
5928
+ const mainDataSetUrl = parser.dataSets.main.url;
5929
+
5930
+ mockGetHashesFromLocusResponse(
5931
+ mainDataSetUrl,
5932
+ new Array(16).fill('00000000000000000000000000000000'),
5933
+ createDataSet('main', 16, 1102)
5934
+ );
5935
+ mockSendSyncRequestResponse(mainDataSetUrl, null);
5936
+
5937
+ parser.handleMessage(
5938
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
5939
+ 'trigger sync metrics'
5940
+ );
5941
+
5942
+ await clock.tickAsync(1000);
5943
+
5944
+ // two distinct tracking ids are generated up-front so the /hashtree and /sync requests do
5945
+ // not share a tracking id
5946
+ assert.calledTwice(generateTrackingId);
5947
+ // the /hashtree request carries its own (first) tracking id
5948
+ assert.calledWith(
5949
+ webexRequest,
5950
+ sinon.match({
5951
+ method: 'GET',
5952
+ uri: `${mainDataSetUrl}/hashtree`,
5953
+ headers: {trackingid: 'our-hashtree-tracking-id'},
5954
+ })
5955
+ );
5956
+ // the /sync request carries the second tracking id, which Locus echoes back on the resulting
5957
+ // LLM message so the Meeting object can match it to this sync
5958
+ assert.calledWith(
5959
+ webexRequest,
5960
+ sinon.match({
5961
+ method: 'POST',
5962
+ uri: `${mainDataSetUrl}/sync`,
5963
+ headers: {trackingid: 'our-sync-tracking-id'},
5964
+ })
5965
+ );
5966
+
5967
+ // the same tracking id is stamped on the sync milestones so the Meeting object can later
5968
+ // match the LLM event to this sync
5969
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5970
+ key: 'internal.client.locus.sync.start',
5971
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5972
+ });
5973
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5974
+ key: 'internal.client.locus.hashtree.request',
5975
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5976
+ });
5977
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5978
+ key: 'internal.client.locus.hashtree.response',
5979
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5980
+ });
5981
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5982
+ key: 'internal.client.locus.sync.request',
5983
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5984
+ });
5985
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
5986
+ key: 'internal.client.locus.sync.response',
5987
+ options: {meetingId: 'meeting-1', dataSetName: 'main', trackingId: 'our-sync-tracking-id'},
5988
+ });
5989
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
5990
+ });
5991
+
5992
+ it('does not complete or clear metrics when matching dataset message arrives', () => {
5993
+ const syncLatencyTracker = {
5994
+ saveLatency: sinon.stub(),
5995
+ saveTimestamp: sinon.stub(),
5996
+ getLocusSyncLatency: sinon.stub(),
5997
+ clearLocusSyncLatency: sinon.stub(),
5998
+ completeLocusSyncLatency: sinon.stub(),
5999
+ };
6000
+ const parser = createHashTreeParser(
6001
+ undefined,
6002
+ undefined,
6003
+ undefined,
6004
+ syncLatencyTracker
6005
+ );
6006
+
6007
+ parser.handleMessage({
6008
+ dataSets: [
6009
+ {
6010
+ ...createDataSet('main', 16, 1001),
6011
+ root: 'newroot',
6012
+ },
6013
+ ],
6014
+ visibleDataSetsUrl,
6015
+ locusUrl,
6016
+ locusStateElements: [],
6017
+ });
6018
+
6019
+ assert.notCalled(syncLatencyTracker.getLocusSyncLatency);
6020
+ assert.notCalled(syncLatencyTracker.clearLocusSyncLatency);
6021
+ assert.notCalled(syncLatencyTracker.completeLocusSyncLatency);
6022
+ });
6023
+
6024
+ it('does not complete sync metrics when sync response has body (completion is LLM-only)', async () => {
6025
+ const syncLatencyTracker = {
6026
+ saveLatency: sinon.stub(),
6027
+ saveTimestamp: sinon.stub(),
6028
+ getLocusSyncLatency: sinon.stub(),
6029
+ clearLocusSyncLatency: sinon.stub(),
6030
+ completeLocusSyncLatency: sinon.stub(),
6031
+ };
6032
+ const generateTrackingId = sinon.stub().returns('our-sync-tracking-id');
6033
+ const parser = createHashTreeParser(
6034
+ undefined,
6035
+ undefined,
6036
+ undefined,
6037
+ syncLatencyTracker,
6038
+ undefined,
6039
+ generateTrackingId
6040
+ );
6041
+ const mainDataSetUrl = parser.dataSets.main.url;
6042
+ const syncResponse = {
6043
+ dataSets: [
6044
+ {
6045
+ ...createDataSet('main', 16, 1102),
6046
+ root: 'newroot',
6047
+ },
6048
+ ],
6049
+ visibleDataSetsUrl,
6050
+ locusUrl,
6051
+ locusStateElements: [],
6052
+ };
6053
+
6054
+ mockGetHashesFromLocusResponse(
6055
+ mainDataSetUrl,
6056
+ new Array(16).fill('00000000000000000000000000000000'),
6057
+ createDataSet('main', 16, 1102)
6058
+ );
6059
+ mockSendSyncRequestResponse(mainDataSetUrl, syncResponse);
6060
+
6061
+ parser.handleMessage(
6062
+ createHeartbeatMessage('main', 16, 1100, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1'),
6063
+ 'trigger sync metrics'
6064
+ );
6065
+
6066
+ await clock.tickAsync(1000);
6067
+
6068
+ assert.calledWithExactly(syncLatencyTracker.saveTimestamp, {
6069
+ key: 'internal.client.locus.sync.response',
6070
+ options: {
6071
+ meetingId: 'meeting-1',
6072
+ dataSetName: 'main',
6073
+ trackingId: 'our-sync-tracking-id',
6074
+ },
6075
+ });
6076
+ // body-mode syncs return the state elements in the /sync HTTP response, but per the LLM-only
6077
+ // design the CA metric is completed solely from Meeting#processLocusLLMEvent once the matching
6078
+ // LLM message arrives. handleMessage must not record the message-received milestone nor
6079
+ // complete the metric here.
6080
+ assert.neverCalledWith(syncLatencyTracker.saveTimestamp, {
6081
+ key: 'internal.client.locus.sync.message.received',
6082
+ options: {
6083
+ meetingId: 'meeting-1',
6084
+ dataSetName: 'main',
6085
+ trackingId: 'our-sync-tracking-id',
6086
+ },
6087
+ });
6088
+ assert.notCalled(syncLatencyTracker.completeLocusSyncLatency);
6089
+ });
6090
+
3824
6091
  });
3825
6092
  });