Repository navigation
feat(dashboard): serve run inventory from Redis at /api/v1/inspect/inventory #388
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
Merged
Merged
Changes from all commits
Commits
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
Empty file.
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,80 @@ | ||
| import asyncio | ||
| import json | ||
| import time | ||
| from dataclasses import dataclass | ||
| from datetime import UTC, datetime | ||
| from typing import Literal | ||
|
|
||
| from server import openrl_status | ||
| from server.model_metadata import decode_model_metadata | ||
| from server.store import get_state_store | ||
|
|
||
| CACHE_SECONDS, STALE_SECONDS, READ_TIMEOUT_SECONDS = 5, 60, 6 | ||
| Lifecycle = Literal["ended", "active"] | ||
|
|
||
|
|
||
| @dataclass | ||
| class Entry: | ||
| at: float = 0.0 | ||
| task: asyncio.Future | None = None | ||
| last_good: asyncio.Future | None = None | ||
| last_good_at: float = 0.0 | ||
|
|
||
|
|
||
| cache: dict[str, Entry] = {} | ||
|
|
||
|
|
||
| def succeeded(task: asyncio.Future | None) -> bool: | ||
| return task is not None and task.done() and not task.cancelled() and task.exception() is None | ||
|
|
||
|
|
||
| async def cached(name: str, seconds: float, read) -> object: | ||
| entry = cache.setdefault(name, Entry()) | ||
| task = entry.task | ||
| if succeeded(task): | ||
| entry.last_good, entry.last_good_at = task, entry.at | ||
| if task is None or (task.done() and (not succeeded(task) or time.monotonic() - entry.at > seconds)): | ||
| entry.at, entry.task = time.monotonic(), asyncio.ensure_future(read()) | ||
| entry.task.add_done_callback(lambda t: t.cancelled() or t.exception()) # retrieved, so asyncio does not log it | ||
| if succeeded(entry.task): | ||
| return entry.task.result() | ||
| if entry.last_good is not None and time.monotonic() - entry.last_good_at <= STALE_SECONDS: | ||
| return entry.last_good.result() | ||
| return await asyncio.shield(entry.task) | ||
|
|
||
|
|
||
| async def snapshot() -> dict: | ||
| return await cached("inventory", CACHE_SECONDS, read) | ||
|
|
||
|
|
||
| def lifecycle(status: str, live: bool) -> Lifecycle: | ||
| return "active" if status == "active" and live else "ended" | ||
|
|
||
|
|
||
| def join(run_id: str, raw: str, live: set[str]) -> dict: | ||
| row, meta = json.loads(raw), decode_model_metadata(raw) | ||
| name = row.get("name") or row.get("run_name") | ||
| run = {"run_id": run_id, "name": name or f"{(meta.base_model or 'Run').split('/')[-1]} · {run_id[:8]}", "display_name": name} | ||
| run.update(model=meta.base_model, recipe_name=row.get("recipe_name"), fine_tuning_type=meta.fine_tuning_type, client_status=meta.status) | ||
| run["lifecycle"] = lifecycle(meta.status, any(s in live for s in meta.session_ids)) | ||
| run.update(created_at=meta.created_at, completed_at=meta.completed_at, session_ids=meta.session_ids, settings=openrl_status.settings_of(meta)) | ||
| return run | {"shared_runtime": meta.runtime(run_id) != run_id} | ||
|
|
||
|
|
||
| async def read() -> dict: | ||
| store, observed_at = get_state_store(), datetime.now(UTC).isoformat(timespec="seconds") | ||
| scans = [asyncio.wait_for(store.scan_values(prefix), READ_TIMEOUT_SECONDS) for prefix in ("open_rl:model_meta:", "open_rl:session:")] | ||
| metas, sessions = await asyncio.gather(*scans, return_exceptions=True) | ||
| errors, runs = [], [] | ||
| if failed := next((r for r in (metas, sessions) if isinstance(r, Exception)), None): | ||
| errors.append(f"Redis read failed: {f'no reply in {READ_TIMEOUT_SECONDS} s' if isinstance(failed, TimeoutError) else failed}") | ||
| metas, sessions = {}, {} | ||
| live = {name.removeprefix("open_rl:session:") for name in sessions} | ||
| for name, raw in metas.items(): | ||
| run_id = name.removeprefix("open_rl:model_meta:") | ||
| try: | ||
| runs.append(join(run_id, raw, live)) | ||
| except Exception as exc: | ||
| errors.append(f"model record {run_id} unreadable: {exc}") | ||
| runs.sort(key=lambda r: -r["created_at"]) | ||
| return {"observed_at": observed_at, "errors": errors, "runs": runs} |
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,13 @@ | ||
| from fastapi import APIRouter | ||
|
|
||
| from server.dashboard import fleet | ||
|
|
||
| router = APIRouter(tags=["inspection"]) | ||
|
|
||
|
|
||
| @router.get("/api/v1/inspect/inventory") | ||
| async def inventory(): | ||
| """Runs with their lifecycle (ended, active) and an error per unavailable source or unreadable run record. client_status is | ||
| what the client last reported, active until it deletes the model, so a crashed run stays active there; lifecycle is ended | ||
| once none of the run's sessions is live.""" | ||
| return await fleet.snapshot() | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import asyncio | ||
| import unittest | ||
| from unittest import mock | ||
|
|
||
| from fastapi.testclient import TestClient | ||
|
|
||
| from server import api_server | ||
| from server.dashboard import fleet | ||
| from server.model_metadata import TrainingModelMetadata | ||
| from server.store import InMemoryStateStore | ||
|
|
||
|
|
||
| def meta(**fields) -> str: | ||
| return TrainingModelMetadata(base_model="Qwen/Qwen3-8B", **fields).model_dump_json() | ||
|
|
||
|
|
||
| class InventoryTest(unittest.TestCase): | ||
| def inventory(self, **records: str) -> dict: | ||
| store = InMemoryStateStore() | ||
| for key, value in records.items(): | ||
| asyncio.run(store.set_value(f"open_rl:{key}", value)) | ||
| fleet.cache.clear() | ||
| self.enterContext(mock.patch.object(fleet, "get_state_store", return_value=store)) | ||
| return TestClient(api_server.app).get("/api/v1/inspect/inventory").json() | ||
|
|
||
| def test_a_run_is_active_only_while_the_client_has_a_live_session(self): | ||
| body = self.inventory( | ||
| **{ | ||
| "model_meta:live": meta(session_ids=["s1"], created_at=3), | ||
| "model_meta:idle": meta(session_ids=["s2"], created_at=2), | ||
| "model_meta:done": meta(status="completed", session_ids=["s1"], created_at=1), | ||
| "session:s1": "{}", | ||
| } | ||
| ) | ||
|
|
||
| runs = [(r["run_id"], r["lifecycle"], r["client_status"]) for r in body["runs"]] | ||
| self.assertEqual(runs, [("live", "active", "active"), ("idle", "ended", "active"), ("done", "ended", "completed")]) | ||
| self.assertEqual(body["errors"], []) | ||
|
|
||
| def test_a_malformed_model_record_is_skipped_with_an_error(self): | ||
| body = self.inventory(**{"model_meta:good": meta(), "model_meta:bad": "not json"}) | ||
|
|
||
| self.assertEqual([r["run_id"] for r in body["runs"]], ["good"]) | ||
| self.assertTrue(any("bad" in error for error in body["errors"]), body["errors"]) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am curious why doesn't this API maps to the shapes we know:
/api/v1/sessions ?
/api/v1/runs ?
/api/v1/jobs ?
/api/v1/models ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have later PR's that will add the routes like this from the big dashboard PR's here is the list:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not particularly strong on any of the names so we can change them
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Lets go with this. since they are all routed to "/api/v1/inspect" so independent from the post training api, probably fine to keep it in api-server for simplicity of deployment.