@webex/plugin-meetings 3.12.0-next.19 → 3.12.0-next.191

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 (312) 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 +208 -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/assets/README.md +28 -0
  40. package/assets/e2ee-0.0.1.js +2 -0
  41. package/assets/e2ee-0.0.1.wasm +0 -0
  42. package/dist/aiEnableRequest/index.js +15 -2
  43. package/dist/aiEnableRequest/index.js.map +1 -1
  44. package/dist/annotation/index.js +55 -19
  45. package/dist/annotation/index.js.map +1 -1
  46. package/dist/assets/e2ee-0.0.1.js +2 -0
  47. package/dist/assets/e2ee-0.0.1.wasm +0 -0
  48. package/dist/breakouts/breakout.js +8 -3
  49. package/dist/breakouts/breakout.js.map +1 -1
  50. package/dist/breakouts/events.js +29 -14
  51. package/dist/breakouts/events.js.map +1 -1
  52. package/dist/breakouts/index.js +128 -7
  53. package/dist/breakouts/index.js.map +1 -1
  54. package/dist/common/errors/webex-errors.js +54 -5
  55. package/dist/common/errors/webex-errors.js.map +1 -1
  56. package/dist/config.js +3 -2
  57. package/dist/config.js.map +1 -1
  58. package/dist/constants.js +39 -11
  59. package/dist/constants.js.map +1 -1
  60. package/dist/controls-options-manager/index.js +46 -10
  61. package/dist/controls-options-manager/index.js.map +1 -1
  62. package/dist/hashTree/constants.js +4 -1
  63. package/dist/hashTree/constants.js.map +1 -1
  64. package/dist/hashTree/hashTreeParser.js +1096 -391
  65. package/dist/hashTree/hashTreeParser.js.map +1 -1
  66. package/dist/hashTree/utils.js +20 -0
  67. package/dist/hashTree/utils.js.map +1 -1
  68. package/dist/index.js +8 -0
  69. package/dist/index.js.map +1 -1
  70. package/dist/interceptors/dataChannelAuthToken.js +58 -16
  71. package/dist/interceptors/dataChannelAuthToken.js.map +1 -1
  72. package/dist/interceptors/locusRetry.js +24 -9
  73. package/dist/interceptors/locusRetry.js.map +1 -1
  74. package/dist/interpretation/index.js +55 -12
  75. package/dist/interpretation/index.js.map +1 -1
  76. package/dist/interpretation/interpretation.types.js +7 -0
  77. package/dist/interpretation/interpretation.types.js.map +1 -0
  78. package/dist/interpretation/siLanguage.js +1 -1
  79. package/dist/locus-info/controlsUtils.js +4 -1
  80. package/dist/locus-info/controlsUtils.js.map +1 -1
  81. package/dist/locus-info/index.js +615 -176
  82. package/dist/locus-info/index.js.map +1 -1
  83. package/dist/locus-info/infoUtils.js +36 -5
  84. package/dist/locus-info/infoUtils.js.map +1 -1
  85. package/dist/locus-info/types.js +20 -0
  86. package/dist/locus-info/types.js.map +1 -1
  87. package/dist/media/MediaConnectionAwaiter.js +229 -166
  88. package/dist/media/MediaConnectionAwaiter.js.map +1 -1
  89. package/dist/media/index.js +8 -2
  90. package/dist/media/index.js.map +1 -1
  91. package/dist/media/properties.js +4 -5
  92. package/dist/media/properties.js.map +1 -1
  93. package/dist/meeting/in-meeting-actions.js +5 -1
  94. package/dist/meeting/in-meeting-actions.js.map +1 -1
  95. package/dist/meeting/index.js +1850 -961
  96. package/dist/meeting/index.js.map +1 -1
  97. package/dist/meeting/locusMediaRequest.js +229 -82
  98. package/dist/meeting/locusMediaRequest.js.map +1 -1
  99. package/dist/meeting/muteState.js +10 -1
  100. package/dist/meeting/muteState.js.map +1 -1
  101. package/dist/meeting/request.js +5 -2
  102. package/dist/meeting/request.js.map +1 -1
  103. package/dist/meeting/util.js +42 -4
  104. package/dist/meeting/util.js.map +1 -1
  105. package/dist/meeting/voicea-meeting.js +2 -1
  106. package/dist/meeting/voicea-meeting.js.map +1 -1
  107. package/dist/meeting-info/meeting-info-v2.js +12 -5
  108. package/dist/meeting-info/meeting-info-v2.js.map +1 -1
  109. package/dist/meetings/index.js +304 -129
  110. package/dist/meetings/index.js.map +1 -1
  111. package/dist/meetings/meetings.types.js +6 -1
  112. package/dist/meetings/meetings.types.js.map +1 -1
  113. package/dist/meetings/request.js +39 -0
  114. package/dist/meetings/request.js.map +1 -1
  115. package/dist/meetings/util.js +116 -18
  116. package/dist/meetings/util.js.map +1 -1
  117. package/dist/member/index.js +10 -0
  118. package/dist/member/index.js.map +1 -1
  119. package/dist/member/types.js.map +1 -1
  120. package/dist/member/util.js +30 -0
  121. package/dist/member/util.js.map +1 -1
  122. package/dist/members/index.js +101 -43
  123. package/dist/members/index.js.map +1 -1
  124. package/dist/members/util.js +8 -1
  125. package/dist/members/util.js.map +1 -1
  126. package/dist/metrics/constants.js +7 -1
  127. package/dist/metrics/constants.js.map +1 -1
  128. package/dist/multistream/codec/constants.js +63 -0
  129. package/dist/multistream/codec/constants.js.map +1 -0
  130. package/dist/multistream/mediaRequestManager.js +62 -15
  131. package/dist/multistream/mediaRequestManager.js.map +1 -1
  132. package/dist/multistream/receiveSlot.js +9 -0
  133. package/dist/multistream/receiveSlot.js.map +1 -1
  134. package/dist/multistream/remoteMediaManager.js +32 -4
  135. package/dist/multistream/remoteMediaManager.js.map +1 -1
  136. package/dist/multistream/sendSlotManager.js +11 -1
  137. package/dist/multistream/sendSlotManager.js.map +1 -1
  138. package/dist/reachability/clusterReachability.js.map +1 -1
  139. package/dist/reachability/index.js +121 -83
  140. package/dist/reachability/index.js.map +1 -1
  141. package/dist/reachability/reachability.types.js +2 -0
  142. package/dist/reachability/reachability.types.js.map +1 -1
  143. package/dist/reachability/util.js +45 -0
  144. package/dist/reachability/util.js.map +1 -1
  145. package/dist/reactions/reactions.type.js.map +1 -1
  146. package/dist/recording-controller/index.js +1 -3
  147. package/dist/recording-controller/index.js.map +1 -1
  148. package/dist/roap/turnDiscovery.js +8 -1
  149. package/dist/roap/turnDiscovery.js.map +1 -1
  150. package/dist/types/annotation/index.d.ts +19 -0
  151. package/dist/types/common/errors/webex-errors.d.ts +36 -2
  152. package/dist/types/config.d.ts +3 -2
  153. package/dist/types/constants.d.ts +15 -2
  154. package/dist/types/controls-options-manager/index.d.ts +16 -0
  155. package/dist/types/hashTree/constants.d.ts +1 -0
  156. package/dist/types/hashTree/hashTreeParser.d.ts +201 -22
  157. package/dist/types/hashTree/utils.d.ts +7 -0
  158. package/dist/types/index.d.ts +4 -0
  159. package/dist/types/interceptors/locusRetry.d.ts +4 -4
  160. package/dist/types/interpretation/interpretation.types.d.ts +10 -0
  161. package/dist/types/locus-info/index.d.ts +106 -8
  162. package/dist/types/locus-info/infoUtils.d.ts +8 -0
  163. package/dist/types/locus-info/types.d.ts +22 -1
  164. package/dist/types/media/MediaConnectionAwaiter.d.ts +66 -49
  165. package/dist/types/media/properties.d.ts +6 -2
  166. package/dist/types/meeting/in-meeting-actions.d.ts +4 -0
  167. package/dist/types/meeting/index.d.ts +217 -16
  168. package/dist/types/meeting/locusMediaRequest.d.ts +12 -0
  169. package/dist/types/meeting/request.d.ts +1 -0
  170. package/dist/types/meeting/util.d.ts +12 -1
  171. package/dist/types/meeting-info/meeting-info-v2.d.ts +1 -0
  172. package/dist/types/meetings/index.d.ts +40 -19
  173. package/dist/types/meetings/meetings.types.d.ts +15 -0
  174. package/dist/types/meetings/request.d.ts +14 -0
  175. package/dist/types/member/index.d.ts +1 -0
  176. package/dist/types/member/types.d.ts +1 -0
  177. package/dist/types/member/util.d.ts +9 -0
  178. package/dist/types/members/index.d.ts +15 -2
  179. package/dist/types/members/util.d.ts +1 -5
  180. package/dist/types/metrics/constants.d.ts +6 -0
  181. package/dist/types/multistream/codec/constants.d.ts +7 -0
  182. package/dist/types/multistream/mediaRequestManager.d.ts +22 -5
  183. package/dist/types/multistream/remoteMediaManager.d.ts +18 -0
  184. package/dist/types/multistream/sendSlotManager.d.ts +5 -1
  185. package/dist/types/reachability/clusterReachability.d.ts +3 -3
  186. package/dist/types/reachability/index.d.ts +10 -3
  187. package/dist/types/reachability/reachability.types.d.ts +7 -0
  188. package/dist/types/reachability/util.d.ts +17 -0
  189. package/dist/types/reactions/reactions.type.d.ts +3 -0
  190. package/dist/webinar/index.js +441 -252
  191. package/dist/webinar/index.js.map +1 -1
  192. package/package.json +26 -24
  193. package/src/aiEnableRequest/ai-docs/ai-enable-request-spec.md +223 -0
  194. package/src/aiEnableRequest/index.ts +16 -0
  195. package/src/annotation/ai-docs/annotation-spec.md +236 -0
  196. package/src/annotation/index.ts +61 -29
  197. package/src/breakouts/ai-docs/breakouts-spec.md +324 -0
  198. package/src/breakouts/breakout.ts +3 -1
  199. package/src/breakouts/events.ts +33 -11
  200. package/src/breakouts/index.ts +145 -3
  201. package/src/common/errors/webex-errors.ts +56 -3
  202. package/src/config.ts +7 -3
  203. package/src/constants.ts +23 -4
  204. package/src/controls-options-manager/ai-docs/controls-options-manager-spec.md +243 -0
  205. package/src/controls-options-manager/index.ts +62 -10
  206. package/src/hashTree/ai-docs/hash-tree-spec.md +267 -0
  207. package/src/hashTree/constants.ts +7 -0
  208. package/src/hashTree/hashTreeParser.ts +861 -193
  209. package/src/hashTree/utils.ts +19 -0
  210. package/src/index.ts +7 -0
  211. package/src/interceptors/ai-docs/interceptors-spec.md +247 -0
  212. package/src/interceptors/dataChannelAuthToken.ts +59 -12
  213. package/src/interceptors/locusRetry.ts +26 -5
  214. package/src/interpretation/ai-docs/interpretation-spec.md +256 -0
  215. package/src/interpretation/index.ts +65 -10
  216. package/src/interpretation/interpretation.types.ts +11 -0
  217. package/src/locus-info/ai-docs/locus-info-spec.md +293 -0
  218. package/src/locus-info/controlsUtils.ts +3 -1
  219. package/src/locus-info/index.ts +566 -164
  220. package/src/locus-info/infoUtils.ts +41 -6
  221. package/src/locus-info/types.ts +26 -1
  222. package/src/media/MediaConnectionAwaiter.ts +229 -196
  223. package/src/media/ai-docs/media-spec.md +267 -0
  224. package/src/media/index.ts +10 -1
  225. package/src/media/properties.ts +8 -3
  226. package/src/meeting/ai-docs/meeting-spec.md +404 -0
  227. package/src/meeting/in-meeting-actions.ts +8 -0
  228. package/src/meeting/index.ts +1093 -251
  229. package/src/meeting/locusMediaRequest.ts +106 -6
  230. package/src/meeting/muteState.ts +10 -1
  231. package/src/meeting/request.ts +11 -0
  232. package/src/meeting/util.ts +53 -9
  233. package/src/meeting/voicea-meeting.ts +1 -1
  234. package/src/meeting-info/ai-docs/meeting-info-spec.md +261 -0
  235. package/src/meeting-info/meeting-info-v2.ts +11 -4
  236. package/src/meetings/ai-docs/meetings-spec.md +296 -0
  237. package/src/meetings/index.ts +202 -81
  238. package/src/meetings/meetings.types.ts +19 -0
  239. package/src/meetings/request.ts +43 -0
  240. package/src/meetings/util.ts +117 -4
  241. package/src/member/ai-docs/member-spec.md +196 -0
  242. package/src/member/index.ts +10 -0
  243. package/src/member/types.ts +1 -0
  244. package/src/member/util.ts +29 -0
  245. package/src/members/ai-docs/members-spec.md +256 -0
  246. package/src/members/index.ts +70 -7
  247. package/src/members/util.ts +12 -4
  248. package/src/metrics/ai-docs/metrics-spec.md +185 -0
  249. package/src/metrics/constants.ts +6 -0
  250. package/src/multistream/ai-docs/multistream-spec.md +295 -0
  251. package/src/multistream/codec/constants.ts +58 -0
  252. package/src/multistream/mediaRequestManager.ts +119 -28
  253. package/src/multistream/receiveSlot.ts +18 -0
  254. package/src/multistream/remoteMediaManager.ts +23 -1
  255. package/src/multistream/sendSlotManager.ts +15 -1
  256. package/src/personal-meeting-room/ai-docs/personal-meeting-room-spec.md +234 -0
  257. package/src/reachability/ai-docs/reachability-spec.md +261 -0
  258. package/src/reachability/clusterReachability.ts +3 -2
  259. package/src/reachability/index.ts +47 -16
  260. package/src/reachability/reachability.types.ts +11 -0
  261. package/src/reachability/util.ts +36 -0
  262. package/src/reactions/ai-docs/reactions-spec.md +198 -0
  263. package/src/reactions/reactions.type.ts +3 -0
  264. package/src/reconnection-manager/ai-docs/reconnection-manager-spec.md +272 -0
  265. package/src/recording-controller/ai-docs/recording-controller-spec.md +223 -0
  266. package/src/recording-controller/index.ts +1 -2
  267. package/src/roap/ai-docs/roap-spec.md +241 -0
  268. package/src/roap/turnDiscovery.ts +9 -1
  269. package/src/webinar/ai-docs/webinar-spec.md +243 -0
  270. package/src/webinar/index.ts +247 -89
  271. package/test/unit/spec/aiEnableRequest/index.ts +86 -0
  272. package/test/unit/spec/annotation/index.ts +214 -182
  273. package/test/unit/spec/breakouts/breakout.ts +9 -3
  274. package/test/unit/spec/breakouts/events.ts +120 -2
  275. package/test/unit/spec/breakouts/index.ts +336 -15
  276. package/test/unit/spec/common/errors/webex-errors.ts +78 -0
  277. package/test/unit/spec/controls-options-manager/index.js +139 -32
  278. package/test/unit/spec/hashTree/hashTreeParser.ts +2360 -239
  279. package/test/unit/spec/hashTree/utils.ts +37 -0
  280. package/test/unit/spec/interceptors/dataChannelAuthToken.ts +179 -1
  281. package/test/unit/spec/interceptors/locusRetry.ts +234 -5
  282. package/test/unit/spec/interpretation/index.ts +119 -4
  283. package/test/unit/spec/locus-info/controlsUtils.js +172 -57
  284. package/test/unit/spec/locus-info/index.js +1014 -58
  285. package/test/unit/spec/locus-info/infoUtils.js +184 -1
  286. package/test/unit/spec/media/MediaConnectionAwaiter.ts +479 -17
  287. package/test/unit/spec/media/index.ts +92 -0
  288. package/test/unit/spec/media/properties.ts +26 -26
  289. package/test/unit/spec/meeting/in-meeting-actions.ts +4 -0
  290. package/test/unit/spec/meeting/index.js +3601 -536
  291. package/test/unit/spec/meeting/locusMediaRequest.ts +406 -4
  292. package/test/unit/spec/meeting/muteState.js +81 -0
  293. package/test/unit/spec/meeting/request.js +12 -0
  294. package/test/unit/spec/meeting/utils.js +205 -19
  295. package/test/unit/spec/meeting/voicea-meeting.ts +85 -1
  296. package/test/unit/spec/meeting-info/meetinginfov2.js +88 -11
  297. package/test/unit/spec/meetings/index.js +549 -49
  298. package/test/unit/spec/meetings/request.js +141 -0
  299. package/test/unit/spec/meetings/utils.js +402 -51
  300. package/test/unit/spec/member/index.js +7 -0
  301. package/test/unit/spec/member/util.js +89 -0
  302. package/test/unit/spec/members/index.js +216 -0
  303. package/test/unit/spec/members/request.js +37 -1
  304. package/test/unit/spec/members/utils.js +63 -0
  305. package/test/unit/spec/multistream/mediaRequestManager.ts +501 -37
  306. package/test/unit/spec/multistream/remoteMediaManager.ts +46 -0
  307. package/test/unit/spec/multistream/sendSlotManager.ts +30 -2
  308. package/test/unit/spec/reachability/index.ts +128 -46
  309. package/test/unit/spec/reachability/util.ts +31 -0
  310. package/test/unit/spec/recording-controller/index.js +9 -8
  311. package/test/unit/spec/roap/turnDiscovery.ts +20 -0
  312. package/test/unit/spec/webinar/index.ts +935 -466
@@ -1,13 +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';
10
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';
11
17
 
12
18
  const visibleDataSetsUrl = 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/visibleDataSets';
13
19
 
@@ -112,6 +118,7 @@ function createDataSet(name: string, leafCount: number, version = 1) {
112
118
  name,
113
119
  idleMs: 1000,
114
120
  backoff: {maxMs: 1000, exponent: 2},
121
+ heartbeatIntervalMs: 5000,
115
122
  };
116
123
  }
117
124
 
@@ -152,31 +159,47 @@ describe('HashTreeParser', () => {
152
159
  let webexRequest: sinon.SinonStub;
153
160
  let callback: sinon.SinonStub;
154
161
  let mathRandomStub: sinon.SinonStub;
162
+ let metricsStub: sinon.SinonStub;
163
+ let loggerInfoStub: sinon.SinonStub;
155
164
 
156
165
  beforeEach(() => {
157
166
  clock = sinon.useFakeTimers();
158
167
  webexRequest = sinon.stub();
159
168
  callback = sinon.stub();
160
169
  mathRandomStub = sinon.stub(Math, 'random').returns(0);
170
+ metricsStub = sinon.stub(Metrics, 'sendBehavioralMetric');
171
+ loggerInfoStub = sinon.stub(LoggerProxy.logger, 'info');
161
172
  });
162
173
  afterEach(() => {
163
174
  clock.restore();
164
175
  mathRandomStub.restore();
176
+ metricsStub.restore();
177
+ loggerInfoStub.restore();
165
178
  });
166
179
 
167
180
  // Helper to create a HashTreeParser instance with common defaults
168
181
  function createHashTreeParser(
169
182
  initialLocus: any = exampleInitialLocus,
170
183
  metadata: any = exampleMetadata,
171
- excludedDataSets?: string[]
184
+ excludedDataSets?: string[],
185
+ syncLatencyTracker?: any,
186
+ syncLatencyMeetingId = 'meeting-1',
187
+ generateTrackingId?: any,
188
+ isLlmExpected?: () => boolean
172
189
  ) {
173
190
  return new HashTreeParser({
174
191
  initialLocus,
175
192
  metadata,
176
193
  webexRequest,
177
- locusInfoUpdateCallback: callback,
194
+ callbacks: {
195
+ locusInfoUpdateCallback: callback,
196
+ syncLatencyTracker,
197
+ generateTrackingId,
198
+ isLlmExpected,
199
+ },
178
200
  debugId: 'test',
179
201
  excludedDataSets,
202
+ syncLatencyMeetingId,
180
203
  });
181
204
  }
182
205
 
@@ -217,7 +240,7 @@ describe('HashTreeParser', () => {
217
240
  }
218
241
 
219
242
  // Helper to mock sendSyncRequestToLocus response
220
- function mockSendSyncRequestResponse(dataSetUrl: string, response: any) {
243
+ function mockSendSyncRequestResponse(dataSetUrl: string, response: any, headers?: any) {
221
244
  webexRequest
222
245
  .withArgs(
223
246
  sinon.match({
@@ -227,6 +250,7 @@ describe('HashTreeParser', () => {
227
250
  )
228
251
  .resolves({
229
252
  body: response,
253
+ headers,
230
254
  });
231
255
  }
232
256
 
@@ -567,6 +591,11 @@ describe('HashTreeParser', () => {
567
591
  },
568
592
  data: {info: {id: 'some-fake-locus-info'}},
569
593
  },
594
+ ],
595
+ });
596
+
597
+ assert.calledWith(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
598
+ updatedObjects: [
570
599
  {
571
600
  htMeta: {
572
601
  elementId: {
@@ -632,6 +661,32 @@ describe('HashTreeParser', () => {
632
661
  expect(syncCalls[2].args[0].uri).to.equal(`${atdActiveDataSet.url}/sync`);
633
662
  });
634
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
+
635
690
  it('handles sync response that has locusStateElements undefined', async () => {
636
691
  const minimalInitialLocus = {
637
692
  dataSets: [],
@@ -672,8 +727,11 @@ describe('HashTreeParser', () => {
672
727
  assert.notCalled(callback);
673
728
  });
674
729
 
675
- [404, 409].forEach((errorCode) => {
676
- 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 () => {
677
735
  const minimalInitialLocus = {
678
736
  dataSets: [],
679
737
  locus: null,
@@ -696,7 +754,6 @@ describe('HashTreeParser', () => {
696
754
  )
697
755
  .rejects(error);
698
756
 
699
- // initializeFromMessage should throw MeetingEndedError
700
757
  let thrownError;
701
758
  try {
702
759
  await parser.initializeFromMessage({
@@ -708,7 +765,7 @@ describe('HashTreeParser', () => {
708
765
  thrownError = e;
709
766
  }
710
767
 
711
- expect(thrownError).to.be.instanceOf(MeetingEndedError);
768
+ expect(thrownError).to.be.instanceOf(expectedError);
712
769
  });
713
770
  });
714
771
  });
@@ -1730,12 +1787,122 @@ describe('HashTreeParser', () => {
1730
1787
  });
1731
1788
  });
1732
1789
 
1733
- describe('emits MEETING_ENDED', () => {
1734
- [404, 409].forEach((statusCode) => {
1735
- 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 () => {
1736
1904
  const parser = createHashTreeParser();
1737
1905
 
1738
- // Send a message to trigger sync algorithm
1739
1906
  const message = {
1740
1907
  dataSets: [createDataSet('main', 16, 1100)],
1741
1908
  visibleDataSetsUrl,
@@ -1760,12 +1927,9 @@ describe('HashTreeParser', () => {
1760
1927
 
1761
1928
  const mainDataSetUrl = parser.dataSets.main.url;
1762
1929
 
1763
- // Mock getHashesFromLocus to reject with the sentinel error
1764
- const error: any = new Error(`Request failed with status ${statusCode}`);
1765
- error.statusCode = statusCode;
1766
- if (statusCode === 409) {
1767
- error.body = {errorCode: 2403004};
1768
- }
1930
+ const error: any = new Error('Request failed with status 409');
1931
+ error.statusCode = 409;
1932
+ error.body = {errorCode: 2403004};
1769
1933
  webexRequest
1770
1934
  .withArgs(
1771
1935
  sinon.match({
@@ -1775,23 +1939,22 @@ describe('HashTreeParser', () => {
1775
1939
  )
1776
1940
  .rejects(error);
1777
1941
 
1778
- // Trigger sync by advancing time
1779
1942
  await clock.tickAsync(1000);
1780
1943
 
1781
- // Verify callback was called with MEETING_ENDED
1782
1944
  assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1783
1945
 
1784
- // Verify all timers are stopped
1785
1946
  Object.values(parser.dataSets).forEach((ds: any) => {
1786
1947
  assert.isUndefined(ds.timer);
1787
1948
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1788
1949
  });
1950
+
1951
+ // Verify no sync failure metric was sent for end-meeting sentinel
1952
+ assert.notCalled(metricsStub);
1789
1953
  });
1790
1954
 
1791
- it(`when /sync returns ${statusCode}`, async () => {
1955
+ it('when /sync returns 409', async () => {
1792
1956
  const parser = createHashTreeParser();
1793
1957
 
1794
- // Send a message to trigger sync algorithm
1795
1958
  const message = {
1796
1959
  dataSets: [createDataSet('main', 16, 1100)],
1797
1960
  visibleDataSetsUrl,
@@ -1816,19 +1979,15 @@ describe('HashTreeParser', () => {
1816
1979
 
1817
1980
  const mainDataSetUrl = parser.dataSets.main.url;
1818
1981
 
1819
- // Mock getHashesFromLocus to succeed
1820
1982
  mockGetHashesFromLocusResponse(
1821
1983
  mainDataSetUrl,
1822
1984
  new Array(16).fill('00000000000000000000000000000000'),
1823
1985
  createDataSet('main', 16, 1101)
1824
1986
  );
1825
1987
 
1826
- // Mock sendSyncRequestToLocus to reject with the sentinel error
1827
- const error: any = new Error(`Request failed with status ${statusCode}`);
1828
- error.statusCode = statusCode;
1829
- if (statusCode === 409) {
1830
- error.body = {errorCode: 2403004};
1831
- }
1988
+ const error: any = new Error('Request failed with status 409');
1989
+ error.statusCode = 409;
1990
+ error.body = {errorCode: 2403004};
1832
1991
  webexRequest
1833
1992
  .withArgs(
1834
1993
  sinon.match({
@@ -1838,19 +1997,130 @@ describe('HashTreeParser', () => {
1838
1997
  )
1839
1998
  .rejects(error);
1840
1999
 
1841
- // Trigger sync by advancing time
1842
2000
  await clock.tickAsync(1000);
1843
2001
 
1844
- // Verify callback was called with MEETING_ENDED
1845
2002
  assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.MEETING_ENDED});
1846
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
+
1847
2057
  // Verify all timers are stopped
1848
2058
  Object.values(parser.dataSets).forEach((ds: any) => {
1849
2059
  assert.isUndefined(ds.timer);
1850
2060
  assert.isUndefined(ds.heartbeatWatchdogTimer);
1851
2061
  });
1852
2062
  });
1853
- });
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
+ });
1854
2124
  });
1855
2125
 
1856
2126
  it('requests only mismatched hashes during sync', async () => {
@@ -2021,66 +2291,287 @@ describe('HashTreeParser', () => {
2021
2291
  },
2022
2292
  });
2023
2293
  });
2024
- });
2025
2294
 
2026
- describe('handles visible data sets changes correctly', () => {
2027
- it('handles addition of visible data set (one that does not require async initialization)', async () => {
2028
- // 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 () => {
2029
2296
  const parser = createHashTreeParser();
2030
2297
 
2031
- // Stub updateItems on self hash tree to return true
2032
- sinon.stub(parser.dataSets.self.hashTree, 'updateItems').returns([true]);
2033
-
2034
- // Send a message with Metadata object that has a new visibleDataSets list
2035
- const message = {
2036
- dataSets: [createDataSet('self', 1, 2100), createDataSet('attendees', 8, 4000)],
2037
- visibleDataSetsUrl,
2038
- locusUrl,
2039
- locusStateElements: [
2298
+ // Send a heartbeat with a mismatched root hash to trigger runSyncAlgorithm
2299
+ const heartbeatMessage = {
2300
+ dataSets: [
2040
2301
  {
2041
- htMeta: {
2042
- elementId: {
2043
- type: 'metadata' as const,
2044
- id: 5,
2045
- version: 51,
2046
- },
2047
- dataSetNames: ['self'],
2048
- },
2049
- data: {
2050
- visibleDataSets: [
2051
- {
2052
- name: 'main',
2053
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/main',
2054
- },
2055
- {
2056
- name: 'self',
2057
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self',
2058
- },
2059
- {
2060
- name: 'atd-unmuted',
2061
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted',
2062
- },
2063
- {
2064
- name: 'attendees',
2065
- url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/attendees',
2066
- },
2067
- ], // added 'attendees'
2068
- },
2302
+ ...createDataSet('main', 16, 1100),
2303
+ root: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1', // different from ours
2069
2304
  },
2070
2305
  ],
2306
+ visibleDataSetsUrl,
2307
+ locusUrl,
2071
2308
  };
2072
2309
 
2073
- parser.handleMessage(message, 'add visible dataset');
2074
-
2075
- // Verify that 'attendees' was added to visibleDataSets
2076
- expect(parser.visibleDataSets.some((vds) => vds.name === 'attendees')).to.be.true;
2310
+ parser.handleMessage(heartbeatMessage, 'heartbeat with mismatch');
2077
2311
 
2078
- // Verify that a hash tree was created for 'attendees'
2079
- assert.exists(parser.dataSets.attendees.hashTree);
2080
- assert.equal(parser.dataSets.attendees.hashTree.numLeaves, 8);
2312
+ // The sync timer should be set
2313
+ expect(parser.dataSets.main.timer).to.not.be.undefined;
2081
2314
 
2082
- // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
2083
- assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
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);
2572
+
2573
+ // Verify callback was called with the metadata update (appears twice - processed once for visible dataset changes, once in main loop)
2574
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
2084
2575
  updatedObjects: [
2085
2576
  {
2086
2577
  htMeta: {
@@ -2292,7 +2783,7 @@ describe('HashTreeParser', () => {
2292
2783
  expect(syncCalls[1].args[0].uri).to.equal(`${newAtdActiveDataSet.url}/sync`);
2293
2784
  });
2294
2785
 
2295
- 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 () => {
2296
2787
  const parser = createHashTreeParser();
2297
2788
 
2298
2789
  // Stub updateItems on self hash tree to return true
@@ -2357,8 +2848,8 @@ describe('HashTreeParser', () => {
2357
2848
  // Wait for the async initialization (queueMicrotask) to complete
2358
2849
  await clock.tickAsync(0);
2359
2850
 
2360
- // Verify callback was called with MEETING_ENDED
2361
- 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});
2362
2853
  });
2363
2854
 
2364
2855
  it('handles removal of visible data set', async () => {
@@ -2680,7 +3171,6 @@ describe('HashTreeParser', () => {
2680
3171
  ],
2681
3172
  visibleDataSetsUrl,
2682
3173
  locusUrl,
2683
- heartbeatIntervalMs,
2684
3174
  };
2685
3175
 
2686
3176
  parser.handleMessage(heartbeatMessage, 'initial heartbeat');
@@ -2712,6 +3202,12 @@ describe('HashTreeParser', () => {
2712
3202
  })
2713
3203
  );
2714
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
+
2715
3211
  // Verify no sync requests were sent for other datasets
2716
3212
  assert.neverCalledWith(
2717
3213
  webexRequest,
@@ -2729,6 +3225,106 @@ describe('HashTreeParser', () => {
2729
3225
  );
2730
3226
  });
2731
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
+
2732
3328
  it('calls POST sync directly for leafCount === 1 data sets', async () => {
2733
3329
  const parser = createHashTreeParser();
2734
3330
  const heartbeatIntervalMs = 5000;
@@ -2744,7 +3340,6 @@ describe('HashTreeParser', () => {
2744
3340
  ],
2745
3341
  visibleDataSetsUrl,
2746
3342
  locusUrl,
2747
- heartbeatIntervalMs,
2748
3343
  };
2749
3344
 
2750
3345
  parser.handleMessage(heartbeatMessage, 'self heartbeat');
@@ -2755,6 +3350,12 @@ describe('HashTreeParser', () => {
2755
3350
  // Advance time past watchdog delay
2756
3351
  await clock.tickAsync(heartbeatIntervalMs);
2757
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
+
2758
3359
  // For leafCount === 1, performSync skips GET hashtree and goes straight to POST sync
2759
3360
  assert.neverCalledWith(
2760
3361
  webexRequest,
@@ -2774,7 +3375,6 @@ describe('HashTreeParser', () => {
2774
3375
 
2775
3376
  it('sets watchdog timers for each data set in the message', async () => {
2776
3377
  const parser = createHashTreeParser();
2777
- const heartbeatIntervalMs = 5000;
2778
3378
 
2779
3379
  // Send heartbeat with multiple datasets
2780
3380
  const heartbeatMessage = {
@@ -2791,7 +3391,6 @@ describe('HashTreeParser', () => {
2791
3391
  ],
2792
3392
  visibleDataSetsUrl,
2793
3393
  locusUrl,
2794
- heartbeatIntervalMs,
2795
3394
  };
2796
3395
 
2797
3396
  parser.handleMessage(heartbeatMessage, 'multi-dataset heartbeat');
@@ -2805,7 +3404,6 @@ describe('HashTreeParser', () => {
2805
3404
 
2806
3405
  it('resets the watchdog timer for a specific data set when a new heartbeat for it is received', async () => {
2807
3406
  const parser = createHashTreeParser();
2808
- const heartbeatIntervalMs = 5000;
2809
3407
 
2810
3408
  // Send first heartbeat for 'main'
2811
3409
  const heartbeat1 = {
@@ -2817,7 +3415,6 @@ describe('HashTreeParser', () => {
2817
3415
  ],
2818
3416
  visibleDataSetsUrl,
2819
3417
  locusUrl,
2820
- heartbeatIntervalMs,
2821
3418
  };
2822
3419
 
2823
3420
  parser.handleMessage(heartbeat1, 'first heartbeat');
@@ -2838,7 +3435,6 @@ describe('HashTreeParser', () => {
2838
3435
  ],
2839
3436
  visibleDataSetsUrl,
2840
3437
  locusUrl,
2841
- heartbeatIntervalMs,
2842
3438
  };
2843
3439
 
2844
3440
  parser.handleMessage(heartbeat2, 'second heartbeat');
@@ -2857,7 +3453,6 @@ describe('HashTreeParser', () => {
2857
3453
 
2858
3454
  it('resets the watchdog timer when a normal message (with locusStateElements) is received', async () => {
2859
3455
  const parser = createHashTreeParser();
2860
- const heartbeatIntervalMs = 5000;
2861
3456
 
2862
3457
  // Send initial heartbeat to start the watchdog for 'main'
2863
3458
  const heartbeat = {
@@ -2869,7 +3464,6 @@ describe('HashTreeParser', () => {
2869
3464
  ],
2870
3465
  visibleDataSetsUrl,
2871
3466
  locusUrl,
2872
- heartbeatIntervalMs,
2873
3467
  };
2874
3468
 
2875
3469
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2897,7 +3491,6 @@ describe('HashTreeParser', () => {
2897
3491
  data: {someData: 'value'},
2898
3492
  },
2899
3493
  ],
2900
- heartbeatIntervalMs,
2901
3494
  };
2902
3495
 
2903
3496
  parser.handleMessage(normalMessage, 'normal message');
@@ -2911,21 +3504,212 @@ describe('HashTreeParser', () => {
2911
3504
  const parser = createHashTreeParser();
2912
3505
 
2913
3506
  // Send a heartbeat message without heartbeatIntervalMs
2914
- const heartbeatMessage = createHeartbeatMessage(
2915
- 'main',
2916
- 16,
2917
- 1100,
2918
- parser.dataSets.main.hashTree.getRootHash()
2919
- );
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
+ };
2920
3518
 
2921
3519
  parser.handleMessage(heartbeatMessage, 'heartbeat without interval');
2922
3520
 
2923
3521
  expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
2924
3522
  });
2925
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
+
2926
3711
  it('stops all watchdog timers when meeting ends via sentinel message', async () => {
2927
3712
  const parser = createHashTreeParser();
2928
- const heartbeatIntervalMs = 5000;
2929
3713
 
2930
3714
  // Send heartbeat for multiple datasets
2931
3715
  const heartbeat = {
@@ -2942,7 +3726,6 @@ describe('HashTreeParser', () => {
2942
3726
  ],
2943
3727
  visibleDataSetsUrl,
2944
3728
  locusUrl,
2945
- heartbeatIntervalMs,
2946
3729
  };
2947
3730
 
2948
3731
  parser.handleMessage(heartbeat, 'initial heartbeat');
@@ -2993,7 +3776,6 @@ describe('HashTreeParser', () => {
2993
3776
  };
2994
3777
 
2995
3778
  const parser = createHashTreeParser(initialLocus, metadata);
2996
- const heartbeatIntervalMs = 5000;
2997
3779
 
2998
3780
  // Set Math.random to return 1 so that backoff = 1^exponent * maxMs = maxMs
2999
3781
  mathRandomStub.returns(1);
@@ -3015,7 +3797,6 @@ describe('HashTreeParser', () => {
3015
3797
  ],
3016
3798
  visibleDataSetsUrl,
3017
3799
  locusUrl,
3018
- heartbeatIntervalMs,
3019
3800
  };
3020
3801
 
3021
3802
  parser.handleMessage(heartbeat, 'heartbeat');
@@ -3065,7 +3846,6 @@ describe('HashTreeParser', () => {
3065
3846
 
3066
3847
  it('does not set watchdog for data sets without a hash tree', async () => {
3067
3848
  const parser = createHashTreeParser();
3068
- const heartbeatIntervalMs = 5000;
3069
3849
 
3070
3850
  // 'atd-active' is in the initial locus but is not visible (no hash tree)
3071
3851
  // Send heartbeat mentioning a non-visible dataset
@@ -3079,7 +3859,6 @@ describe('HashTreeParser', () => {
3079
3859
  ],
3080
3860
  visibleDataSetsUrl,
3081
3861
  locusUrl,
3082
- heartbeatIntervalMs,
3083
3862
  };
3084
3863
 
3085
3864
  parser.handleMessage(heartbeatMessage, 'heartbeat with non-visible dataset');
@@ -3088,125 +3867,332 @@ describe('HashTreeParser', () => {
3088
3867
  expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3089
3868
  expect(parser.dataSets['atd-active']?.heartbeatWatchdogTimer).to.be.undefined;
3090
3869
  });
3091
- });
3092
- });
3093
3870
 
3094
- describe('#callLocusInfoUpdateCallback filtering', () => {
3095
- // Helper to setup parser with initial objects and reset callback history
3096
- function setupParserWithObjects(locusStateElements: any[]) {
3097
- const parser = createHashTreeParser();
3098
-
3099
- if (locusStateElements.length > 0) {
3100
- // Determine which datasets to include based on the objects' dataSetNames
3101
- const dataSetNames = new Set<string>();
3102
- locusStateElements.forEach((element) => {
3103
- element.htMeta?.dataSetNames?.forEach((name) => dataSetNames.add(name));
3104
- });
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();
3105
3873
 
3106
- const dataSets = [];
3107
- if (dataSetNames.has('main')) dataSets.push(createDataSet('main', 16, 1100));
3108
- if (dataSetNames.has('self')) dataSets.push(createDataSet('self', 1, 2100));
3109
- if (dataSetNames.has('atd-unmuted')) dataSets.push(createDataSet('atd-unmuted', 16, 3100));
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');
3110
3876
 
3111
- const setupMessage = {
3112
- dataSets,
3877
+ const heartbeatMessage = {
3878
+ dataSets: [
3879
+ {
3880
+ ...createDataSet('main', 16, 1100),
3881
+ root: parser.dataSets.main.hashTree.getRootHash(),
3882
+ },
3883
+ ],
3113
3884
  visibleDataSetsUrl,
3114
3885
  locusUrl,
3115
- locusStateElements,
3116
3886
  };
3117
3887
 
3118
- parser.handleMessage(setupMessage, 'setup');
3119
- }
3888
+ parser.handleMessage(heartbeatMessage, 'heartbeat for non-visible dataset with hash tree');
3120
3889
 
3121
- callback.resetHistory();
3122
- return parser;
3123
- }
3890
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.be.undefined;
3891
+ });
3124
3892
 
3125
- it('filters out updates when a dataset has a higher version', () => {
3126
- const parser = setupParserWithObjects([
3127
- {
3128
- htMeta: {
3129
- elementId: {type: 'locus' as const, id: 5, version: 100},
3130
- dataSetNames: ['main'],
3131
- },
3132
- data: {existingField: 'existing'},
3133
- },
3134
- ]);
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;
3135
3896
 
3136
- // Try to update with an older version (90)
3137
- const updateMessage = {
3138
- dataSets: [createDataSet('main', 16, 1101)],
3139
- visibleDataSetsUrl,
3140
- locusUrl,
3141
- locusStateElements: [
3142
- {
3143
- htMeta: {
3144
- elementId: {type: 'locus' as const, id: 5, version: 90},
3145
- dataSetNames: ['main'],
3897
+ // Send initial heartbeat for 'main'
3898
+ const heartbeatMessage = {
3899
+ dataSets: [
3900
+ {
3901
+ ...createDataSet('main', 16, 1100),
3902
+ root: parser.dataSets.main.hashTree.getRootHash(),
3146
3903
  },
3147
- data: {someField: 'value'},
3148
- },
3149
- ],
3150
- };
3904
+ ],
3905
+ visibleDataSetsUrl,
3906
+ locusUrl,
3907
+ };
3151
3908
 
3152
- parser.handleMessage(updateMessage, 'update with older version');
3909
+ parser.handleMessage(heartbeatMessage, 'initial heartbeat');
3910
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3153
3911
 
3154
- // Callback should not be called because the update was filtered out
3155
- assert.notCalled(callback);
3156
- });
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);
3157
3920
 
3158
- it('allows updates when version is newer than existing', () => {
3159
- const parser = setupParserWithObjects([
3160
- {
3161
- htMeta: {
3162
- elementId: {type: 'locus' as const, id: 5, version: 100},
3163
- dataSetNames: ['main'],
3164
- },
3165
- data: {existingField: 'existing'},
3166
- },
3167
- ]);
3921
+ // Advance time past heartbeatIntervalMs to fire the watchdog
3922
+ await clock.tickAsync(heartbeatIntervalMs);
3168
3923
 
3169
- // Try to update with a newer version (110)
3170
- const updateMessage = {
3171
- dataSets: [createDataSet('main', 16, 1101)],
3172
- visibleDataSetsUrl,
3173
- locusUrl,
3174
- locusStateElements: [
3175
- {
3176
- htMeta: {
3177
- elementId: {type: 'locus' as const, id: 5, version: 110},
3178
- dataSetNames: ['main'],
3179
- },
3180
- data: {someField: 'new value'},
3181
- },
3182
- ],
3183
- };
3924
+ // Verify sync was triggered
3925
+ assert.calledWith(
3926
+ webexRequest,
3927
+ sinon.match({
3928
+ method: 'GET',
3929
+ uri: `${mainDataSetUrl}/hashtree`,
3930
+ })
3931
+ );
3184
3932
 
3185
- parser.handleMessage(updateMessage, 'update with newer version');
3933
+ // The watchdog timer should have been restarted after firing
3934
+ expect(parser.dataSets.main.heartbeatWatchdogTimer).to.not.be.undefined;
3186
3935
 
3187
- // Callback should be called with the update
3188
- assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
3189
- updatedObjects: [
3190
- {
3191
- htMeta: {
3192
- elementId: {type: 'locus', id: 5, version: 110},
3193
- dataSetNames: ['main'],
3194
- },
3195
- data: {someField: 'new value'},
3196
- },
3197
- ],
3198
- });
3199
- });
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);
3200
3944
 
3201
- it('filters out removal when object still exists in any dataset', () => {
3202
- const parser = setupParserWithObjects([
3203
- {
3204
- htMeta: {
3205
- elementId: {type: 'participant' as const, id: 10, version: 50},
3206
- dataSetNames: ['main', 'atd-unmuted'],
3207
- },
3208
- data: {name: 'participant'},
3209
- },
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', () => {
4081
+ // Helper to setup parser with initial objects and reset callback history
4082
+ function setupParserWithObjects(locusStateElements: any[]) {
4083
+ const parser = createHashTreeParser();
4084
+
4085
+ if (locusStateElements.length > 0) {
4086
+ // Determine which datasets to include based on the objects' dataSetNames
4087
+ const dataSetNames = new Set<string>();
4088
+ locusStateElements.forEach((element) => {
4089
+ element.htMeta?.dataSetNames?.forEach((name) => dataSetNames.add(name));
4090
+ });
4091
+
4092
+ const dataSets = [];
4093
+ if (dataSetNames.has('main')) dataSets.push(createDataSet('main', 16, 1100));
4094
+ if (dataSetNames.has('self')) dataSets.push(createDataSet('self', 1, 2100));
4095
+ if (dataSetNames.has('atd-unmuted')) dataSets.push(createDataSet('atd-unmuted', 16, 3100));
4096
+
4097
+ const setupMessage = {
4098
+ dataSets,
4099
+ visibleDataSetsUrl,
4100
+ locusUrl,
4101
+ locusStateElements,
4102
+ };
4103
+
4104
+ parser.handleMessage(setupMessage, 'setup');
4105
+ }
4106
+
4107
+ callback.resetHistory();
4108
+ return parser;
4109
+ }
4110
+
4111
+ it('filters out updates when a dataset has a higher version', () => {
4112
+ const parser = setupParserWithObjects([
4113
+ {
4114
+ htMeta: {
4115
+ elementId: {type: 'locus' as const, id: 5, version: 100},
4116
+ dataSetNames: ['main'],
4117
+ },
4118
+ data: {existingField: 'existing'},
4119
+ },
4120
+ ]);
4121
+
4122
+ // Try to update with an older version (90)
4123
+ const updateMessage = {
4124
+ dataSets: [createDataSet('main', 16, 1101)],
4125
+ visibleDataSetsUrl,
4126
+ locusUrl,
4127
+ locusStateElements: [
4128
+ {
4129
+ htMeta: {
4130
+ elementId: {type: 'locus' as const, id: 5, version: 90},
4131
+ dataSetNames: ['main'],
4132
+ },
4133
+ data: {someField: 'value'},
4134
+ },
4135
+ ],
4136
+ };
4137
+
4138
+ parser.handleMessage(updateMessage, 'update with older version');
4139
+
4140
+ // Callback should not be called because the update was filtered out
4141
+ assert.notCalled(callback);
4142
+ });
4143
+
4144
+ it('allows updates when version is newer than existing', () => {
4145
+ const parser = setupParserWithObjects([
4146
+ {
4147
+ htMeta: {
4148
+ elementId: {type: 'locus' as const, id: 5, version: 100},
4149
+ dataSetNames: ['main'],
4150
+ },
4151
+ data: {existingField: 'existing'},
4152
+ },
4153
+ ]);
4154
+
4155
+ // Try to update with a newer version (110)
4156
+ const updateMessage = {
4157
+ dataSets: [createDataSet('main', 16, 1101)],
4158
+ visibleDataSetsUrl,
4159
+ locusUrl,
4160
+ locusStateElements: [
4161
+ {
4162
+ htMeta: {
4163
+ elementId: {type: 'locus' as const, id: 5, version: 110},
4164
+ dataSetNames: ['main'],
4165
+ },
4166
+ data: {someField: 'new value'},
4167
+ },
4168
+ ],
4169
+ };
4170
+
4171
+ parser.handleMessage(updateMessage, 'update with newer version');
4172
+
4173
+ // Callback should be called with the update
4174
+ assert.calledOnceWithExactly(callback, {updateType: LocusInfoUpdateType.OBJECTS_UPDATED,
4175
+ updatedObjects: [
4176
+ {
4177
+ htMeta: {
4178
+ elementId: {type: 'locus', id: 5, version: 110},
4179
+ dataSetNames: ['main'],
4180
+ },
4181
+ data: {someField: 'new value'},
4182
+ },
4183
+ ],
4184
+ });
4185
+ });
4186
+
4187
+ it('filters out removal when object still exists in any dataset', () => {
4188
+ const parser = setupParserWithObjects([
4189
+ {
4190
+ htMeta: {
4191
+ elementId: {type: 'participant' as const, id: 10, version: 50},
4192
+ dataSetNames: ['main', 'atd-unmuted'],
4193
+ },
4194
+ data: {name: 'participant'},
4195
+ },
3210
4196
  ]);
3211
4197
 
3212
4198
  // Try to remove the object from main only (it still exists in atd-unmuted)
@@ -3545,6 +4531,9 @@ describe('HashTreeParser', () => {
3545
4531
  parser.handleMessage(emptyMessage, 'empty elements');
3546
4532
 
3547
4533
  assert.notCalled(callback);
4534
+ assert.calledWith(metricsStub, BEHAVIORAL_METRICS.HASH_TREE_EMPTY_LOCUS_STATE_ELEMENTS, {
4535
+ debugId: 'test',
4536
+ });
3548
4537
  });
3549
4538
 
3550
4539
  it('always calls callback for MEETING_ENDED regardless of filtering', () => {
@@ -3775,7 +4764,7 @@ describe('HashTreeParser', () => {
3775
4764
  });
3776
4765
  });
3777
4766
 
3778
- describe('#resume', () => {
4767
+ describe('#resumeFromMessage', () => {
3779
4768
  const createResumeMessage = (visibleDataSets?, dataSets?) => ({
3780
4769
  locusUrl,
3781
4770
  visibleDataSetsUrl,
@@ -3802,7 +4791,7 @@ describe('HashTreeParser', () => {
3802
4791
 
3803
4792
  expect(parser.state).to.equal('stopped');
3804
4793
 
3805
- parser.resume(createResumeMessage());
4794
+ parser.resumeFromMessage(createResumeMessage());
3806
4795
 
3807
4796
  expect(parser.state).to.equal('active');
3808
4797
  });
@@ -3811,7 +4800,7 @@ describe('HashTreeParser', () => {
3811
4800
  const parser = createHashTreeParser();
3812
4801
  parser.stop();
3813
4802
 
3814
- parser.resume({
4803
+ parser.resumeFromMessage({
3815
4804
  locusUrl,
3816
4805
  visibleDataSetsUrl,
3817
4806
  dataSets: [createDataSet('main', 16, 2000)],
@@ -3830,7 +4819,7 @@ describe('HashTreeParser', () => {
3830
4819
  createDataSet('self', 2, 6000),
3831
4820
  ];
3832
4821
 
3833
- parser.resume(createResumeMessage(undefined, newDataSets));
4822
+ parser.resumeFromMessage(createResumeMessage(undefined, newDataSets));
3834
4823
 
3835
4824
  expect(Object.keys(parser.dataSets)).to.have.lengthOf(2);
3836
4825
  expect(parser.dataSets.main.leafCount).to.equal(8);
@@ -3852,7 +4841,7 @@ describe('HashTreeParser', () => {
3852
4841
  {name: 'self', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/participant/713e9f99/datasets/self'},
3853
4842
  ];
3854
4843
 
3855
- parser.resume(createResumeMessage(visibleDataSets, dataSets));
4844
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
3856
4845
 
3857
4846
  expect(parser.dataSets.main.hashTree).to.be.instanceOf(HashTree);
3858
4847
  expect(parser.dataSets.self.hashTree).to.be.instanceOf(HashTree);
@@ -3866,7 +4855,7 @@ describe('HashTreeParser', () => {
3866
4855
  const handleMessageStub = sinon.stub(parser, 'handleMessage');
3867
4856
 
3868
4857
  const message = createResumeMessage();
3869
- parser.resume(message);
4858
+ parser.resumeFromMessage(message);
3870
4859
 
3871
4860
  assert.calledOnceWithExactly(handleMessageStub, message, 'on resume');
3872
4861
  });
@@ -3886,7 +4875,7 @@ describe('HashTreeParser', () => {
3886
4875
  {name: 'atd-unmuted', url: 'https://locus-a.wbx2.com/locus/api/v1/loci/97d64a5f/datasets/atd-unmuted'},
3887
4876
  ];
3888
4877
 
3889
- parser.resume(createResumeMessage(visibleDataSets, dataSets));
4878
+ parser.resumeFromMessage(createResumeMessage(visibleDataSets, dataSets));
3890
4879
 
3891
4880
  expect(parser.visibleDataSets.some((vds) => vds.name === 'atd-unmuted')).to.be.false;
3892
4881
  expect(parser.visibleDataSets.some((vds) => vds.name === 'main')).to.be.true;
@@ -3894,40 +4883,887 @@ describe('HashTreeParser', () => {
3894
4883
  });
3895
4884
  });
3896
4885
 
3897
- describe('#handleLocusUpdate when stopped', () => {
3898
- it('should return early without processing when parser is stopped', () => {
4886
+ describe('#resumeFromApiResponse', () => {
4887
+ const exampleLocus = {
4888
+ participants: [],
4889
+ } as any;
4890
+
4891
+ it('should set state to active', async () => {
3899
4892
  const parser = createHashTreeParser();
3900
4893
  parser.stop();
3901
4894
 
3902
- parser.handleLocusUpdate({
3903
- dataSets: [createDataSet('main', 16, 2000)],
3904
- locus: {participants: []},
3905
- });
4895
+ expect(parser.state).to.equal('stopped');
3906
4896
 
3907
- assert.notCalled(callback);
4897
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
4898
+
4899
+ await parser.resumeFromApiResponse(exampleLocus);
4900
+
4901
+ expect(parser.state).to.equal('active');
3908
4902
  });
3909
- });
3910
4903
 
3911
- describe('#handleMessage when stopped', () => {
3912
- it('should return early without processing when parser is stopped', () => {
4904
+ it('should reset dataSets to empty', async () => {
3913
4905
  const parser = createHashTreeParser();
4906
+
4907
+ expect(Object.keys(parser.dataSets).length).to.be.greaterThan(0);
4908
+
3914
4909
  parser.stop();
3915
4910
 
3916
- parser.handleMessage({
3917
- dataSets: [createDataSet('main', 16, 2000)],
3918
- visibleDataSetsUrl,
3919
- locusUrl,
3920
- locusStateElements: [
3921
- {
3922
- htMeta: {elementId: {type: 'self' as const, id: 4, version: 200}, dataSetNames: ['self']},
3923
- data: {id: 'new-self'},
3924
- },
3925
- ],
3926
- });
4911
+ sinon.stub(parser, 'initializeFromGetLociResponse').resolves();
3927
4912
 
3928
- assert.notCalled(callback);
4913
+ await parser.resumeFromApiResponse(exampleLocus);
4914
+
4915
+ expect(parser.dataSets).to.deep.equal({});
3929
4916
  });
3930
- });
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
+
4947
+ describe('#handleLocusUpdate when stopped', () => {
4948
+ it('should return early without processing when parser is stopped', () => {
4949
+ const parser = createHashTreeParser();
4950
+ parser.stop();
4951
+
4952
+ parser.handleLocusUpdate({
4953
+ dataSets: [createDataSet('main', 16, 2000)],
4954
+ locus: {participants: []},
4955
+ });
4956
+
4957
+ assert.notCalled(callback);
4958
+ });
4959
+ });
4960
+
4961
+ describe('#handleMessage when stopped', () => {
4962
+ it('should return early without processing when parser is stopped', () => {
4963
+ const parser = createHashTreeParser();
4964
+ parser.stop();
4965
+
4966
+ parser.handleMessage({
4967
+ dataSets: [createDataSet('main', 16, 2000)],
4968
+ visibleDataSetsUrl,
4969
+ locusUrl,
4970
+ locusStateElements: [
4971
+ {
4972
+ htMeta: {elementId: {type: 'self' as const, id: 4, version: 200}, dataSetNames: ['self']},
4973
+ data: {id: 'new-self'},
4974
+ },
4975
+ ],
4976
+ });
4977
+
4978
+ assert.notCalled(callback);
4979
+ });
4980
+ });
4981
+
4982
+ describe('#syncAllDatasets', () => {
4983
+ it('should sync all datasets that have hash trees in priority order', async () => {
4984
+ const parser = createHashTreeParser();
4985
+
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],
5006
+ visibleDataSetsUrl,
5007
+ locusUrl,
5008
+ locusStateElements: [],
5009
+ });
5010
+
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
+ });
5020
+
5021
+ await parser.syncAllDatasets();
5022
+
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`}));
5026
+
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);
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
+ });
3931
5767
 
3932
5768
  describe('#cleanUp', () => {
3933
5769
  it('should stop the parser, clear all timers and clear all dataSets', () => {
@@ -3943,7 +5779,6 @@ describe('HashTreeParser', () => {
3943
5779
  ],
3944
5780
  visibleDataSetsUrl,
3945
5781
  locusUrl,
3946
- heartbeatIntervalMs: 5000,
3947
5782
  locusStateElements: [
3948
5783
  {
3949
5784
  htMeta: {
@@ -3968,4 +5803,290 @@ describe('HashTreeParser', () => {
3968
5803
  expect(parser.dataSets).to.deep.equal({});
3969
5804
  });
3970
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
+
6091
+ });
3971
6092
  });