Skip to content

Commit e12e05f

Browse files
authored
Merge pull request #4632 from Duang777/codex/optimize-core-hotpath-6
perf(status): reuse run history scan for contract checks
2 parents f2c4a27 + bb8c20d commit e12e05f

7 files changed

Lines changed: 508 additions & 30 deletions

File tree

‎examples/control_plane/status-collection-readmodel-smoke.py‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from pathlib import Path
88
import sys
99
import tempfile
10+
from types import SimpleNamespace
1011
from typing import Any
1112

1213

@@ -117,6 +118,7 @@ def assert_wrapper_parity(registry_path: Path, runtime_root: Path, scan_root: Pa
117118
def assert_context_orchestration() -> None:
118119
calls: list[tuple[str, dict[str, Any]]] = []
119120
runtime_root = Path("/tmp/status-collection-runtime")
121+
history_audit = object()
120122

121123
def record(name: str, value: Any) -> Any:
122124
calls.append((name, value if isinstance(value, dict) else {"value": value}))
@@ -136,23 +138,28 @@ def resolve_runtime_root(
136138
assert registry_path == Path("registry.json"), registry_path
137139
return runtime_root
138140

139-
def collect_history(**kwargs: Any) -> dict[str, Any]:
141+
def collect_status_history(**kwargs: Any) -> SimpleNamespace:
140142
assert kwargs["limit"] == 20, kwargs
141143
assert kwargs["goal_id"] == GOAL_ID, kwargs
142-
assert kwargs["include_runtime_goals"] is True, kwargs
143-
return record(
144-
"collect_history",
144+
assert kwargs["status_include_runtime_goals"] is True, kwargs
145+
history = record(
146+
"collect_status_history",
145147
{
146148
"goal_count": 1,
147149
"run_count": 0,
148150
"goals": [],
149151
"activation_state_filter": kwargs.get("activation_state_filter"),
150152
},
151153
)
154+
return SimpleNamespace(
155+
status_history=history,
156+
contract_audit=history_audit,
157+
)
152158

153159
def check_contract(**kwargs: Any) -> dict[str, Any]:
154160
assert kwargs["limit"] == 2, kwargs
155161
assert kwargs["goal_id_filter"] == GOAL_ID, kwargs
162+
assert kwargs["history_audit"] is history_audit, kwargs
156163
return record(
157164
"check_contract",
158165
{
@@ -186,7 +193,7 @@ def build_attention_queue(**kwargs: Any) -> dict[str, Any]:
186193
"collect_global_registry_health",
187194
{"ok": True, "current_registry_is_global": True},
188195
),
189-
collect_history=collect_history,
196+
collect_status_history=collect_status_history,
190197
check_contract=check_contract,
191198
build_attention_queue=build_attention_queue,
192199
build_runtime_summaries=lambda **kwargs: record(
@@ -229,7 +236,9 @@ def build_attention_queue(**kwargs: Any) -> dict[str, Any]:
229236
context=context,
230237
)
231238

232-
history_call = next(call for call in calls if call[0] == "collect_history")
239+
history_call = next(
240+
call for call in calls if call[0] == "collect_status_history"
241+
)
233242
assert history_call[1]["activation_state_filter"] == "active", history_call
234243
contract_call = next(call for call in calls if call[0] == "check_contract")
235244
assert contract_call[1]["activation_state_filter"] == "active", contract_call
@@ -257,7 +266,7 @@ def build_attention_queue(**kwargs: Any) -> dict[str, Any]:
257266
assert [name for name, _ in calls][:4] == [
258267
"load_registry",
259268
"collect_global_registry_health",
260-
"collect_history",
269+
"collect_status_history",
261270
"check_contract",
262271
], calls
263272

‎loopx/contract.py‎

Lines changed: 55 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@
2323
index_identity,
2424
)
2525
from .control_plane.todos.active_state_editing import COMPLETED_WORK_ARCHIVE_HEADING
26-
from .history import collect_history, load_registry
26+
from .history import (
27+
RunHistoryAudit,
28+
build_run_history_audit,
29+
collect_history,
30+
load_registry,
31+
)
2732
from .paths import DEFAULT_RUNTIME_ROOT, rel_or_abs, resolve_runtime_root
2833
from .registry import inspect_registry, inspect_registry_boundary, registry_goals, resolve_state_file
2934
from .state_projection import state_projection_gap_warning
@@ -877,6 +882,7 @@ def check_contract(
877882
goal_id_filter: str | None = None,
878883
activation_state_filter: GoalActivationState | str | None = None,
879884
include_public_boundary_scan: bool = True,
885+
history_audit: RunHistoryAudit | None = None,
880886
) -> dict[str, Any]:
881887
error_diagnostics: list[dict[str, Any]] = []
882888
warnings: list[str] = []
@@ -953,34 +959,70 @@ def add_global_error(code: str, message: str) -> None:
953959
else:
954960
warnings.append(f"runtime root does not exist yet: {runtime_root}")
955961

956-
history = collect_history(
962+
if history_audit is None:
963+
history = collect_history(
964+
registry_path=registry_path,
965+
runtime_root=runtime_root,
966+
goal_id=goal_id_filter,
967+
limit=limit,
968+
activation_state_filter=activation_state_filter,
969+
)
970+
history_audit = build_run_history_audit(
971+
history,
972+
registry_path=registry_path,
973+
runtime_root=runtime_root,
974+
goal_id=goal_id_filter,
975+
activation_state_filter=activation_state_filter,
976+
include_runtime_goals=True,
977+
)
978+
elif not history_audit.matches(
957979
registry_path=registry_path,
958980
runtime_root=runtime_root,
959981
goal_id=goal_id_filter,
960-
limit=limit,
961982
activation_state_filter=activation_state_filter,
983+
include_runtime_goals=True,
984+
):
985+
raise ValueError("history audit scope does not match contract request")
986+
checks.append(
987+
f"run-history goals={history_audit.goal_count} runs={history_audit.run_count}"
962988
)
963-
checks.append(f"run-history goals={history.get('goal_count')} runs={history.get('run_count')}")
964-
for item in history.get("goals") or []:
965-
raw = int(item.get("raw_index_records") or 0)
966-
unique = int(item.get("unique_runs") or 0)
967-
if item.get("legacy_runtime_goal") and raw > unique:
968-
checks.append(f"{item.get('id')}: legacy runtime goal has duplicate rows raw={raw} unique={unique}")
989+
for item in history_audit.goals:
990+
raw = item.raw_index_records
991+
unique = item.unique_runs
992+
if item.legacy_runtime_goal and raw > unique:
993+
checks.append(
994+
f"{item.goal_id}: legacy runtime goal has duplicate rows "
995+
f"raw={raw} unique={unique}"
996+
)
969997
continue
970998
if raw > unique:
971-
duplicate_summary = _index_duplicate_summary(Path(str(item.get("index_path") or "")))
999+
duplicate_summary = _index_duplicate_summary(item.index_path)
9721000
if duplicate_summary.get("unexpected_duplicate_rows"):
973-
warnings.append(_index_duplicate_warning(item.get("id"), raw, unique, duplicate_summary))
1001+
warnings.append(
1002+
_index_duplicate_warning(
1003+
item.goal_id,
1004+
raw,
1005+
unique,
1006+
duplicate_summary,
1007+
)
1008+
)
9741009
else:
9751010
emitted_check = False
9761011
if duplicate_summary.get("reward_overlay_rows"):
9771012
emitted_check = True
9781013
checks.append(
979-
f"{item.get('id')}: reward overlay rows raw={raw} unique={unique} "
1014+
f"{item.goal_id}: reward overlay rows raw={raw} unique={unique} "
9801015
f"overlays={duplicate_summary.get('reward_overlay_rows')}"
9811016
)
9821017
if not emitted_check:
983-
warnings.append(_index_duplicate_warning(item.get("id"), raw, unique, duplicate_summary))
1018+
warnings.append(
1019+
_index_duplicate_warning(
1020+
item.goal_id,
1021+
raw,
1022+
unique,
1023+
duplicate_summary,
1024+
)
1025+
)
9841026

9851027
if include_public_boundary_scan:
9861028
boundary = scan_public_boundary(scan_roots, registry=registry)

‎loopx/control_plane/status/collection.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class StatusCollectionContext:
4949
load_registry: StatusCallback
5050
resolve_runtime_root: StatusCallback
5151
collect_global_registry_health: StatusCallback
52-
collect_history: StatusCallback
52+
collect_status_history: StatusCallback
5353
check_contract: StatusCallback
5454
build_attention_queue: StatusCallback
5555
build_runtime_summaries: StatusCallback
@@ -102,15 +102,16 @@ def collect_status(
102102
current_registry=registry,
103103
)
104104
include_runtime_goals = bool(global_registry.get("current_registry_is_global"))
105-
history = context.collect_history(
105+
history_collection = context.collect_status_history(
106106
registry_path=registry_path,
107107
runtime_root=runtime_root,
108108
goal_id=goal_filter,
109109
limit=control_plane_limit,
110-
include_runtime_goals=include_runtime_goals,
110+
status_include_runtime_goals=include_runtime_goals,
111111
activation_state_filter=activation_filter,
112112
agent_lane_id=agent_lane_id,
113113
)
114+
history = history_collection.status_history
114115
contract = context.check_contract(
115116
registry_path=registry_path,
116117
runtime_root_override=str(runtime_root),
@@ -119,6 +120,7 @@ def collect_status(
119120
goal_id_filter=goal_filter,
120121
include_public_boundary_scan=include_public_boundary_scan,
121122
activation_state_filter=activation_filter,
123+
history_audit=history_collection.contract_audit,
122124
)
123125
contract = project_contract_health_for_goal(contract, goal_id=goal_filter)
124126
queue = context.build_attention_queue(

‎loopx/history.py‎

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import json
44
from contextlib import nullcontext
55
from collections.abc import Callable
6+
from dataclasses import dataclass
67
from datetime import datetime, timezone
78
from heapq import merge
89
from itertools import islice
@@ -71,6 +72,55 @@
7172
)
7273

7374

75+
@dataclass(frozen=True, slots=True)
76+
class RunIndexAudit:
77+
goal_id: str
78+
index_path: Path
79+
raw_index_records: int
80+
unique_runs: int
81+
legacy_runtime_goal: bool
82+
83+
84+
@dataclass(frozen=True, slots=True)
85+
class RunHistoryAudit:
86+
registry_path: Path
87+
runtime_root: Path
88+
goal_id: str | None
89+
activation_state_filter: str | None
90+
include_runtime_goals: bool
91+
goal_count: int
92+
run_count: int
93+
goals: tuple[RunIndexAudit, ...]
94+
95+
def matches(
96+
self,
97+
*,
98+
registry_path: Path,
99+
runtime_root: Path,
100+
goal_id: str | None,
101+
activation_state_filter: GoalActivationState | str | None,
102+
include_runtime_goals: bool,
103+
) -> bool:
104+
normalized_activation = (
105+
normalize_goal_activation_state(activation_state_filter).value
106+
if activation_state_filter is not None
107+
else None
108+
)
109+
return (
110+
self.registry_path == registry_path.expanduser().resolve()
111+
and self.runtime_root == runtime_root.expanduser().resolve()
112+
and self.goal_id == (str(goal_id or "").strip() or None)
113+
and self.activation_state_filter == normalized_activation
114+
and self.include_runtime_goals is include_runtime_goals
115+
)
116+
117+
118+
@dataclass(frozen=True, slots=True)
119+
class StatusHistoryCollection:
120+
status_history: dict[str, Any]
121+
contract_audit: RunHistoryAudit
122+
123+
74124
def now_local() -> str:
75125
return now_local_iso()
76126

@@ -386,6 +436,116 @@ def collect_history(
386436
}
387437

388438

439+
def build_run_history_audit(
440+
history: dict[str, Any],
441+
*,
442+
registry_path: Path,
443+
runtime_root: Path,
444+
goal_id: str | None,
445+
activation_state_filter: GoalActivationState | str | None,
446+
include_runtime_goals: bool,
447+
) -> RunHistoryAudit:
448+
normalized_activation = (
449+
normalize_goal_activation_state(activation_state_filter).value
450+
if activation_state_filter is not None
451+
else None
452+
)
453+
return RunHistoryAudit(
454+
registry_path=registry_path.expanduser().resolve(),
455+
runtime_root=runtime_root.expanduser().resolve(),
456+
goal_id=str(goal_id or "").strip() or None,
457+
activation_state_filter=normalized_activation,
458+
include_runtime_goals=include_runtime_goals,
459+
goal_count=int(history.get("goal_count") or 0),
460+
run_count=int(history.get("run_count") or 0),
461+
goals=tuple(
462+
RunIndexAudit(
463+
goal_id=str(item.get("id") or ""),
464+
index_path=Path(str(item.get("index_path") or "")),
465+
raw_index_records=int(item.get("raw_index_records") or 0),
466+
unique_runs=int(item.get("unique_runs") or 0),
467+
legacy_runtime_goal=bool(item.get("legacy_runtime_goal")),
468+
)
469+
for item in history.get("goals") or []
470+
if isinstance(item, dict)
471+
),
472+
)
473+
474+
475+
def history_for_registry_members(
476+
history: dict[str, Any],
477+
*,
478+
limit: int,
479+
) -> dict[str, Any]:
480+
goals = [
481+
goal
482+
for goal in history.get("goals") or []
483+
if isinstance(goal, dict) and goal.get("registry_member") is True
484+
]
485+
recent_limit = max(0, limit)
486+
recent_runs = list(
487+
islice(
488+
merge(
489+
*(
490+
goal.get("latest_runs", [])[:recent_limit]
491+
for goal in goals
492+
if isinstance(goal.get("latest_runs"), list)
493+
),
494+
key=lambda item: _chronology_key(item.get("generated_at")),
495+
reverse=True,
496+
),
497+
recent_limit,
498+
)
499+
)
500+
return {
501+
**history,
502+
"goal_count": len(goals),
503+
"run_count": sum(int(goal.get("unique_runs") or 0) for goal in goals),
504+
"goals": goals,
505+
"runs": recent_runs,
506+
}
507+
508+
509+
def collect_status_history(
510+
*,
511+
registry_path: Path,
512+
runtime_root: Path,
513+
goal_id: str | None,
514+
limit: int,
515+
status_include_runtime_goals: bool,
516+
activation_state_filter: GoalActivationState | str | None = None,
517+
agent_lane_id: str | None = None,
518+
) -> StatusHistoryCollection:
519+
history = collect_history(
520+
registry_path=registry_path,
521+
runtime_root=runtime_root,
522+
goal_id=goal_id,
523+
limit=limit,
524+
include_runtime_goals=True,
525+
activation_state_filter=activation_state_filter,
526+
agent_lane_id=agent_lane_id,
527+
)
528+
audit = build_run_history_audit(
529+
history,
530+
registry_path=registry_path,
531+
runtime_root=runtime_root,
532+
goal_id=goal_id,
533+
activation_state_filter=activation_state_filter,
534+
include_runtime_goals=True,
535+
)
536+
status_history = history
537+
if (
538+
not status_include_runtime_goals
539+
and not str(goal_id or "").strip()
540+
and activation_state_filter is None
541+
):
542+
status_history = history_for_registry_members(history, limit=limit)
543+
return StatusHistoryCollection(
544+
status_history=status_history,
545+
contract_audit=audit,
546+
)
547+
548+
389549
def inspect_index_duplicates(
390550
*,
391551
registry_path: Path,

0 commit comments

Comments
 (0)