Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(run-card): carry non-scalar metrics, and surface them in the UI

cgycoreyddcc89e218fb
diff --git a/agent/backtest/run_card.py b/agent/backtest/run_card.py
index ddbc38a06..7d48e9dc7 100644
--- a/agent/backtest/run_card.py
+++ b/agent/backtest/run_card.py
@@ -11,6 +11,25 @@ from typing import Any, Mapping, Sequence
SCHEMA_VERSION = "0.1"
+# Largest single structured metric the card will carry, counted in BYTES of the
+# JSON the card actually writes (indented, sorted, non-ASCII kept literal). The
+# card is an at-a-glance artefact read on every run, so a structured metric that
+# exceeds this is named under `_OMITTED_KEY` rather than allowed to grow the
+# card without bound.
+_STRUCTURED_METRIC_MAX_BYTES = 4096
+# Reserved: records which structured metrics were dropped. A metric of this name
+# is itself omitted-and-named rather than published, so the record can never be
+# silently overwritten by one.
+_OMITTED_KEY = "_omitted"
+# Metrics whose value is also stored under a dedicated top-level card key, so
+# carrying them here would publish the same object twice. Only ``validation``
+# qualifies: ``card["validation"] = metrics["validation"]``.
+#
+# ``warnings`` deliberately does NOT: the card's top-level ``warnings`` comes
+# from ``config["content_filter_warnings"]``, whereas the options engine puts
+# its own annualisation warnings under ``metrics["warnings"]`` - a different
+# list with no other home. Excluding it would silently discard them.
+_DEDICATED_CARD_KEYS = ("validation",)
BACKTEST_SUMMARY_KEYS = (
"codes",
"start_date",
@@ -38,7 +57,8 @@ def write_run_card(
run_dir: Directory where run_card.json and run_card.md are written.
config: Full backtest configuration. Only a summary and hash are stored.
metrics: Backtest metrics. Scalar values are stored; ``validation`` is
- stored separately when present.
+ stored under its own top-level key. Non-scalar metrics are carried
+ in ``structured_metrics``.
data_sources: Data sources used by the run.
strategy_path: Optional strategy source file to hash for reproducibility.
warnings: Optional warnings to include in the card.
@@ -73,6 +93,9 @@ def write_run_card(
normalized_refs = _normalize_artifact_refs(artifact_refs)
if normalized_refs:
card["artifact_refs"] = normalized_refs
+ structured = _structured_metrics(metrics)
+ if structured:
+ card["structured_metrics"] = structured
if "validation" in metrics:
card["validation"] = metrics["validation"]
@@ -123,13 +146,84 @@ def _backtest_summary(config: Mapping[str, Any]) -> dict[str, Any]:
def _scalar_metrics(metrics: Mapping[str, Any]) -> dict[str, Any]:
+ """Scalar metrics, minus any whose value has a dedicated top-level key."""
return {
key: value
for key, value in metrics.items()
- if key != "validation" and _is_scalar(value)
+ if key not in _DEDICATED_CARD_KEYS and _is_scalar(value)
}
+def _structured_metrics(metrics: Mapping[str, Any]) -> dict[str, Any]:
+ """Keep the non-scalar metrics that ``metrics`` cannot hold.
+
+ ``metrics`` is a deliberately scalar-only, stable surface, so a dict- or
+ list-shaped metric is filtered out of it. Discarding those outright loses
+ evidence the engine authors for card readers: for example
+ ``unfilled_plan_rejections_by_symbol`` names the sleeve and reason behind a
+ rejection, while the scalar ``unfilled_plan_rejections`` beside it is an
+ anonymous count. They are carried here instead, excluding
+ ``_DEDICATED_CARD_KEYS`` - those already have their own top-level key and
+ would otherwise be published twice.
+
+ The card is written at the end of an already-completed run, so this must
+ never raise: a value that cannot be serialised, or that is larger than
+ ``_STRUCTURED_METRIC_MAX_BYTES``, is omitted and named under
+ ``_OMITTED_KEY`` rather than allowed to fail the run or bloat the card. The
+ bound is what keeps ``by_symbol``-style maps from turning into a
+ multi-hundred-kilobyte card as new structured metrics are added.
+
+ Args:
+ metrics: Backtest metrics as passed to :func:`write_run_card`.
+
+ Returns:
+ The non-scalar metrics that fit, or an empty dict when there are none.
+ """
+ structured = {
+ key: value
+ for key, value in metrics.items()
+ if key not in _DEDICATED_CARD_KEYS and not _is_scalar(value)
+ }
+ if not structured:
+ return {}
+ kept: dict[str, Any] = {}
+ omitted: list[str] = []
+ for key, value in structured.items():
+ if key == _OMITTED_KEY:
+ omitted.append(key)
+ continue
+ try:
+ size = _serialised_size(value)
+ except (TypeError, ValueError, RecursionError):
+ omitted.append(key)
+ continue
+ if size > _STRUCTURED_METRIC_MAX_BYTES:
+ omitted.append(key)
+ else:
+ kept[key] = value
+ if omitted:
+ kept[_OMITTED_KEY] = sorted(omitted)
+ return kept
+
+
+def _serialised_size(value: Any) -> int:
+ """UTF-8 bytes this value occupies in the card's own JSON formatting.
+
+ Measured on the normalised value (``_json_safe``, as the writer applies)
+ and in bytes: ``len()`` on the string counts characters, which understates
+ a CJK value roughly threefold, and the card is written indented rather than
+ compact, so a compact dump would understate it again.
+ """
+ rendered = json.dumps(
+ _json_safe(value),
+ ensure_ascii=False,
+ indent=2,
+ sort_keys=True,
+ default=str,
+ )
+ return len(rendered.encode("utf-8"))
+
+
def _json_safe(value: Any) -> Any:
if isinstance(value, float):
return value if math.isfinite(value) else None
@@ -208,6 +302,21 @@ def _render_markdown(card: Mapping[str, Any]) -> str:
metric_values = card.get("metrics", {})
lines.extend(f"- {key}: {value}" for key, value in metric_values.items()) if metric_values else lines.append("- No scalar metrics recorded.")
+ structured = card.get("structured_metrics", {})
+ if structured:
+ lines.extend(["", "## Structured metrics", ""])
+ lines.append(
+ "Non-scalar metrics, which the `metrics` block cannot hold - carried so "
+ "they can be inspected by key instead of only as a flattened count."
+ )
+ lines.append("")
+ # Deliberately not an inline code span: a value containing a backtick
+ # would close the span early and corrupt the section. Formatted like
+ # the scalar lines above instead.
+ for key, value in structured.items():
+ rendered = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
+ lines.append(f"- {key}: {rendered}")
+
lines.extend(["", "## Validation"])
if "validation" in card:
validation = card["validation"]
diff --git a/agent/tests/test_plan_rejected.py b/agent/tests/test_plan_rejected.py
index eefbc6daa..2cda00991 100644
--- a/agent/tests/test_plan_rejected.py
+++ b/agent/tests/test_plan_rejected.py
@@ -70,6 +70,12 @@ class _NoopHookEngine(_RecorderEngine):
pass
+class _CountingEngine(_RecorderEngine):
+ """Keeps the base counter instead of the recorder, to test the real hook."""
+
+ _on_plan_rejected = BaseEngine._on_plan_rejected
+
+
def _frame(open_price=100.0, ts=_TS):
return pd.DataFrame({"open": [open_price], "close": [100.0]}, index=[ts])
@@ -301,3 +307,34 @@ def test_an_overriding_subclass_still_gets_the_default_counting():
engine._plan_open_order("A", 0.5, _frame(), _TS, 1_000.0)
assert engine.seen == [("A", "zero_size")]
assert engine._plan_rejection_metrics()["unfilled_plan_rejections"] == 1
+
+
+def test_total_and_by_symbol_share_one_counter():
+ """#1235/#1274: the scalar count and the named map come from one counter.
+
+ A card reader may only ever see `unfilled_plan_rejections`. If the named map
+ could diverge from that scalar, the count would be unreconcilable with
+ anything - so a non-zero total must imply a matching, non-empty map, and a
+ zero total must imply no rows.
+ """
+ engine = _CountingEngine()
+ engine._on_plan_rejected("BIL", "zero_size", _TS)
+ engine._on_plan_rejected("BIL", "zero_size", _TS)
+ engine._on_plan_rejected("XLK", "no_bar", _TS)
+
+ metrics = engine._plan_rejection_metrics()
+ assert metrics["unfilled_plan_rejections"] == 3
+ assert metrics["unfilled_plan_rejections_by_symbol"] == {
+ "BIL": {"zero_size": 2},
+ "XLK": {"no_bar": 1},
+ }
+ named_total = sum(
+ count
+ for reasons in metrics["unfilled_plan_rejections_by_symbol"].values()
+ for count in reasons.values()
+ )
+ assert named_total == metrics["unfilled_plan_rejections"]
+
+ empty = _CountingEngine()._plan_rejection_metrics()
+ assert empty["unfilled_plan_rejections"] == 0
+ assert empty["unfilled_plan_rejections_by_symbol"] == {}
diff --git a/agent/tests/test_run_card_structured_metrics.py b/agent/tests/test_run_card_structured_metrics.py
new file mode 100644
index 000000000..f2f1a6426
--- /dev/null
+++ b/agent/tests/test_run_card_structured_metrics.py
@@ -0,0 +1,187 @@
+"""Tests for the run card's structured_metrics block.
+
+`write_run_card` stores only scalar metrics in `card["metrics"]`. Non-scalar
+metrics are carried under a sibling `structured_metrics` key so that a value the
+engine authors for card readers cannot be silently discarded.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from backtest.run_card import write_run_card
+
+
+def test_structured_metrics_survive_without_widening_metrics(tmp_path: Path) -> None:
+ """#1235/#1274: a dropped sleeve must stay visible by name in the card.
+
+ `metrics` is a scalar-only surface, so a dict-shaped rejection map is
+ filtered out of it. It must not vanish from the card altogether: the
+ scalar count alone cannot say *which* sleeve was dropped.
+ """
+ metrics = {
+ "sharpe": 1.42,
+ "unfilled_plan_rejections": 551,
+ "unfilled_plan_rejections_by_symbol": {"BIL": {"zero_size": 12}},
+ "dropped_target_adjustments": [],
+ }
+
+ card = write_run_card(tmp_path, {"codes": ["BIL"], "source": "auto"}, metrics)
+
+ # the scalar surface is unchanged - anything asserting on it still holds
+ assert card["metrics"] == {
+ "sharpe": 1.42,
+ "unfilled_plan_rejections": 551,
+ }
+ # ...but the named evidence is now carried, not discarded
+ assert card["structured_metrics"]["unfilled_plan_rejections_by_symbol"] == {"BIL": {"zero_size": 12}}
+ assert card["structured_metrics"]["dropped_target_adjustments"] == []
+
+ on_disk = json.loads((tmp_path / "run_card.json").read_text(encoding="utf-8"))
+ assert on_disk["structured_metrics"]["unfilled_plan_rejections_by_symbol"] == {"BIL": {"zero_size": 12}}
+ md = (tmp_path / "run_card.md").read_text(encoding="utf-8")
+ # Rendering must be driven by the structured block, not by the config summary:
+ # the symbol alone also appears under ## Backtest, so assert the rendered value.
+ assert "## Structured metrics" in md
+ assert 'unfilled_plan_rejections_by_symbol: {"BIL": {"zero_size": 12}}' in md
+
+
+def test_oversized_structured_metric_is_omitted_and_named(tmp_path: Path) -> None:
+ """The card is read on every run; a structured metric must not grow it unbounded.
+
+ A large map is named under `_omitted` rather than silently carried, so the
+ card stays bounded without the data disappearing unannounced.
+ """
+ from backtest.run_card import _STRUCTURED_METRIC_MAX_BYTES
+
+ big = {"k%04d" % i: i for i in range(_STRUCTURED_METRIC_MAX_BYTES)}
+ metrics = {
+ "sharpe": 1.0,
+ "unfilled_plan_rejections_by_symbol": {"BIL": {"zero_size": 12}},
+ "by_symbol": big,
+ }
+
+ card = write_run_card(tmp_path, {"codes": ["BIL"], "source": "auto"}, metrics)
+
+ assert card["metrics"] == {"sharpe": 1.0}
+ assert card["structured_metrics"]["unfilled_plan_rejections_by_symbol"] == {"BIL": {"zero_size": 12}}
+ assert card["structured_metrics"]["_omitted"] == ["by_symbol"]
+ assert "by_symbol" not in card["structured_metrics"]
+
+
+def test_unserialisable_structured_metric_cannot_fail_the_run(tmp_path: Path) -> None:
+ """The card is written after the run completes; it must never raise.
+
+ `write_run_card` runs at the end of a finished backtest, so a pathological
+ structured metric must degrade to an omission, not lose the whole card.
+ """
+ circular: dict[str, object] = {}
+ circular["self"] = circular
+
+ card = write_run_card(
+ tmp_path,
+ {"codes": ["BIL"], "source": "auto"},
+ {"sharpe": 1.0, "circular": circular, "nan_map": {"a": float("nan")}},
+ )
+
+ assert card["metrics"] == {"sharpe": 1.0}
+ assert card["structured_metrics"]["_omitted"] == ["circular"]
+ # a NaN inside a retained map is nulled by _json_safe, not left non-JSON
+ assert card["structured_metrics"]["nan_map"] == {"a": None}
+ assert (tmp_path / "run_card.json").exists()
+
+
+def test_validation_is_carried_once_and_not_also_in_metrics(tmp_path: Path) -> None:
+ """`card["validation"] = metrics["validation"]` - the same object.
+
+ So it belongs under its own key only, never a second time in the metrics
+ or structured blocks.
+ """
+ card = write_run_card(
+ tmp_path,
+ {"codes": ["SPY"], "source": "auto"},
+ {"sharpe": 1.0, "validation": {"consistency": True}},
+ )
+
+ assert card["validation"] == {"consistency": True}
+ assert card["metrics"] == {"sharpe": 1.0}
+ assert "validation" not in card.get("structured_metrics", {})
+
+
+def test_engine_warnings_are_not_mistaken_for_the_card_warnings(tmp_path: Path) -> None:
+ """Sharing a name is not sharing a value.
+
+ The card's top-level `warnings` comes from `config["content_filter_warnings"]`,
+ but the options engine puts its own annualisation warnings under
+ `metrics["warnings"]`. Those must reach the card - dropping them for sharing
+ a name would be the very silent loss this block exists to prevent.
+ """
+ engine_warnings = ["Annual return requires at least two observations."]
+ card = write_run_card(
+ tmp_path,
+ {"codes": ["SPY"], "source": "auto"},
+ {"sharpe": None, "warnings": engine_warnings},
+ warnings=["from config: content filter"],
+ )
+
+ assert card["warnings"] == ["from config: content filter"]
+ assert card.get("structured_metrics", {}).get("warnings") == engine_warnings
+
+
+def test_bound_is_measured_in_bytes_of_the_written_json(tmp_path: Path) -> None:
+ """The guard's unit must match its name: CJK is three bytes per character.
+
+ ``len()`` on ``json.dumps(..., ensure_ascii=False)`` counts characters, so a
+ value of 1400 CJK characters measures ~1400 there while occupying ~4200
+ UTF-8 bytes in the written card - past a bound named ``..._MAX_BYTES``. The
+ card is also written indented, which a compact dump understates again.
+ """
+ from backtest.run_card import _STRUCTURED_METRIC_MAX_BYTES, _serialised_size
+
+ assert _serialised_size({"note": "键" * 100}) < _STRUCTURED_METRIC_MAX_BYTES
+ assert _serialised_size({"note": "键" * 1400}) > _STRUCTURED_METRIC_MAX_BYTES
+
+ card = write_run_card(
+ tmp_path,
+ {"codes": ["BIL"], "source": "auto"},
+ {"sharpe": 1.0, "cjk": {"note": "键" * 1400}},
+ )
+
+ assert card["structured_metrics"]["_omitted"] == ["cjk"]
+
+
+def test_markdown_section_survives_a_backtick_in_a_metric(tmp_path: Path) -> None:
+ """A backtick inside a value must not close a rendered span early.
+
+ An inline code span would be terminated by the first backtick in the value,
+ corrupting the rest of the section - the JSON is emitted inline instead.
+ """
+ write_run_card(
+ tmp_path,
+ {"codes": ["BIL"], "source": "auto"},
+ {"sharpe": 1.0, "note": {"text": "ends`here"}},
+ )
+
+ md = (tmp_path / "run_card.md").read_text(encoding="utf-8")
+ line = next(line for line in md.splitlines() if line.startswith("- note:"))
+ # emitted verbatim, with no code span to be closed early by the backtick
+ assert line == '- note: {"text": "ends`here"}'
+
+
+def test_the_omitted_record_cannot_be_overwritten_by_a_metric(tmp_path: Path) -> None:
+ """``_omitted`` names what the block dropped, so a metric may not claim it.
+
+ Publishing a metric literally called ``_omitted`` would let one metric be
+ silently reinterpreted as the drop record - and change its type doing so.
+ """
+ circular: dict[str, object] = {}
+ circular["self"] = circular
+
+ card = write_run_card(
+ tmp_path,
+ {"codes": ["BIL"], "source": "auto"},
+ {"sharpe": 1.0, "_omitted": {"real": 1}, "circ": circular},
+ )
+
+ assert card["structured_metrics"]["_omitted"] == ["_omitted", "circ"]
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index a38160d0f..14cd6862f 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -670,6 +670,8 @@
"noBacktestSummary": "لم يتم تسجيل ملخص اختبار عكسي.",
"noReproducibilityHashes": "لم يتم تسجيل تجزئات قابلية إعادة الإنتاج.",
"noScalarMetrics": "لم يتم تسجيل مقاييس عددية.",
+ "noStructuredMetrics": "لم يتم تسجيل أي مقاييس مهيكلة.",
+ "structuredMetrics": "المقاييس المهيكلة",
"noValidationPayload": "لم يتم تسجيل حمولة التحقق.",
"noArtifactChecksums": "لم يتم تسجيل مجاميع التحقق للمنتجات.",
"noCodeFiles": "لا توجد ملفات شفرة.",
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 4615b6b63..e8cd96e19 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -675,6 +675,8 @@
"noBacktestSummary": "Keine Backtest-Zusammenfassung aufgezeichnet.",
"noReproducibilityHashes": "Keine Reproduzierbarkeits-Hashes aufgezeichnet.",
"noScalarMetrics": "Keine skalaren Metriken aufgezeichnet.",
+ "noStructuredMetrics": "Keine strukturierten Kennzahlen aufgezeichnet.",
+ "structuredMetrics": "Strukturierte Kennzahlen",
"noValidationPayload": "Keine Validierungsdaten aufgezeichnet.",
"noArtifactChecksums": "Keine Artefakt-Prüfsummen aufgezeichnet.",
"noCodeFiles": "Keine Codedateien.",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 204775de9..7f4ec5452 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -675,6 +675,8 @@
"noBacktestSummary": "No backtest summary recorded.",
"noReproducibilityHashes": "No reproducibility hashes recorded.",
"noScalarMetrics": "No scalar metrics recorded.",
+ "noStructuredMetrics": "No structured metrics recorded.",
+ "structuredMetrics": "Structured metrics",
"noValidationPayload": "No validation payload recorded.",
"noArtifactChecksums": "No artifact checksums recorded.",
"noCodeFiles": "No code files.",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index b38401bb7..e848d7f52 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -675,6 +675,8 @@
"noBacktestSummary": "No se registró ningún resumen de backtest.",
"noReproducibilityHashes": "No se registraron hashes de reproducibilidad.",
"noScalarMetrics": "No se registraron métricas escalares.",
+ "noStructuredMetrics": "No se registraron métricas estructuradas.",
+ "structuredMetrics": "Métricas estructuradas",
"noValidationPayload": "No se registró ningún payload de validación.",
"noArtifactChecksums": "No se registraron sumas de verificación de artefactos.",
"noCodeFiles": "No hay archivos de código.",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index b8f9c5165..ae8125958 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -670,6 +670,8 @@
"noBacktestSummary": "バックテストサマリは記録されていません。",
"noReproducibilityHashes": "再現性ハッシュは記録されていません。",
"noScalarMetrics": "スカラーメトリクスは記録されていません。",
+ "noStructuredMetrics": "構造化メトリクスは記録されていません。",
+ "structuredMetrics": "構造化メトリクス",
"noValidationPayload": "検証ペイロードは記録されていません。",
"noArtifactChecksums": "成果物チェックサムは記録されていません。",
"noCodeFiles": "コードファイルがありません。",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index eb9c217d6..791e5c414 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -670,6 +670,8 @@
"noBacktestSummary": "기록된 백테스트 요약이 없습니다.",
"noReproducibilityHashes": "기록된 재현성 해시가 없습니다.",
"noScalarMetrics": "기록된 스칼라 지표가 없습니다.",
+ "noStructuredMetrics": "기록된 구조화 지표가 없습니다.",
+ "structuredMetrics": "구조화된 지표",
"noValidationPayload": "기록된 검증 페이로드가 없습니다.",
"noArtifactChecksums": "기록된 아티팩트 체크섬이 없습니다.",
"noCodeFiles": "코드 파일이 없습니다.",
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index caa53019e..474ff5df6 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -675,6 +675,8 @@
"noBacktestSummary": "Nenhum resumo de backtest registrado.",
"noReproducibilityHashes": "Nenhum hashe de reprodutibilidade registrado.",
"noScalarMetrics": "Nenhuma métrica escalar registrada.",
+ "noStructuredMetrics": "Nenhuma métrica estruturada registrada.",
+ "structuredMetrics": "Métricas estruturadas",
"noValidationPayload": "Nenhuma carga útil de validação registrada.",
"noArtifactChecksums": "Nenhuma soma de verificação de artefato registrada.",
"noCodeFiles": "Nenhum arquivo de código.",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index c2bc02db3..38fc8f9ea 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -670,6 +670,8 @@
"noBacktestSummary": "暂无回测摘要记录。",
"noReproducibilityHashes": "暂无可复现性哈希记录。",
"noScalarMetrics": "暂无标量指标记录。",
+ "noStructuredMetrics": "未记录结构化指标。",
+ "structuredMetrics": "结构化指标",
"noValidationPayload": "暂无验证数据记录。",
"noArtifactChecksums": "暂无制品校验和记录。",
"noCodeFiles": "暂无代码文件。",
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 05f2827c3..1de6c76f6 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1154,6 +1154,9 @@ export interface RunCard {
reproducibility?: Record<string, unknown>;
data_sources?: string[];
metrics?: Record<string, unknown>;
+ // Carried alongside `metrics`, which is scalar-only: dict/list-shaped metrics
+ // (e.g. which sleeve a plan rejection dropped) reach the card here.
+ structured_metrics?: Record<string, unknown>;
validation?: unknown;
warnings?: string[];
artifacts?: RunCardArtifact[];
diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsx
index 5c0c391e5..7dc6875dc 100644
--- a/frontend/src/pages/RunDetail.tsx
+++ b/frontend/src/pages/RunDetail.tsx
@@ -7,6 +7,7 @@ import {
ArrowLeft,
ArrowLeftRight,
BarChart3,
+ Braces,
CalendarRange,
CheckCircle2,
Code2,
@@ -468,6 +469,11 @@ function RunCardTab({ card }: { card: RunCard }) {
const backtest = card.backtest || {};
const reproducibility = card.reproducibility || {};
const metrics = card.metrics || {};
+ // Rendered as JSON: a dict or list value would otherwise collapse - an empty
+ // list formats as a blank cell, which reads as "missing" rather than "none".
+ const structuredMetrics = Object.fromEntries(
+ Object.entries(card.structured_metrics || {}).map(([key, value]) => [key, JSON.stringify(value)]),
+ );
const artifacts = card.artifacts || [];
const warnings = card.warnings || [];
const dataSources = card.data_sources || [];
@@ -521,6 +527,10 @@ function RunCardTab({ card }: { card: RunCard }) {
</RunCardPanel>
</div>
+ <RunCardPanel title={i18n.t("runDetail.structuredMetrics")} icon={Braces}>
+ <KeyValueTable data={structuredMetrics} empty={i18n.t("runDetail.noStructuredMetrics")} monospaceValues />
+ </RunCardPanel>
+
<RunCardPanel title={i18n.t("runDetail.artifactChecksums")} icon={FileCheck2}>
{artifacts.length > 0 ? (
<div className="overflow-x-auto">
@@ -753,7 +763,7 @@ function KeyValueTable({ data, empty, monospaceValues = false }: { data: Record<
<tbody>
{entries.map(([key, value]) => (
<tr key={key} className="border-b last:border-0 hover:bg-muted/40">
- <td className="w-36 py-2 ps-4 pr-4 align-top text-muted-foreground">{key}</td>
+ <td className="w-36 break-all py-2 ps-4 pr-4 align-top text-muted-foreground">{key}</td>
<td className={cn("py-2 align-top", monospaceValues ? "break-all font-mono text-xs" : "break-words text-right tabular-nums")}>{formatRunCardValue(value)}</td>
</tr>
))}
diff --git a/frontend/src/pages/__tests__/RunDetail.test.tsx b/frontend/src/pages/__tests__/RunDetail.test.tsx
index 41d4ecc71..20e7d5837 100644
--- a/frontend/src/pages/__tests__/RunDetail.test.tsx
+++ b/frontend/src/pages/__tests__/RunDetail.test.tsx
@@ -276,6 +276,57 @@ describe("RunDetail page", () => {
expect(screen.getByText("artifacts/result.json")).toHaveClass("ps-4");
});
+ it("renders structured metrics that the scalar `metrics` block cannot hold", async () => {
+ // #1235/#1274: the sleeve a plan rejection dropped is dict-shaped, so it
+ // never reaches `metrics`. It must still be readable in the card, not just
+ // present in the JSON.
+ apiMock.getRun.mockResolvedValue({
+ status: "success",
+ run_id: "structured",
+ prompt: "Structured card",
+ run_card: {
+ metrics: { sharpe: 1.42 },
+ structured_metrics: {
+ unfilled_plan_rejections_by_symbol: { BIL: { zero_size: 12 } },
+ dropped_target_adjustments: [],
+ _omitted: ["by_symbol"],
+ },
+ } as NonNullable<RunData["run_card"]>,
+ });
+ apiMock.getRunCode.mockResolvedValue({});
+
+ renderRunDetail("/runs/structured");
+
+ await screen.findByText("Structured card");
+ fireEvent.click(screen.getByRole("tab", { name: "Run Card" }));
+
+ expect(
+ await screen.findByText("unfilled_plan_rejections_by_symbol"),
+ ).toBeInTheDocument();
+ expect(screen.getByText('{"BIL":{"zero_size":12}}')).toBeInTheDocument();
+ // an empty list must read as "none", not as a blank cell that looks missing
+ expect(screen.getByText("[]")).toBeInTheDocument();
+ // the record of what the block dropped is surfaced too, as JSON
+ expect(screen.getByText('["by_symbol"]')).toBeInTheDocument();
+ });
+
+ it("shows the structured-metrics empty state when the card carries none", async () => {
+ apiMock.getRun.mockResolvedValue({
+ status: "success",
+ run_id: "scalar-only",
+ prompt: "Scalar only",
+ run_card: { metrics: { sharpe: 1.42 } } as NonNullable<RunData["run_card"]>,
+ });
+ apiMock.getRunCode.mockResolvedValue({});
+
+ renderRunDetail("/runs/scalar-only");
+
+ await screen.findByText("Scalar only");
+ fireEvent.click(screen.getByRole("tab", { name: "Run Card" }));
+
+ expect(await screen.findByText("No structured metrics recorded.")).toBeInTheDocument();
+ });
+
it("renders the Factor Research tab from has_factor_artifacts and lazy-loads the report", async () => {
apiMock.getRun.mockResolvedValue({
status: "success",