local-context-compiler 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. lcc/__init__.py +72 -0
  2. lcc/agents/__init__.py +37 -0
  3. lcc/agents/local_agent.py +403 -0
  4. lcc/agents/local_solver.py +89 -0
  5. lcc/agents/local_verifier.py +276 -0
  6. lcc/benchmarking/__init__.py +65 -0
  7. lcc/benchmarking/case_loader.py +257 -0
  8. lcc/benchmarking/metadata.py +90 -0
  9. lcc/benchmarking/report.py +91 -0
  10. lcc/benchmarking/runner.py +316 -0
  11. lcc/benchmarking/schemas.py +125 -0
  12. lcc/cleaning/__init__.py +40 -0
  13. lcc/cleaning/boilerplate.py +75 -0
  14. lcc/cleaning/deduplicate.py +88 -0
  15. lcc/cleaning/normalize.py +184 -0
  16. lcc/cleaning/speech.py +313 -0
  17. lcc/cli.py +1614 -0
  18. lcc/compressor.py +119 -0
  19. lcc/inspection/__init__.py +56 -0
  20. lcc/inspection/inspector.py +678 -0
  21. lcc/inspection/report.py +100 -0
  22. lcc/inspection/schemas.py +186 -0
  23. lcc/intake/__init__.py +17 -0
  24. lcc/intake/parser.py +182 -0
  25. lcc/intake/pipeline.py +170 -0
  26. lcc/lexical_selection.py +320 -0
  27. lcc/mcp_server.py +357 -0
  28. lcc/pipeline.py +147 -0
  29. lcc/prompt_builder/__init__.py +7 -0
  30. lcc/prompt_builder/builder.py +41 -0
  31. lcc/prompt_builder/templates.py +223 -0
  32. lcc/py.typed +1 -0
  33. lcc/relevance/__init__.py +164 -0
  34. lcc/relevance/blocks.py +201 -0
  35. lcc/relevance/compactor.py +2257 -0
  36. lcc/relevance/decisions.py +266 -0
  37. lcc/relevance/graph.py +224 -0
  38. lcc/relevance/jev.py +347 -0
  39. lcc/relevance/laya.py +360 -0
  40. lcc/relevance/provider.py +221 -0
  41. lcc/relevance/safety.py +75 -0
  42. lcc/relevance/sufficiency.py +69 -0
  43. lcc/relevance/trim.py +254 -0
  44. lcc/relevance/verifier.py +327 -0
  45. lcc/reporting/__init__.py +23 -0
  46. lcc/reporting/explain.py +270 -0
  47. lcc/reporting/report.py +121 -0
  48. lcc/router/__init__.py +57 -0
  49. lcc/router/cli.py +138 -0
  50. lcc/router/cloud_client.py +112 -0
  51. lcc/router/config.py +150 -0
  52. lcc/router/context_adapter.py +141 -0
  53. lcc/router/errors.py +15 -0
  54. lcc/router/eval_runner.py +179 -0
  55. lcc/router/features.py +151 -0
  56. lcc/router/final_formatter.py +75 -0
  57. lcc/router/fireworks_client.py +17 -0
  58. lcc/router/lcc_adapter.py +13 -0
  59. lcc/router/policy.py +64 -0
  60. lcc/router/prompt_builder.py +48 -0
  61. lcc/router/router.py +199 -0
  62. lcc/router/schemas.py +178 -0
  63. lcc/router/token_accounting.py +8 -0
  64. lcc/schemas.py +110 -0
  65. lcc/semantic_retrieval/__init__.py +42 -0
  66. lcc/semantic_retrieval/boundary.py +500 -0
  67. lcc/semantic_retrieval/execution.py +481 -0
  68. lcc/token_budget/__init__.py +29 -0
  69. lcc/token_budget/counters.py +252 -0
  70. lcc/token_budget/pricing.py +109 -0
  71. lcc/toon.py +74 -0
  72. local_context_compiler-0.4.0.dist-info/METADATA +683 -0
  73. local_context_compiler-0.4.0.dist-info/RECORD +77 -0
  74. local_context_compiler-0.4.0.dist-info/WHEEL +5 -0
  75. local_context_compiler-0.4.0.dist-info/entry_points.txt +2 -0
  76. local_context_compiler-0.4.0.dist-info/licenses/LICENSE +21 -0
  77. local_context_compiler-0.4.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,276 @@
1
+ """Local quality gates and verification for local-first agent execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ from decimal import Decimal, InvalidOperation
9
+ from typing import Any
10
+
11
+ from lcc.router.config import PolicyConfig
12
+ from lcc.router.schemas import (
13
+ LCCReportSummary,
14
+ LocalAnswer,
15
+ TaskFeatures,
16
+ TaskInput,
17
+ VerificationDecision,
18
+ VerificationResult,
19
+ )
20
+
21
+
22
+ class RuleBasedVerifier:
23
+ """Conservative structured gate. High uncertainty or invalid format escalates to remote."""
24
+
25
+ def __init__(self, accept_confidence: float = 0.78) -> None:
26
+ self.accept_confidence = accept_confidence
27
+
28
+ def verify(
29
+ self,
30
+ task: TaskInput,
31
+ candidate: LocalAnswer,
32
+ lcc_report: LCCReportSummary,
33
+ features: TaskFeatures,
34
+ ) -> VerificationResult:
35
+ missing: list[str] = []
36
+ risks: list[str] = []
37
+ answer = candidate.answer.strip()
38
+ format_valid = True
39
+ confidence = 0.88
40
+ parsed_json = _json_value(answer) if _expects_json(task.expected_format) else None
41
+
42
+ if not answer:
43
+ missing.append("non-empty answer")
44
+ risks.append("candidate_answer_empty")
45
+ confidence -= 0.5
46
+
47
+ if task.expected_format:
48
+ valid, requirement = _format_valid(task.expected_format, answer)
49
+ if not valid:
50
+ format_valid = False
51
+ missing.append(requirement)
52
+ risks.append("strict_format_failed")
53
+ confidence -= 0.3
54
+
55
+ for field in task.metadata.get("required_fields", []) or []:
56
+ if isinstance(parsed_json, dict):
57
+ field_missing = str(field) not in parsed_json
58
+ else:
59
+ field_missing = str(field) not in answer
60
+ if field_missing:
61
+ missing.append(f"field:{field}")
62
+ confidence -= 0.08
63
+
64
+ if features.requires_calculation:
65
+ expected_result = _simple_calculation_result(task)
66
+ if expected_result is None:
67
+ risks.append("calculation_not_deterministically_verified")
68
+ confidence -= 0.12
69
+ elif not _answer_contains_number(answer, expected_result):
70
+ rendered = _render_decimal(expected_result)
71
+ missing.append(f"calculated result:{rendered}")
72
+ risks.append("calculation_result_mismatch")
73
+ confidence -= 0.35
74
+
75
+ if features.requires_external_knowledge:
76
+ risks.append("external_knowledge_required")
77
+ confidence -= 0.28
78
+ if features.has_conflicting_instructions:
79
+ risks.append("conflicting_instructions")
80
+ confidence -= 0.25
81
+ if features.ambiguity_score >= 0.45:
82
+ if _acknowledges_ambiguity(answer):
83
+ risks.append("ambiguity_acknowledged")
84
+ confidence -= 0.04
85
+ else:
86
+ missing.append("ambiguity_acknowledgement")
87
+ risks.append("overconfident_ambiguous_answer")
88
+ confidence -= 0.25
89
+ if features.ambiguity_score >= 0.65:
90
+ risks.append("ambiguous_task")
91
+ confidence -= 0.18
92
+ if lcc_report.recommendation_action == "manual_review":
93
+ risks.append("lcc_manual_review")
94
+ confidence -= 0.25
95
+ if _looks_unsupported(task, answer):
96
+ risks.append("possible_unsupported_claims")
97
+ confidence -= 0.12
98
+
99
+ confidence = round(max(0.0, min(confidence, 1.0)), 2)
100
+ decision = (
101
+ VerificationDecision.ACCEPT_LOCAL
102
+ if confidence >= self.accept_confidence and format_valid and not missing
103
+ else VerificationDecision.ESCALATE_REMOTE
104
+ )
105
+ explanation = (
106
+ "Local answer passed deterministic format and risk checks."
107
+ if decision == VerificationDecision.ACCEPT_LOCAL
108
+ else "Local answer did not clear the conservative acceptance gate."
109
+ )
110
+ return VerificationResult(
111
+ decision=decision,
112
+ confidence=confidence,
113
+ format_valid=format_valid,
114
+ missing_requirements=missing,
115
+ risk_reasons=risks,
116
+ explanation=explanation,
117
+ )
118
+
119
+
120
+ class LocalLLMVerifier:
121
+ """Optional local-model verifier with rule-based fallback."""
122
+
123
+ def __init__(self, solver: Any, fallback: RuleBasedVerifier) -> None:
124
+ self.solver = solver
125
+ self.fallback = fallback
126
+
127
+ def verify(
128
+ self,
129
+ task: TaskInput,
130
+ candidate: LocalAnswer,
131
+ lcc_report: LCCReportSummary,
132
+ features: TaskFeatures,
133
+ ) -> VerificationResult:
134
+ from lcc.router.prompt_builder import build_verifier_prompt
135
+
136
+ try:
137
+ verifier_task = TaskInput(
138
+ task_id=f"{task.task_id}:verify",
139
+ instruction="Return only verifier JSON.",
140
+ context=build_verifier_prompt(task, candidate),
141
+ expected_format="json",
142
+ )
143
+ raw = self.solver.solve(verifier_task, verifier_task.context).answer
144
+ payload = _extract_json(raw)
145
+ return VerificationResult(
146
+ decision=VerificationDecision(str(payload["decision"])),
147
+ confidence=float(payload["confidence"]),
148
+ format_valid=bool(payload["format_valid"]),
149
+ missing_requirements=[
150
+ str(item) for item in payload.get("missing_requirements", [])
151
+ ],
152
+ risk_reasons=[str(item) for item in payload.get("risk_reasons", [])],
153
+ explanation=str(payload.get("explanation", "")),
154
+ )
155
+ except Exception:
156
+ return self.fallback.verify(task, candidate, lcc_report, features)
157
+
158
+
159
+ def _format_valid(expected_format: str, answer: str) -> tuple[bool, str]:
160
+ marker = expected_format.lower()
161
+ if "json" in marker:
162
+ try:
163
+ value = json.loads(answer)
164
+ except json.JSONDecodeError:
165
+ return False, "valid JSON object"
166
+ if "array" in marker:
167
+ if not isinstance(value, list):
168
+ return False, "valid JSON array"
169
+ elif not isinstance(value, dict):
170
+ return False, "valid JSON object"
171
+ if "yaml" in marker and ":" not in answer:
172
+ return False, "YAML-like key/value output"
173
+ if "csv" in marker and "," not in answer:
174
+ return False, "CSV output"
175
+ if "markdown table" in marker and "|" not in answer:
176
+ return False, "markdown table"
177
+ if "exactly" in marker and not answer:
178
+ return False, "exact requested output"
179
+ return True, ""
180
+
181
+
182
+ def _expects_json(expected_format: str | None) -> bool:
183
+ return bool(expected_format and "json" in expected_format.lower())
184
+
185
+
186
+ def _json_value(answer: str) -> Any | None:
187
+ try:
188
+ return json.loads(answer)
189
+ except json.JSONDecodeError:
190
+ return None
191
+
192
+
193
+ def _acknowledges_ambiguity(answer: str) -> bool:
194
+ return bool(
195
+ re.search(
196
+ r"\b(ambiguous|unclear|unknown|cannot determine|not enough context|conflicting)\b",
197
+ answer,
198
+ flags=re.IGNORECASE,
199
+ )
200
+ )
201
+
202
+
203
+ def _simple_calculation_result(task: TaskInput) -> Decimal | None:
204
+ text = f"{task.instruction}\n{task.context}"
205
+ match = re.search(
206
+ r"(-?\d+(?:\.\d+)?)\s*([+\-*/×x])\s*(-?\d+(?:\.\d+)?)",
207
+ text,
208
+ flags=re.IGNORECASE,
209
+ )
210
+ if not match:
211
+ return None
212
+ try:
213
+ left = Decimal(match.group(1))
214
+ right = Decimal(match.group(3))
215
+ except InvalidOperation:
216
+ return None
217
+ operator = match.group(2).lower()
218
+ if operator == "+":
219
+ return left + right
220
+ if operator == "-":
221
+ return left - right
222
+ if operator in {"*", "x", "×"}:
223
+ return left * right
224
+ if operator == "/" and right != 0:
225
+ return left / right
226
+ return None
227
+
228
+
229
+ def _answer_contains_number(answer: str, expected: Decimal) -> bool:
230
+ for raw in re.findall(r"-?\d+(?:\.\d+)?", answer):
231
+ try:
232
+ if Decimal(raw) == expected:
233
+ return True
234
+ except InvalidOperation:
235
+ continue
236
+ return False
237
+
238
+
239
+ def _render_decimal(value: Decimal) -> str:
240
+ normalized = value.normalize()
241
+ if normalized == normalized.to_integral():
242
+ return str(normalized.quantize(Decimal(1)))
243
+ return format(normalized, "f")
244
+
245
+
246
+ def _looks_unsupported(task: TaskInput, answer: str) -> bool:
247
+ if not task.context.strip():
248
+ return False
249
+ answer_terms = {
250
+ item.lower()
251
+ for item in re.findall(r"[A-Za-z][A-Za-z0-9_-]{5,}", answer)
252
+ if item.lower() not in {"answer", "context", "because"}
253
+ }
254
+ context = task.context.lower()
255
+ unknown = [term for term in answer_terms if term not in context]
256
+ return len(unknown) >= 4
257
+
258
+
259
+ def _extract_json(text: str) -> dict[str, Any]:
260
+ try:
261
+ value = json.loads(text)
262
+ except json.JSONDecodeError:
263
+ match = re.search(r"\{.*\}", text, flags=re.DOTALL)
264
+ if not match:
265
+ raise
266
+ value = json.loads(match.group(0))
267
+ if not isinstance(value, dict):
268
+ raise ValueError("verifier output must be a JSON object")
269
+ return value
270
+
271
+
272
+ def create_verifier(policy: PolicyConfig, solver: Any | None = None) -> Any:
273
+ fallback = RuleBasedVerifier(policy.router.local_accept_confidence)
274
+ if os.getenv("LOCAL_VERIFIER_BACKEND", "rule").lower() == "local_llm" and solver is not None:
275
+ return LocalLLMVerifier(solver=solver, fallback=fallback)
276
+ return fallback
@@ -0,0 +1,65 @@
1
+ """Deterministic, fixture-based benchmark harness for lcc (ADR 0007, ADR 0010).
2
+
3
+ Runs deterministic optimize or prepare workflows over committed local fixtures and measures
4
+ mechanical behavior — token savings, compression ratio, character reduction, exact/
5
+ approximate token mode, literal marker preservation, warnings, prepare action, and lexical
6
+ selection state. It makes **no claim** about final LLM answer quality and performs no network
7
+ or model calls.
8
+
9
+ This package sits above ``lcc.pipeline`` (like the CLI); it composes the pipeline and does
10
+ not change any deterministic-core contract (ADR 0002, ADR 0006).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from lcc.benchmarking.case_loader import (
16
+ BenchmarkCaseError,
17
+ discover_case_dirs,
18
+ load_case,
19
+ load_suite,
20
+ )
21
+ from lcc.benchmarking.metadata import (
22
+ BENCH_METADATA_VERSION,
23
+ BenchmarkMetadata,
24
+ build_metadata,
25
+ metadata_to_dict,
26
+ )
27
+ from lcc.benchmarking.report import (
28
+ suite_to_dict,
29
+ suite_to_json,
30
+ suite_to_markdown,
31
+ write_suite_json,
32
+ write_suite_markdown,
33
+ )
34
+ from lcc.benchmarking.runner import find_markers, run_case, run_suite
35
+ from lcc.benchmarking.schemas import (
36
+ BENCH_SCHEMA_VERSION,
37
+ BenchmarkCase,
38
+ BenchmarkExpectations,
39
+ CaseResult,
40
+ SuiteResult,
41
+ )
42
+
43
+ __all__ = [
44
+ "BENCH_SCHEMA_VERSION",
45
+ "BENCH_METADATA_VERSION",
46
+ "BenchmarkCase",
47
+ "BenchmarkCaseError",
48
+ "BenchmarkExpectations",
49
+ "BenchmarkMetadata",
50
+ "CaseResult",
51
+ "SuiteResult",
52
+ "build_metadata",
53
+ "discover_case_dirs",
54
+ "find_markers",
55
+ "load_case",
56
+ "load_suite",
57
+ "metadata_to_dict",
58
+ "run_case",
59
+ "run_suite",
60
+ "suite_to_dict",
61
+ "suite_to_json",
62
+ "suite_to_markdown",
63
+ "write_suite_json",
64
+ "write_suite_markdown",
65
+ ]
@@ -0,0 +1,257 @@
1
+ """Load benchmark cases from disk into validated dataclasses (ADR 0007).
2
+
3
+ This is the benchmark harness's IO boundary, analogous to ``token_budget.pricing.load_pricing``:
4
+ it reads committed fixture files (a ``case.yaml`` plus an ``input.txt``), validates them, and
5
+ returns pure dataclasses. It performs no network or model calls.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import yaml
14
+
15
+ from lcc.benchmarking.schemas import (
16
+ COMPRESSION_LEVELS,
17
+ WORKFLOWS,
18
+ BenchmarkCase,
19
+ BenchmarkExpectations,
20
+ )
21
+
22
+ CASE_FILE = "case.yaml"
23
+ INPUT_FILE = "input.txt"
24
+
25
+ _EXPECTATION_KEYS = {
26
+ "min_token_savings_percent",
27
+ "max_token_savings_percent",
28
+ "min_required_marker_recall",
29
+ "allow_approximate_token_count",
30
+ "max_forbidden_markers_found",
31
+ "expected_prepare_action",
32
+ "expected_selection_applied",
33
+ "min_selected_chunk_count",
34
+ "max_selected_chunk_count",
35
+ "min_skipped_duplicate_chunk_count",
36
+ }
37
+
38
+ _PREPARE_ACTIONS = {"skip", "optimize_safe", "optimize_with_flags", "manual_review"}
39
+
40
+
41
+ class BenchmarkCaseError(ValueError):
42
+ """Raised when a benchmark case directory is missing files or has invalid metadata."""
43
+
44
+
45
+ def discover_case_dirs(root: str | Path) -> list[Path]:
46
+ """Return benchmark case directories under ``root`` (those containing a ``case.yaml``).
47
+
48
+ Sorted by directory name for deterministic ordering. Raises ``BenchmarkCaseError`` when
49
+ ``root`` is missing, is not a directory, or contains no cases.
50
+ """
51
+ root_path = Path(root)
52
+ if not root_path.exists():
53
+ raise BenchmarkCaseError(f"benchmark path does not exist: {root}")
54
+ if not root_path.is_dir():
55
+ raise BenchmarkCaseError(f"benchmark path is not a directory: {root}")
56
+ dirs = sorted(
57
+ (
58
+ child
59
+ for child in root_path.iterdir()
60
+ if child.is_dir() and (child / CASE_FILE).is_file()
61
+ ),
62
+ key=lambda path: path.name,
63
+ )
64
+ if not dirs:
65
+ raise BenchmarkCaseError(
66
+ f"no benchmark cases (subdirectories with a {CASE_FILE}) under: {root}"
67
+ )
68
+ return dirs
69
+
70
+
71
+ def load_suite(root: str | Path) -> list[BenchmarkCase]:
72
+ """Discover and load every benchmark case under ``root``."""
73
+ return [load_case(case_dir) for case_dir in discover_case_dirs(root)]
74
+
75
+
76
+ def load_case(case_dir: str | Path) -> BenchmarkCase:
77
+ """Load and validate a single benchmark case directory into a ``BenchmarkCase``."""
78
+ cdir = Path(case_dir)
79
+ case_file = cdir / CASE_FILE
80
+ input_file = cdir / INPUT_FILE
81
+ where = cdir.name or str(cdir)
82
+
83
+ if not case_file.is_file():
84
+ raise BenchmarkCaseError(f"case {where!r}: missing {CASE_FILE}")
85
+ if not input_file.is_file():
86
+ raise BenchmarkCaseError(f"case {where!r}: missing {INPUT_FILE}")
87
+
88
+ try:
89
+ loaded = yaml.safe_load(case_file.read_text(encoding="utf-8"))
90
+ except yaml.YAMLError as exc:
91
+ raise BenchmarkCaseError(f"case {where!r}: could not parse {CASE_FILE}: {exc}") from exc
92
+ if not isinstance(loaded, dict):
93
+ raise BenchmarkCaseError(f"case {where!r}: {CASE_FILE} must contain a YAML mapping")
94
+ data: dict[str, Any] = loaded
95
+
96
+ compression_level = _optional_str(data, "compression_level", where, default="safe")
97
+ if compression_level not in COMPRESSION_LEVELS:
98
+ supported = ", ".join(sorted(COMPRESSION_LEVELS))
99
+ raise BenchmarkCaseError(
100
+ f"case {where!r}: unknown compression_level {compression_level!r}; "
101
+ f"supported: {supported}"
102
+ )
103
+ workflow = _optional_str(data, "workflow", where, default="optimize")
104
+ if workflow not in WORKFLOWS:
105
+ supported = ", ".join(sorted(WORKFLOWS))
106
+ raise BenchmarkCaseError(
107
+ f"case {where!r}: unknown workflow {workflow!r}; supported: {supported}"
108
+ )
109
+
110
+ return BenchmarkCase(
111
+ id=_required_str(data, "id", where),
112
+ description=_required_str(data, "description", where),
113
+ question=_required_str(data, "question", where, allow_empty=True),
114
+ input_text=input_file.read_text(encoding="utf-8"),
115
+ workflow=workflow,
116
+ model=_optional_str(data, "model", where, default="gpt-4.1"),
117
+ max_input_tokens=_optional_int(data, "max_input_tokens", where),
118
+ compression_level=compression_level,
119
+ required_markers=_str_list(data, "required_markers", where),
120
+ forbidden_markers=_str_list(data, "forbidden_markers", where),
121
+ expectations=_parse_expectations(data.get("expectations"), where),
122
+ )
123
+
124
+
125
+ def _required_str(data: dict[str, Any], key: str, where: str, *, allow_empty: bool = False) -> str:
126
+ value = data.get(key)
127
+ if value is None:
128
+ raise BenchmarkCaseError(f"case {where!r}: missing required field {key!r}")
129
+ if not isinstance(value, str):
130
+ raise BenchmarkCaseError(f"case {where!r}: field {key!r} must be a string")
131
+ if not allow_empty and not value.strip():
132
+ raise BenchmarkCaseError(f"case {where!r}: field {key!r} must not be empty")
133
+ return value
134
+
135
+
136
+ def _optional_str(data: dict[str, Any], key: str, where: str, *, default: str) -> str:
137
+ value = data.get(key)
138
+ if value is None:
139
+ return default
140
+ if not isinstance(value, str):
141
+ raise BenchmarkCaseError(f"case {where!r}: field {key!r} must be a string")
142
+ return value
143
+
144
+
145
+ def _optional_int(data: dict[str, Any], key: str, where: str) -> int | None:
146
+ value = data.get(key)
147
+ if value is None:
148
+ return None
149
+ if isinstance(value, bool) or not isinstance(value, int):
150
+ raise BenchmarkCaseError(f"case {where!r}: field {key!r} must be an integer or null")
151
+ return value
152
+
153
+
154
+ def _str_list(data: dict[str, Any], key: str, where: str) -> list[str]:
155
+ value = data.get(key)
156
+ if value is None:
157
+ return []
158
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
159
+ raise BenchmarkCaseError(f"case {where!r}: field {key!r} must be a list of strings")
160
+ return list(value)
161
+
162
+
163
+ def _parse_expectations(value: Any, where: str) -> BenchmarkExpectations:
164
+ if value is None:
165
+ return BenchmarkExpectations()
166
+ if not isinstance(value, dict):
167
+ raise BenchmarkCaseError(f"case {where!r}: 'expectations' must be a mapping")
168
+ unknown = set(value) - _EXPECTATION_KEYS
169
+ if unknown:
170
+ raise BenchmarkCaseError(
171
+ f"case {where!r}: unknown expectation key(s): {', '.join(sorted(map(str, unknown)))}"
172
+ )
173
+
174
+ exp = BenchmarkExpectations()
175
+ if "min_token_savings_percent" in value:
176
+ exp.min_token_savings_percent = _as_float(value, "min_token_savings_percent", where)
177
+ if "max_token_savings_percent" in value:
178
+ exp.max_token_savings_percent = _as_float(value, "max_token_savings_percent", where)
179
+ if "min_required_marker_recall" in value:
180
+ exp.min_required_marker_recall = _as_float(value, "min_required_marker_recall", where)
181
+ if "allow_approximate_token_count" in value:
182
+ exp.allow_approximate_token_count = _as_bool(value, "allow_approximate_token_count", where)
183
+ if "max_forbidden_markers_found" in value:
184
+ exp.max_forbidden_markers_found = _as_int(value, "max_forbidden_markers_found", where)
185
+ if "expected_prepare_action" in value:
186
+ exp.expected_prepare_action = _as_prepare_action(value, "expected_prepare_action", where)
187
+ if "expected_selection_applied" in value:
188
+ exp.expected_selection_applied = _as_bool(value, "expected_selection_applied", where)
189
+ if "min_selected_chunk_count" in value:
190
+ exp.min_selected_chunk_count = _as_int(value, "min_selected_chunk_count", where)
191
+ if "max_selected_chunk_count" in value:
192
+ exp.max_selected_chunk_count = _as_int(value, "max_selected_chunk_count", where)
193
+ if "min_skipped_duplicate_chunk_count" in value:
194
+ exp.min_skipped_duplicate_chunk_count = _as_int(
195
+ value, "min_skipped_duplicate_chunk_count", where
196
+ )
197
+
198
+ if not 0.0 <= exp.min_required_marker_recall <= 1.0:
199
+ raise BenchmarkCaseError(
200
+ f"case {where!r}: min_required_marker_recall must be within [0.0, 1.0]"
201
+ )
202
+ if exp.min_token_savings_percent > exp.max_token_savings_percent:
203
+ raise BenchmarkCaseError(
204
+ f"case {where!r}: min_token_savings_percent exceeds max_token_savings_percent"
205
+ )
206
+ if exp.max_forbidden_markers_found < 0:
207
+ raise BenchmarkCaseError(
208
+ f"case {where!r}: max_forbidden_markers_found must not be negative"
209
+ )
210
+ if exp.min_skipped_duplicate_chunk_count < 0:
211
+ raise BenchmarkCaseError(
212
+ f"case {where!r}: min_skipped_duplicate_chunk_count must not be negative"
213
+ )
214
+ if exp.min_selected_chunk_count is not None and exp.min_selected_chunk_count < 0:
215
+ raise BenchmarkCaseError(f"case {where!r}: min_selected_chunk_count must not be negative")
216
+ if exp.max_selected_chunk_count is not None and exp.max_selected_chunk_count < 0:
217
+ raise BenchmarkCaseError(f"case {where!r}: max_selected_chunk_count must not be negative")
218
+ if (
219
+ exp.min_selected_chunk_count is not None
220
+ and exp.max_selected_chunk_count is not None
221
+ and exp.min_selected_chunk_count > exp.max_selected_chunk_count
222
+ ):
223
+ raise BenchmarkCaseError(
224
+ f"case {where!r}: min_selected_chunk_count exceeds max_selected_chunk_count"
225
+ )
226
+ return exp
227
+
228
+
229
+ def _as_float(data: dict[str, Any], key: str, where: str) -> float:
230
+ value = data[key]
231
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
232
+ raise BenchmarkCaseError(f"case {where!r}: expectation {key!r} must be a number")
233
+ return float(value)
234
+
235
+
236
+ def _as_int(data: dict[str, Any], key: str, where: str) -> int:
237
+ value = data[key]
238
+ if isinstance(value, bool) or not isinstance(value, int):
239
+ raise BenchmarkCaseError(f"case {where!r}: expectation {key!r} must be an integer")
240
+ return value
241
+
242
+
243
+ def _as_bool(data: dict[str, Any], key: str, where: str) -> bool:
244
+ value = data[key]
245
+ if not isinstance(value, bool):
246
+ raise BenchmarkCaseError(f"case {where!r}: expectation {key!r} must be a boolean")
247
+ return value
248
+
249
+
250
+ def _as_prepare_action(data: dict[str, Any], key: str, where: str) -> str:
251
+ value = data[key]
252
+ if not isinstance(value, str):
253
+ raise BenchmarkCaseError(f"case {where!r}: expectation {key!r} must be a string")
254
+ if value not in _PREPARE_ACTIONS:
255
+ supported = ", ".join(sorted(_PREPARE_ACTIONS))
256
+ raise BenchmarkCaseError(f"case {where!r}: expectation {key!r} must be one of: {supported}")
257
+ return value
@@ -0,0 +1,90 @@
1
+ """Reproducible benchmark metadata (ADR 0014).
2
+
3
+ Every benchmark result must record the full identity of what produced it: corpus and
4
+ objective hashes, requested vs resolved model, provider, policy/schema/tokenizer
5
+ versions, timestamp, configuration, thresholds and seed. A moving alias such as
6
+ ``jev-latest`` is never the only model identifier — the resolved version is recorded
7
+ alongside it.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import time
14
+ from dataclasses import asdict, dataclass, field
15
+ from typing import Any
16
+
17
+ from lcc.relevance.compactor import RELEVANCE_SCHEMA_VERSION
18
+ from lcc.relevance.decisions import (
19
+ BLOCK_PARSER_VERSION,
20
+ POLICY_VERSION,
21
+ PROTECTION_VERSION,
22
+ RELATIONSHIP_VERSION,
23
+ )
24
+ from lcc.relevance.trim import TRIM_POLICY_VERSION
25
+
26
+ BENCH_METADATA_VERSION = "bench-metadata-1.0"
27
+
28
+
29
+ def _sha256(text: str) -> str:
30
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class BenchmarkMetadata:
35
+ """Identity of one benchmark measurement; JSON-serializable via :func:`metadata_to_dict`."""
36
+
37
+ metadata_version: str = BENCH_METADATA_VERSION
38
+ corpus_sha256: str = ""
39
+ objective_sha256: str = ""
40
+ requested_model: str = ""
41
+ resolved_model: str | None = None
42
+ provider: str = ""
43
+ policy_version: str = POLICY_VERSION
44
+ schema_version: str = RELEVANCE_SCHEMA_VERSION
45
+ block_parser_version: str = BLOCK_PARSER_VERSION
46
+ protection_version: str = PROTECTION_VERSION
47
+ relationship_version: str = RELATIONSHIP_VERSION
48
+ trim_policy_version: str = TRIM_POLICY_VERSION
49
+ tokenizer_id: str = ""
50
+ tokenizer_version: str | None = None
51
+ token_count_method: str = ""
52
+ timestamp: str = ""
53
+ configuration: dict[str, Any] = field(default_factory=dict)
54
+ thresholds: dict[str, Any] = field(default_factory=dict)
55
+ seed: int | None = None
56
+
57
+
58
+ def build_metadata(
59
+ *,
60
+ corpus: str,
61
+ objective: str,
62
+ requested_model: str,
63
+ resolved_model: str | None = None,
64
+ provider: str = "",
65
+ configuration: dict[str, Any] | None = None,
66
+ thresholds: dict[str, Any] | None = None,
67
+ seed: int | None = None,
68
+ tokenizer_id: str = "",
69
+ tokenizer_version: str | None = None,
70
+ token_count_method: str = "",
71
+ ) -> BenchmarkMetadata:
72
+ """Build metadata for one measurement; timestamp is UTC ISO-8601."""
73
+ return BenchmarkMetadata(
74
+ corpus_sha256=_sha256(corpus),
75
+ objective_sha256=_sha256(objective),
76
+ requested_model=requested_model,
77
+ resolved_model=resolved_model or requested_model,
78
+ provider=provider,
79
+ configuration=dict(configuration or {}),
80
+ thresholds=dict(thresholds or {}),
81
+ seed=seed,
82
+ tokenizer_id=tokenizer_id,
83
+ tokenizer_version=tokenizer_version,
84
+ token_count_method=token_count_method,
85
+ timestamp=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
86
+ )
87
+
88
+
89
+ def metadata_to_dict(meta: BenchmarkMetadata) -> dict[str, Any]:
90
+ return asdict(meta)