Files
headroom/tests/test_dashboard_poll_guard_playwright.py
trs-80 3201bab560 perf(dashboard): poll once at a time and initialize once (#3470)
## Description

Two defects made the dashboard do twice the work, and then let it stack.

**`init()` ran twice on every load.** Alpine already calls an `x-data`
object's own `init()`; both templates named it in `x-init="init()"` as
well. In `dashboard.html` that started two 5-second poll timers and
registered the `R` shortcut twice, for the lifetime of the page. In
`settings.html` it fetched `/settings/schema` twice on every load. An
idle dashboard tab issued 28 requests over 30.5 seconds where 14 is the
intended cadence, and one `R` press fired two poll sequences.

**`pollDashboard()` never waited for the previous invocation.** The
timer and the `R` shortcut share it, and each run fetches at least
`/stats` and `/health`, so a slow endpoint or a repeated manual refresh
put two full sequences in flight at once.

These ship together because they are one behavior. The in-flight guard
alone does not fix the duplicate timer: two timers fire milliseconds
apart, so they rarely overlap — they just double the request rate.
`settings.html` is included because it is the identical one-line bug,
and leaving it would keep the broken pattern in the tree for the next
page to copy.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [x] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Remove `x-init="init()"` from `dashboard.html` and `settings.html`,
leaving Alpine's own single call. Each template keeps a comment saying
why the attribute is absent, so it does not get added back as an
obvious-looking fix.
- Guard `pollDashboard()` with a `polling_` flag, released in a
`finally` block: an outstanding poll makes a further invocation return
instead of stacking a second sequence, and a rejection releases the
guard rather than wedging polling permanently.
- Keep the `document.hidden` check ahead of the guard, so a hidden-tab
poll returns without ever taking it.
- Add `tests/test_dashboard_poll_guard_playwright.py`: 8 tests driving
the real Alpine component in Chromium. The filename matches CI's
`tests/test_dashboard_*_playwright.py` glob, so the existing
`test-dashboard-ui` job runs it.

A concurrent `R` press is dropped rather than queued. The in-flight poll
refreshes stats regardless, and lifetime/history/feed each keep their
own staleness interval, so queueing would be more machinery than the
case earns.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

Five of the eight new tests fail on the unchanged templates. Overlap is
made deterministic by gating `window.fetch` on a promise the test
resolves — not by racing a real timer.

### Test Output

```text
$ pytest tests/test_dashboard_poll_guard_playwright.py -q      # templates reverted, tests kept
FAILED test_no_template_asks_alpine_to_run_init_again[dashboard]
FAILED test_no_template_asks_alpine_to_run_init_again[settings]
FAILED test_the_component_initializes_once            - assert 4 == 2
FAILED test_a_second_poll_during_the_first_issues_no_further_requests
                     - assert {'inFlight': 4, 'settled': 4} == {'inFlight': 2, 'settled': 2}
FAILED test_manual_refresh_during_a_poll_does_not_duplicate_it - assert 6 == 2
5 failed, 3 passed in 5.82s

$ pytest tests/test_dashboard_poll_guard_playwright.py -q      # with this change
8 passed in 5.97s

$ pytest tests/test_dashboard_poll_guard_playwright.py tests/test_dashboard_static_assets.py \
         tests/test_dashboard_static_mime_types.py tests/test_dashboard_accessibility.py \
         tests/test_dashboard_agent_usage.py tests/test_dashboard_token_savings.py \
         tests/test_cli_dashboard.py tests/test_proxy_dashboard_stats_cache.py \
         tests/test_dashboard_cache_lifetime_playwright.py \
         tests/test_dashboard_cache_net_playwright.py \
         tests/test_dashboard_cache_ttl_playwright.py tests/test_proxy_settings_endpoints.py -q
90 passed, 1 skipped in 19.96s

$ pre-commit run --files tests/test_dashboard_poll_guard_playwright.py \
      headroom/dashboard/templates/dashboard.html headroom/dashboard/templates/settings.html
ruff (legacy alias)......................................................Passed
ruff format..............................................................Passed
mypy.....................................................................Passed
```

The three tests that pass either way are deliberate preservation checks:
a poll after the first completes still runs, a rejected poll releases
the guard, and a hidden tab still skips unforced polls.

## Real Behavior Proof

- Environment: macOS 15.6, Python 3.13.11, Playwright 1.52.0 with
Chromium Headless Shell 136.0.7103.25, branch based on `main` @
`e67b3c8a`.
- Exact command / steps: opened the dashboard in a real browser against
fully mocked routes, touched nothing, and counted every request over a
30.5-second window, then read `statsPollMs` back out of the live
component. Ran identically against the unchanged templates and against
this change. Separately re-ran an interaction script — load,
Lifetime/Session switch, theme toggle, request-row expansion, live-feed
drawer open and Escape, one poll cycle — recording every request,
console message and page error on both.
- Observed result: idle tab **28 to 14 requests** over the same window;
poll sequences after load **12 to 6**; opening load **4 to 2** requests;
`statsPollMs` still 5000, so the cadence is unchanged and every removed
request was duplicate work. The settings page went from 2 to 1
`/settings/schema` fetches per load. The interaction script went **14 to
10 requests**, with strictly fewer console warnings (the duplicate
render pass is gone) and no new errors of any kind.
- Not tested: no latency or CPU measurement was taken, and none is
claimed — the result is request count. Not exercised against a live
proxy: all endpoints are mocked, as in the existing dashboard browser
suites. Not tested on Windows, Edge or Safari; not tested with a
genuinely slow upstream, only with a fetch the test holds open
deliberately. No verification of behavior across an Alpine major-version
upgrade, where automatic `init()` invocation is the assumption this
rests on.

## Runtime Rollout Safety

- Rollout-managed feature(s): None. The dashboard UI is not
rollout-gated.
- Minimum rollout channel: N/A — no rollout-managed feature is touched.
- Stable/default behavior changed: Yes, and deliberately: the dashboard
now makes half as many requests when idle, and a poll or manual refresh
issued while one is already outstanding is skipped instead of
duplicated. Displayed data, refresh cadence and hidden-tab behavior are
unchanged.
- Kill switch / disable path: N/A — no flag. Reverting the commit
restores both the duplicate `init()` and the unguarded poll.
- Unsafe override required: No.
- Qualification impact: None. No provider, proxy, optimization or
persistence path is touched; the change is confined to two HTML
templates and one new test file.
- Rollback path: `git revert` of this commit, single step, no data or
schema involved.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

None. The dashboard looks identical; what changed is the request count,
recorded above.

## Additional Notes

- No documentation file needed changing; the two template comments are
the documentation this needs, placed where someone would otherwise
re-add the attribute.
- No `clearInterval` teardown was added. Nothing destroys the component,
and a single interval living as long as the page is pre-existing and
outside this change — it is the *second* interval that was the bug.
- No timer-cadence assertion is committed. Proving "one tick per five
seconds" needs a wall-clock wait and would be flaky in CI; cadence is
verified in the measurement above instead, and the committed load-count
test pins the duplicate `init()`, which is the only way a second timer
can come to exist.
- Unrelated and left alone: `tests/test_dashboard/test_live_feed.py`
fails 4 tests on a clean checkout because it needs a live proxy on
`localhost:8787`; CI already excludes that file.
`tests/test_dashboard_cache_ttl_playwright.py` writes
`dashboard-cache-ttl-main.png` into the repository root on every run, so
it shows up as a modified tracked file.
2026-09-11 20:41:54 -07:00

187 lines
6.5 KiB
Python

"""One dashboard poll runs at a time.
A five-second ``setInterval`` and the ``R`` shortcut both call
``pollDashboard()``, which never waited for a previous invocation to finish.
Each invocation fetches ``/stats`` and ``/health``, so a slow endpoint or a
repeated manual refresh put two full sequences in flight at once.
These tests drive the real Alpine component in a browser. They gate
``window.fetch`` on a promise the test resolves, which is what makes "while the
first request is still pending" a deterministic state rather than a race.
"""
from __future__ import annotations
from collections.abc import Iterator
import pytest
from headroom.dashboard import get_dashboard_html, get_settings_html
from tests.test_dashboard_cache_net_playwright import _open_dashboard
from tests.test_dashboard_cache_ttl_playwright import _sample_stats
playwright = pytest.importorskip("playwright.sync_api")
Page = playwright.Page
sync_playwright = playwright.sync_playwright
# Replaces fetch with a call recorder that hangs until the test releases it,
# and stops the interval so the test drives pollDashboard() itself.
_GATE_FETCH = """
() => {
const component = Alpine.$data(document.body);
clearInterval(component.pollInterval);
window.__urls = [];
const gate = new Promise((resolve) => { window.__release = resolve; });
window.fetch = (url) => {
window.__urls.push(String(url));
return gate.then(() => new Response('{}', {
status: 200,
headers: { 'content-type': 'application/json' },
}));
};
}
"""
# One poll fetches /stats and /health together.
FETCHES_PER_POLL = 2
@pytest.fixture
def page() -> Iterator[Page]: # type: ignore[valid-type]
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
_open_dashboard(page, _sample_stats())
page.evaluate(_GATE_FETCH)
yield page
browser.close()
@pytest.mark.parametrize(
"html",
[get_dashboard_html(), get_settings_html()],
ids=["dashboard", "settings"],
)
def test_no_template_asks_alpine_to_run_init_again(html: str) -> None:
"""Both templates had it; the settings page fetched its schema twice."""
assert 'x-init="init()"' not in html
def test_the_component_initializes_once() -> None:
"""Alpine calls the x-data object's ``init()`` itself.
Naming it in ``x-init`` as well ran it twice: two 5s poll timers, two R
shortcut listeners and two opening fetch sequences, for the lifetime of the
page. Counting the opening sequence is enough to pin it — the duplicate
timer and listener can only exist if ``init()`` ran more than once.
"""
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
polled: list[str] = []
page.on(
"request",
lambda request: (
polled.append(request.url)
if "/stats" in request.url or "/health" in request.url
else None
),
)
_open_dashboard(page, _sample_stats())
assert len(polled) == FETCHES_PER_POLL, polled
browser.close()
def _url_count(page: Page) -> int: # type: ignore[valid-type]
return int(page.evaluate("() => window.__urls.length"))
def test_a_second_poll_during_the_first_issues_no_further_requests(page: Page) -> None: # type: ignore[valid-type]
"""The timer's entry point: two unforced polls, one fetch sequence."""
counts = page.evaluate(
"""async () => {
const component = Alpine.$data(document.body);
const first = component.pollDashboard();
const second = component.pollDashboard();
const inFlight = window.__urls.length;
window.__release();
await Promise.all([first, second]);
return { inFlight, settled: window.__urls.length };
}"""
)
assert counts == {"inFlight": FETCHES_PER_POLL, "settled": FETCHES_PER_POLL}
def test_a_poll_after_the_first_completes_still_runs(page: Page) -> None: # type: ignore[valid-type]
"""The guard suppresses overlap, not the next scheduled refresh."""
page.evaluate(
"""async () => {
const component = Alpine.$data(document.body);
const first = component.pollDashboard();
window.__release();
await first;
await component.pollDashboard();
}"""
)
assert _url_count(page) == 2 * FETCHES_PER_POLL
def test_manual_refresh_during_a_poll_does_not_duplicate_it(page: Page) -> None: # type: ignore[valid-type]
"""The R shortcut shares the guard, and works again once the poll lands."""
# Deliberately not returned: evaluate() awaits a returned promise, and this
# one cannot settle until the gate is released further down.
page.evaluate("() => { Alpine.$data(document.body).pollDashboard(); }")
assert _url_count(page) == FETCHES_PER_POLL
page.keyboard.press("r")
page.wait_for_timeout(100)
assert _url_count(page) == FETCHES_PER_POLL
page.evaluate("() => window.__release()")
page.wait_for_timeout(100)
page.keyboard.press("r")
page.wait_for_timeout(100)
assert _url_count(page) == 2 * FETCHES_PER_POLL
def test_a_failed_poll_releases_the_guard(page: Page) -> None: # type: ignore[valid-type]
"""A rejection must not wedge the dashboard on stale numbers forever."""
recovered = page.evaluate(
"""async () => {
const component = Alpine.$data(document.body);
component.fetchStats = () => Promise.reject(new Error('boom'));
await component.pollDashboard().catch(() => {});
let calls = 0;
component.fetchStats = () => { calls += 1; return Promise.resolve(); };
await component.pollDashboard();
return calls;
}"""
)
assert recovered == 1
def test_a_hidden_tab_still_skips_unforced_polls(page: Page) -> None: # type: ignore[valid-type]
"""Guarding must not cost the existing background-tab saving."""
counts = page.evaluate(
"""async () => {
Object.defineProperty(document, 'hidden', {
configurable: true,
get: () => true,
});
const component = Alpine.$data(document.body);
component.pollDashboard();
const unforced = window.__urls.length;
component.pollDashboard(true);
return { unforced, forced: window.__urls.length };
}"""
)
assert counts == {"unforced": 0, "forced": FETCHES_PER_POLL}