Skip to content

Add opt-in adaptive entity state throttling - #822

Closed
MindFreeze wants to merge 1 commit into
masterfrom
adaptive-entity-state-throttling
Closed

MindFreeze wants to merge 1 commit into
masterfrom
adaptive-entity-state-throttling

Conversation

@MindFreeze

Copy link
Copy Markdown
Member

Adds opt-in passive adaptive throttling for entityStatesColl / subscribeEntityStates via options.throttleUpdates, while keeping default behavior unchanged.

Highlights

  • Opt-in API: EntityStatesCollectionOptions (throttleUpdates?: boolean | ThrottleUpdatesOptions), flushEntityStates(conn), and Store.setState(update, overwrite?, notify?) so coll.state stays immediately consistent while subscriber notifications are coalesced.
  • Adaptive duty-cycle throttling (lib/throttle.ts):
    • Day-0 snapshot bootstrap for slow devices (initial snapshot still publishes immediately).
    • Continuous passive probe using split MessageChannel + rAF → MessageChannel (with synchronous fallback) and winsorized EMA (alpha = 0.25) to scale the cooldown interval between microtask batching (0ms) and maxIntervalMs.
    • Leading + trailing edge coalescing in place with copy-on-write safety when pending state is observed, teardown guard, and reconnect (ready) reset.
  • User-action fast-path: Flushes in the current microtask on matching userId context or recent call_service entity targets (2s lazy-pruned TTL).
  • Hidden-tab deferral: Folds updates without notifying while document.hidden is true and flushes immediately on visibilitychange (skipping EMA measurement on resume).

@MindFreeze
MindFreeze requested an adaptive review from Copilot December 3, 2026 10:31
@MindFreeze MindFreeze closed this Dec 3, 2026
@MindFreeze
MindFreeze deleted the adaptive-entity-state-throttling branch December 3, 2026 10:45

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved throttling bugs can publish partial state from rejected events, deliver updates prematurely or twice, and retain entity stores after connection closure.

6 open issues
What changed in this PR

Adds opt-in adaptive notification throttling to entity-state subscriptions while keeping stored state current and default behavior unchanged.

Changes:

  • Adds throttling options and explicit flushing.
  • Coalesces notifications with user-action fast paths and hidden-tab deferral.
  • Adds tests for adaptive timing, state consistency, and cleanup.
File Description
test/​throttle.spec.ts Tests adaptive measurements, timing, and cleanup.
test/​states.spec.ts Tests subscription integration and default behavior.
README.md Documents throttling options and explicit flushing.
lib/​util.ts Adds service-call and store-read hooks.
lib/​throttle.ts Implements adaptive notification coalescing.
lib/​store.ts Supports silent updates and state-read tracking.
lib/​states.ts Connects throttling options to entity collections.
lib/​connection.ts Reports service calls for entity-target tracking.

Review effort: Max (adaptive)

Comment thread lib/states.ts

return () => {
conn.removeEventListener("ready", markReplace);
cleanup();
Comment thread lib/states.ts
Comment on lines +266 to +267
if (!atLeastHaVersion(conn.haVersion, 2022, 4, 0)) {
return getCollection(
Comment thread lib/throttle.ts
const t0 = shouldProbe ? now() : 0;

try {
store.setState(state, true);
Comment thread lib/throttle.ts
Comment on lines +443 to +466
store.setState(state, true);
} finally {
lastPublishAt = now();
}

if (shouldProbe && !destroyed && !isDocumentHidden()) {
startProbe(t0);
}
};

const scheduleMicrotaskFlush = () => {
if (timerId !== undefined) {
clearTimeout(timerId);
timerId = undefined;
}
if (microtaskScheduled) {
return;
}
microtaskScheduled = true;
Promise.resolve().then(() => {
microtaskScheduled = false;
flush();
});
};
Comment thread lib/throttle.ts

const measureSnapshot = isReplace && !hasProbeSample;
const t0 = measureSnapshot ? now() : 0;
applyUpdates(target, ev);
Comment thread lib/throttle.ts
if (entityCount > 0) {
const msPer1k = (snapshotMs * 1000) / entityCount;
if (msPer1k > options.snapshotThresholdMsPer1k) {
emaCostMs = Math.min(MAX_SAMPLE_MS, msPer1k * SNAPSHOT_SEED_FACTOR);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants