-
Notifications
You must be signed in to change notification settings - Fork 6
feat(experiments): Denormalize rollup metrics onto Experiment + debounced refresh #424
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shanaiabuggy
wants to merge
4
commits into
main
Choose a base branch
from
sbuggy/ase-319
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
117 changes: 117 additions & 0 deletions
117
services/intake/src/nmp/intake/spans/experiment_rollup_refresher.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """Background worker that denormalizes ClickHouse rollups onto Experiment entities. | ||
|
|
||
| Ingest marks ``(workspace, experiment_id)`` dirty — a cheap, non-blocking set add. A | ||
| background loop drains the dirty set on a fixed interval, recomputes each touched | ||
| experiment's rollup via ``get_rollups`` (which uses ``FINAL``, so it's correct under | ||
| re-ingest), and writes the summary onto the experiment's system-managed ``metrics`` | ||
| field. Bursts coalesce: many ingests for one experiment within an interval collapse to a | ||
| single recompute, and ingest latency is never gated on the rollup query. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import logging | ||
| from datetime import datetime, timezone | ||
|
|
||
| from nmp.common.entities.client import EntityClient, EntityConflictError, EntityNotFoundError | ||
| from nmp.intake.entities.experiments import Experiment | ||
| from nmp.intake.spans.experiment_rollup_repository import ExperimentRollupRepository, rollup_to_metrics | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class ExperimentRollupRefresher: | ||
| """Coalesces dirty experiment ids and refreshes their denormalized ``metrics`` on a fixed cadence.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| rollup_repository: ExperimentRollupRepository, | ||
| entity_client: EntityClient, | ||
| interval_seconds: float = 10.0, | ||
| ) -> None: | ||
| self._rollup_repository = rollup_repository | ||
| self._entity_client = entity_client | ||
| self._interval_seconds = interval_seconds | ||
| self._dirty: set[tuple[str, str]] = set() | ||
| self._task: asyncio.Task[None] | None = None | ||
| self._stopping = asyncio.Event() | ||
|
|
||
| def mark_dirty(self, *, workspace: str, experiment_id: str) -> None: | ||
| """Queue an experiment for refresh. Cheap and non-blocking; safe to call from the ingest path.""" | ||
| self._dirty.add((workspace, experiment_id)) | ||
|
|
||
| def pending(self) -> set[tuple[str, str]]: | ||
| """Return a copy of the currently-queued ``(workspace, experiment_id)`` pairs (for observability/tests).""" | ||
| return set(self._dirty) | ||
|
|
||
| def start(self) -> None: | ||
| if self._task is None: | ||
| self._stopping.clear() | ||
| self._task = asyncio.create_task(self._run()) | ||
|
|
||
| async def stop(self) -> None: | ||
| # Signal the loop to exit and let it finish any in-flight flush — we never cancel mid-flush, so a | ||
| # detached batch can't be dropped before it's written. Then a final drain covers the cases the loop | ||
| # can't (it saw the stop flag before its first flush, or items were enqueued during the last flush). | ||
| self._stopping.set() | ||
| if self._task is not None: | ||
| await self._task | ||
| self._task = None | ||
| await self.flush() | ||
|
|
||
| async def _run(self) -> None: | ||
| while not self._stopping.is_set(): | ||
| try: | ||
| # Interruptible sleep: wakes early when stop() sets the event so shutdown is prompt. | ||
| await asyncio.wait_for(self._stopping.wait(), timeout=self._interval_seconds) | ||
| except asyncio.TimeoutError: | ||
| pass # interval elapsed; time for a periodic flush | ||
| try: | ||
| await self.flush() | ||
| except Exception: | ||
| logger.exception("Experiment rollup refresh cycle failed") | ||
|
|
||
| async def flush(self) -> None: | ||
| """Drain the dirty set and write current rollups. Directly callable for deterministic tests.""" | ||
| if not self._dirty: | ||
| return | ||
| batch = self._dirty | ||
| self._dirty = set() | ||
| by_workspace: dict[str, list[str]] = {} | ||
| for workspace, experiment_id in batch: | ||
| by_workspace.setdefault(workspace, []).append(experiment_id) | ||
| for workspace, experiment_ids in by_workspace.items(): | ||
| try: | ||
| await self._refresh_workspace(workspace, experiment_ids) | ||
| except Exception: | ||
| # Re-queue the whole workspace batch for the next cycle (e.g. ClickHouse unavailable). | ||
| logger.exception("Failed to refresh experiment rollups for workspace %s; re-queuing", workspace) | ||
| for experiment_id in experiment_ids: | ||
| self._dirty.add((workspace, experiment_id)) | ||
|
|
||
| async def _refresh_workspace(self, workspace: str, experiment_ids: list[str]) -> None: | ||
| rollups = await self._rollup_repository.get_rollups(workspace=workspace, experiment_ids=experiment_ids) | ||
| refreshed_at = datetime.now(timezone.utc).isoformat() | ||
| for experiment_id in experiment_ids: | ||
| rollup = rollups.get(experiment_id) | ||
| if rollup is None: | ||
| continue | ||
| await self._write_metrics(workspace, experiment_id, rollup_to_metrics(rollup, refreshed_at=refreshed_at)) | ||
|
|
||
| async def _write_metrics(self, workspace: str, experiment_id: str, metrics: dict) -> None: | ||
| try: | ||
| experiment = await self._entity_client.get(Experiment, name=experiment_id, workspace=workspace) | ||
| except EntityNotFoundError: | ||
| # Deleted between ingest and refresh; nothing to update. | ||
| return | ||
| experiment.metrics = metrics | ||
| try: | ||
| await self._entity_client.update(experiment) | ||
| except EntityConflictError: | ||
| # A concurrent user edit won the optimistic lock; re-queue for the next cycle. | ||
| self._dirty.add((workspace, experiment_id)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.