Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): gate generic-header metric tables (#1336 dodge)

cgycorey71c7b6895747
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.py
index b408e9254..8c3070dfe 100644
--- a/agent/src/agent/grounding.py
+++ b/agent/src/agent/grounding.py
@@ -337,7 +337,10 @@ _ANALYSIS_KIND_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
(re.compile(r"(?:夏普|sharpe)", re.IGNORECASE), "sharpe"),
(re.compile(r"(?:胜率|命中率|win\s*rate|hit\s*rate)", re.IGNORECASE), "win_rate"),
(re.compile(r"(?:概率|probability|prob)", re.IGNORECASE), "probability"),
- (re.compile(r"(?:收益|回报|收益率|回报率|\breturns?\b)", re.IGNORECASE), "return"),
+ # 年化/annualized alone ("| 年化 | 18.2% |") resolves to return so a
+ # generic-header table cannot dodge the gate with the fragment the prose
+ # detector (_ANALYSIS_METRIC_RE) already treats as a metric word.
+ (re.compile(r"(?:收益|回报|收益率|回报率|年化|\breturns?\b|\bannualized\b)", re.IGNORECASE), "return"),
)
# Definitional prose ("夏普比率大于 1.0 通常被认为较好") states a convention,
@@ -2697,43 +2700,56 @@ class GroundingLedger:
(cell, _metric_kind_for_text(cell), bool(_FORECAST_FRAME_RE.search(cell)))
for cell in header
]
- if not any(kind for _, kind, _ in columns):
- continue
+ has_kind_header = any(kind for _, kind, _ in columns)
for row in rows:
cells = row + [""] * (len(columns) - len(row))
+ if not has_kind_header:
+ # Generic header ("指标 | 数值", "Metric | Value"): a cell
+ # naming a metric kind is a row LABEL and claims exactly
+ # one adjacent value cell (right first — "label, value"
+ # order — then left, for value-first layouts). Validating
+ # every cell after the label would grab annotation columns
+ # ("备注 | 较去年提升 2%") that prose never attributes to
+ # the label; parity with the prose verdict is the bar.
+ row_kinds = [
+ (index, _metric_kind_for_text(cell))
+ for index, cell in enumerate(cells)
+ if _metric_kind_for_text(cell) is not None
+ ]
+ claimed: set[int] = set()
+ for label_index, row_kind in row_kinds:
+ # A label cell that smuggles its own measurement
+ # ("| 年化收益率 18.2% | - |") is prose-identical to
+ # "年化收益率为 18.2%" — validate the label's own
+ # numbers against its kind too.
+ self._check_table_cell(
+ cells[label_index], row_kind, cells[label_index], issues
+ )
+ # A forecast frame in the LABEL ("| 预计夏普比率 | 1.2 |")
+ # frames the claimed value clause-wide, exactly as prose
+ # exempts the whole clause and the metric-header path
+ # skips a forecast-framed column. Without this the generic
+ # path is stricter than both of its siblings.
+ label_is_forecast = bool(
+ _FORECAST_FRAME_RE.search(cells[label_index])
+ )
+ for value_index in (label_index + 1, label_index - 1):
+ if (
+ 0 <= value_index < len(cells)
+ and value_index not in claimed
+ and _metric_kind_for_text(cells[value_index]) is None
+ ):
+ claimed.add(value_index)
+ if label_is_forecast:
+ continue
+ self._check_table_cell(
+ cells[label_index], row_kind, cells[value_index], issues
+ )
+ continue
for (cell_text, kind, header_forecast), cell in zip(columns, cells):
if kind is None or header_forecast:
continue
- values = self._measure_numbers(cell)
- if not values:
- continue
- # A forecast annotation inside the cell ("预计 12.4%")
- # exempts only that cell, never its neighbours.
- if _FORECAST_FRAME_RE.search(cell) or _DEFINITION_FRAME_RE.search(
- cell
- ):
- continue
- unsupported = [
- value
- for value in values
- if not self._analysis_value_observed(value, kind)
- ]
- if not unsupported:
- continue
- issues.append(
- {
- "code": "analysis_claim_unavailable",
- "claim": f"{cell_text}: {cell}"[:200],
- "value": unsupported[0],
- "kind": kind,
- "message": (
- "No supporting analysis evidence (a completed "
- "backtest result or observed risk metric) exists "
- "for this figure. Mark the analysis as incomplete "
- "and omit these figures."
- ),
- }
- )
+ self._check_table_cell(cell_text, kind, cell, issues)
for index, line in enumerate(lines):
if index in consumed:
continue
@@ -2814,6 +2830,56 @@ class GroundingLedger:
)
return issues
+ def _check_table_cell(
+ self,
+ label: str,
+ kind: str | None,
+ cell: str,
+ issues: list[dict[str, Any]],
+ ) -> None:
+ """Reject one table cell whose numeric value is an unsupported metric.
+
+ Shared by the metric-headed and generic-header (label, value) table
+ paths. A forecast or definitional annotation exempts only that cell.
+
+ Args:
+ label: The metric label the value is attached to (header cell or
+ row's first cell), for the issue claim text.
+ kind: The resolved metric kind, already derived from ``label``.
+ cell: One value cell to validate.
+ issues: Accumulator for ``analysis_claim_unavailable`` issues.
+ """
+ if kind is None:
+ return
+ values = GroundingLedger._measure_numbers(cell)
+ if not values:
+ return
+ # A forecast annotation inside the cell ("预计 12.4%") exempts only
+ # that cell, never its neighbours.
+ if _FORECAST_FRAME_RE.search(cell) or _DEFINITION_FRAME_RE.search(cell):
+ return
+ unsupported = [
+ value
+ for value in values
+ if not self._analysis_value_observed(value, kind)
+ ]
+ if not unsupported:
+ return
+ issues.append(
+ {
+ "code": "analysis_claim_unavailable",
+ "claim": f"{label}: {cell}"[:200],
+ "value": unsupported[0],
+ "kind": kind,
+ "message": (
+ "No supporting analysis evidence (a completed "
+ "backtest result or observed risk metric) exists "
+ "for this figure. Mark the analysis as incomplete "
+ "and omit these figures."
+ ),
+ }
+ )
+
@staticmethod
def _measure_numbers(text: str) -> list[str]:
"""Extract measurement-shaped numbers (decimal or percent) from a claim."""
diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.py
index 2538573b9..11f165e7a 100644
--- a/agent/tests/test_agent_grounding.py
+++ b/agent/tests/test_agent_grounding.py
@@ -3442,3 +3442,100 @@ def test_derived_return_exemption_is_structural_not_phrasal(tmp_path: Path) -> N
"AAPL.US 从 100.0 涨到 112.4,区间收益率为 15.0%。",
):
assert verdict(answer) is True, f"unanchored/wrong return accepted: {answer}"
+def test_generic_header_table_metric_rows_are_gated(tmp_path: Path) -> None:
+ """#1336 must not be dodgeable by formatting the claim as a generic-header
+ table (| 指标 | 数值 | / | Metric | Value |) with the metric kind in the
+ row instead of prose or a metric-headed table."""
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="回测策略")
+
+ result = ledger.validate_final_answer(
+ "| 指标 | 数值 |\n|---|---:|\n| 年化收益 | 18.2% |\n| 最大回撤 | -9.4% |"
+ )
+
+ assert result.valid is False, result.issues
+ assert [
+ i for i in result.issues if i.get("code") == "analysis_claim_unavailable"
+ ]
+
+ # a comparison marker must not launder an unsupported figure through a
+ # metric-headed table either: prose rejects "夏普比率 > 1.5。" without
+ # evidence, so the table form must be rejected too
+ result = ledger.validate_final_answer("| 夏普比率 |\n|---|---|\n| > 1.5 |")
+ assert result.valid is False, result.issues
+
+ # value-first layout (kind in a later cell) is gated too
+ result = ledger.validate_final_answer(
+ "| 数值 | 指标 |\n|---|---|\n| 18.2% | 年化收益率 |"
+ )
+ assert result.valid is False, result.issues
+ # the bare fragment the prose detector treats as a metric word is gated
+ result = ledger.validate_final_answer(
+ "| 指标 | 数值 |\n|---|---|\n| 年化 | 18.2% |"
+ )
+ assert result.valid is False, result.issues
+ # multiple (label, value) pairs in one row are each gated with their own kind
+ result = ledger.validate_final_answer(
+ "| 指标 | 数值 | 指标 | 数值 |\n|---|---|---|---|\n| 年化波动率 | 18.2% | 最大回撤 | -9.4% |"
+ )
+ assert result.valid is False, result.issues
+ assert len([i for i in result.issues if i.get("code") == "analysis_claim_unavailable"]) == 2
+
+
+def test_generic_header_table_matches_prose_verdicts(tmp_path: Path) -> None:
+ """The generic-header fallback must produce the SAME verdict as prose for
+ the same claim — never looser (formatting dodge) and never stricter.
+
+ Prose without evidence rejects comparison phrasing ("最大回撤小于 -5%
+ 触发风控。"), rejects the definitional frame split across the number
+ ("夏普比率通常大于1.0认为较好。"), and rejects a bare claim; with
+ kind-matched evidence all of them pass. Tables must do exactly that.
+ """
+ bare = GroundingLedger(run_dir=tmp_path / "bare", user_message="回测策略")
+ # comparison phrasing rejected without evidence, like prose
+ assert bare.validate_final_answer(
+ "| 指标 | 标准 |\n|---|---|\n| 最大回撤 | 小于 -5% 触发风控 |"
+ ).valid is False
+ # definitional frame split by the number: prose rejects it, tables must not
+ # be looser than prose or the split becomes the new formatting dodge
+ assert bare.validate_final_answer(
+ "| 指标 | 备注 |\n|---|---|\n| 夏普比率 | 通常大于1.0认为较好 |"
+ ).valid is False
+ # a label cell smuggling its own measurement is prose-identical to
+ # "年化收益率为 18.2%" — rejected
+ assert bare.validate_final_answer(
+ "| 指标 | 数值 |\n|---|---|\n| 年化收益率 18.2% | - |"
+ ).valid is False
+
+ backed = GroundingLedger(run_dir=tmp_path / "backed", user_message="回测策略")
+ backed.ingest_tool_result(
+ tool_name="portfolio_risk_xray",
+ arguments={"symbols": ["AAPL"]},
+ result=json.dumps({"annualized_vol": 0.182, "max_drawdown": -0.05}),
+ call_id="x",
+ success=True,
+ )
+ # value-backed row accepted
+ assert backed.validate_final_answer(
+ "| 指标 | 数值 |\n|---|---:|\n| 年化波动率 | 18.2% |"
+ ).valid is True
+ # the same comparison phrasing passes once the figure is kind-backed
+ assert backed.validate_final_answer(
+ "| 指标 | 标准 |\n|---|---|\n| 最大回撤 | 小于 -5% 触发风控 |"
+ ).valid is True
+ # contiguous definitional frame ("通常认为…") is exempt in prose, so in
+ # tables too — the frame regex is the boundary, not the formatting
+ assert backed.validate_final_answer(
+ "| 指标 | 备注 |\n|---|---|\n| 夏普比率 | 通常认为大于 1.0 较好 |"
+ ).valid is True
+ # an annotation column past the value cell is not attributed to the label:
+ # the prose verdict for "年化波动率 18.2%,较去年提升 2%。" with this evidence
+ # is valid, so the table form must not be stricter (parity).
+ assert backed.validate_final_answer(
+ "| 指标 | 数值 | 备注 |\n|---|---|---|\n| 年化波动率 | 18.2% | 较去年提升 2% |"
+ ).valid is True
+ # a FORECAST frame in the label frames the claimed value clause-wide:
+ # prose "预计夏普比率为 1.2。" and the metric-header path (header_forecast
+ # column skip) both accept; the generic path must not be stricter.
+ assert bare.validate_final_answer(
+ "| 指标 | 数值 |\n|---|---|\n| 预计夏普比率 | 1.2 |"
+ ).valid is True