fix(companion): normalize heartbeat jitter random samples

This commit is contained in:
William Valentin
2026-02-16 21:56:25 -08:00
parent 239d9f93ff
commit c5bc2c1754
4 changed files with 42 additions and 2 deletions
+1 -1
View File
@@ -1202,7 +1202,7 @@ Companion runtime helper:
- lifecycle passthroughs for connection state/teardown (`connected`, `dispose(code?, reason?)`) - lifecycle passthroughs for connection state/teardown (`connected`, `dispose(code?, reason?)`)
- stream passthrough helpers (`subscribeEvents`, `subscribeEvent`, `clearEventSubscriptions`, `listKnownEventNames`, `eventSubscriptionCount`, `subscribeAgentStream/Typing/ContextWarning`, `waitForEvent`, `waitForAnyEvent`, `waitForAgentStream/Typing/ContextWarning`) - stream passthrough helpers (`subscribeEvents`, `subscribeEvent`, `clearEventSubscriptions`, `listKnownEventNames`, `eventSubscriptionCount`, `subscribeAgentStream/Typing/ContextWarning`, `waitForEvent`, `waitForAnyEvent`, `waitForAgentStream/Typing/ContextWarning`)
- runtime observability/control passthroughs (`pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `connected`, `waitForIdle()`) - runtime observability/control passthroughs (`pendingRequestCount`, `pendingEventWaitCount`, `hasPendingWork`, `connected`, `waitForIdle()`)
- `src/companion/heartbeatLoop.ts` provides `CompanionHeartbeatLoop` for periodic heartbeat scheduling (`publishHeartbeat`) with start/stop safety, optional interval jitter (`jitterRatio`) to spread load, `tickNow()` for manual sends, success/error hooks, loop observability (`successCount`, `lastSuccessAt`, `failureCount`, `lastFailure`, `getState()`), and optional auto-stop after repeated failures. - `src/companion/heartbeatLoop.ts` provides `CompanionHeartbeatLoop` for periodic heartbeat scheduling (`publishHeartbeat`) with start/stop safety, optional interval jitter (`jitterRatio`) to spread load (with safe normalization for invalid random samples), `tickNow()` for manual sends, success/error hooks, loop observability (`successCount`, `lastSuccessAt`, `failureCount`, `lastFailure`, `getState()`), and optional auto-stop after repeated failures.
## Canvas / A2UI Foundation ## Canvas / A2UI Foundation
+13
View File
@@ -950,6 +950,19 @@
], ],
"test_status": "pnpm test:run src/companion/runtimeClient.test.ts src/companion/platformClients.test.ts src/companion/heartbeatLoop.test.ts src/companion/platformClients.integration.test.ts + pnpm typecheck passing" "test_status": "pnpm test:run src/companion/runtimeClient.test.ts src/companion/platformClients.test.ts src/companion/heartbeatLoop.test.ts src/companion/platformClients.integration.test.ts + pnpm typecheck passing"
}, },
"companion-heartbeat-loop-jitter-sample-normalization": {
"status": "completed",
"date": "2026-02-17",
"updated": "2026-02-17",
"summary": "Hardened heartbeat jitter scheduling by normalizing invalid `randomFn` samples (NaN/out-of-range) before delay calculation, with regression coverage for clamped/fallback behavior.",
"files_modified": [
"src/companion/heartbeatLoop.ts",
"src/companion/heartbeatLoop.test.ts",
"README.md",
"docs/plans/state.json"
],
"test_status": "pnpm test:run src/companion/heartbeatLoop.test.ts src/companion/platformClients.test.ts src/companion/runtimeClient.test.ts src/companion/platformClients.integration.test.ts + pnpm typecheck passing"
},
"browser-tools-activation-clarity": { "browser-tools-activation-clarity": {
"status": "completed", "status": "completed",
"date": "2026-02-17", "date": "2026-02-17",
+26
View File
@@ -81,6 +81,32 @@ describe('CompanionHeartbeatLoop', () => {
loop.stop(); loop.stop();
}); });
it('normalizes invalid randomFn samples for jitter scheduling', async () => {
const publishHeartbeatHigh = vi.fn(async () => buildStatusResult());
const loopHigh = new CompanionHeartbeatLoop(
{ publishHeartbeat: publishHeartbeatHigh },
{ intervalMs: 1000, jitterRatio: 0.5, randomFn: () => 2 },
);
loopHigh.start(false);
await vi.advanceTimersByTimeAsync(1499);
expect(publishHeartbeatHigh).toHaveBeenCalledTimes(0);
await vi.advanceTimersByTimeAsync(1);
expect(publishHeartbeatHigh).toHaveBeenCalledTimes(1);
loopHigh.stop();
const publishHeartbeatNaN = vi.fn(async () => buildStatusResult());
const loopNaN = new CompanionHeartbeatLoop(
{ publishHeartbeat: publishHeartbeatNaN },
{ intervalMs: 1000, jitterRatio: 0.5, randomFn: () => Number.NaN },
);
loopNaN.start(false);
await vi.advanceTimersByTimeAsync(999);
expect(publishHeartbeatNaN).toHaveBeenCalledTimes(0);
await vi.advanceTimersByTimeAsync(1);
expect(publishHeartbeatNaN).toHaveBeenCalledTimes(1);
loopNaN.stop();
});
it('calls onSuccess with heartbeat result payload', async () => { it('calls onSuccess with heartbeat result payload', async () => {
const result = buildStatusResult(); const result = buildStatusResult();
const publishHeartbeat = vi.fn(async () => result); const publishHeartbeat = vi.fn(async () => result);
+2 -1
View File
@@ -154,7 +154,8 @@ export class CompanionHeartbeatLoop {
} }
const minFactor = 1 - this.jitterRatio; const minFactor = 1 - this.jitterRatio;
const maxFactor = 1 + this.jitterRatio; const maxFactor = 1 + this.jitterRatio;
const random = this.randomFn(); const sampled = this.randomFn();
const random = Number.isFinite(sampled) ? Math.max(0, Math.min(1, sampled)) : 0.5;
const factor = minFactor + (maxFactor - minFactor) * random; const factor = minFactor + (maxFactor - minFactor) * random;
return Math.max(1, Math.round(this.intervalMs * factor)); return Math.max(1, Math.round(this.intervalMs * factor));
} }