emrekuruu commited on
Commit
adaffb2
·
verified ·
1 Parent(s): 81a00cc

Argument descriptions carry format only; environment description is the single home of world rules

Browse files
README.md CHANGED
@@ -3,10 +3,7 @@ title: SpreadsheetBench OpenEnv
3
  sdk: docker
4
  app_port: 8000
5
  tags:
6
- - rl-environment
7
- emoji: 📊
8
- colorTo: green
9
- colorFrom: green
10
  ---
11
 
12
  # SpreadsheetBench OpenEnv
@@ -19,4 +16,4 @@ The canonical package catalog contains 901 validated instruction-bearing tasks s
19
 
20
  Install with the server extra, set `SPREADSHEETBENCH_DATA` to a runtime root containing the canonical `spreadsheet/<task-id>/` workbook directories, and run `server`.
21
 
22
- Generated scripts execute in bounded subprocesses with scrubbed environments, resource limits, process-group cleanup, and private per-session directories. The Docker deployment leases a distinct unprivileged UID to every active session while the hidden runtime tree remains root-only. This is pragmatic process containment, not a complete network or kernel sandbox.
 
3
  sdk: docker
4
  app_port: 8000
5
  tags:
6
+ - rl-environment
 
 
 
7
  ---
8
 
9
  # SpreadsheetBench OpenEnv
 
16
 
17
  Install with the server extra, set `SPREADSHEETBENCH_DATA` to a runtime root containing the canonical `spreadsheet/<task-id>/` workbook directories, and run `server`.
18
 
19
+ Generated scripts execute in bounded subprocesses with scrubbed environments, resource limits, process-group cleanup, and private per-session directories. The Docker deployment leases a distinct unprivileged UID to every active session while the hidden runtime tree remains root-only. This is pragmatic process containment, not a complete network or kernel sandbox.
scripts/build_runtime_archive.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the deterministic SpreadsheetBench runtime workbook archive."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ import subprocess
9
+ import tarfile
10
+ import tempfile
11
+
12
+
13
+ ARCHIVE_NAME = "spreadsheetbench-runtime-v0.1.tar.zst"
14
+
15
+
16
+ def referenced_paths(package_root: Path) -> tuple[str, ...]:
17
+ task_root = package_root / "src/spreadsheetbench_env/assets/tasks"
18
+ paths: list[str] = []
19
+ for filename in ("dev.json", "test.json"):
20
+ payload = json.loads((task_root / filename).read_text(encoding="utf-8"))
21
+ for task in payload["tasks"]:
22
+ for case in task["cases"]:
23
+ paths.extend((str(case["input"]), str(case["answer"])))
24
+ if len(paths) != len(set(paths)):
25
+ raise ValueError("canonical SpreadsheetBench cases contain duplicate runtime paths")
26
+ return tuple(sorted(paths))
27
+
28
+
29
+ def _normalized_tar(package_root: Path, source_root: Path, destination: Path) -> None:
30
+ with tarfile.open(destination, "w", format=tarfile.PAX_FORMAT) as archive:
31
+ for relative in referenced_paths(package_root):
32
+ source = (source_root / relative).resolve()
33
+ if not source.is_relative_to(source_root.resolve()) or not source.is_file():
34
+ raise FileNotFoundError(f"missing canonical runtime workbook: {relative}")
35
+ info = archive.gettarinfo(str(source), arcname=relative)
36
+ info.uid = 0
37
+ info.gid = 0
38
+ info.uname = "root"
39
+ info.gname = "root"
40
+ info.mtime = 0
41
+ info.mode = 0o600
42
+ with source.open("rb") as handle:
43
+ archive.addfile(info, handle)
44
+
45
+
46
+ def build_archive(repository: Path) -> Path:
47
+ package_root = repository / "environments/spreadsheetbench"
48
+ source_root = repository / "data/spreadsheetbench"
49
+ output_root = package_root / "runtime-data"
50
+ output_root.mkdir(parents=True, exist_ok=True)
51
+ archive_path = output_root / ARCHIVE_NAME
52
+ with tempfile.TemporaryDirectory(prefix="spreadsheetbench-runtime-") as temp:
53
+ tar_path = Path(temp) / "runtime.tar"
54
+ compressed_path = Path(temp) / ARCHIVE_NAME
55
+ _normalized_tar(package_root, source_root, tar_path)
56
+ subprocess.run(
57
+ [
58
+ "zstd",
59
+ "--quiet",
60
+ "--threads=0",
61
+ "-19",
62
+ "--no-check",
63
+ "-o",
64
+ str(compressed_path),
65
+ str(tar_path),
66
+ ],
67
+ check=True,
68
+ )
69
+ compressed_path.replace(archive_path)
70
+ digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
71
+ archive_path.with_suffix(archive_path.suffix + ".sha256").write_text(
72
+ f"{digest} {archive_path.name}\n",
73
+ encoding="utf-8",
74
+ )
75
+ return archive_path
76
+
77
+
78
+ def main() -> None:
79
+ repository = Path(__file__).resolve().parents[3]
80
+ archive = build_archive(repository)
81
+ print(archive)
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
scripts/freeze_catalog.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Freeze the validated SpreadsheetBench catalog from the official local release."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ import hashlib
7
+ import json
8
+ from pathlib import Path
9
+ import re
10
+
11
+
12
+ ARCHIVE_SHA256 = "9cf7228b54f1edcdd4b372eb736774adf29cb4f804c9920229bac6c154833399"
13
+ SOURCE_REVISION = (
14
+ "KAKA22/SpreadsheetBench spreadsheetbench_912_v0.1.tar.gz SHA-256 "
15
+ f"{ARCHIVE_SHA256}; EnvCommons validation reference "
16
+ "f9ae2bb897da711e4d4cd36e1f78be0c94cfd5a6"
17
+ )
18
+ EXCLUSIONS = {
19
+ "189-9": ("time-dependent", "TODAY()-relative answer is frozen to dataset-build time"),
20
+ "283-32": ("invalid-metadata", "invalid cell reference A"),
21
+ "73-45": ("invalid-metadata", "invalid cell reference 308"),
22
+ "118-8": ("invalid-metadata", "answer sheet mismatch"),
23
+ "130-9": ("invalid-metadata", "answer sheet mismatch"),
24
+ "532-3": ("invalid-metadata", "invalid nested sheet/cell reference"),
25
+ "CF_25745": ("invalid-metadata", "answer sheet mismatch"),
26
+ "52763": ("invalid-metadata", "answer sheet mismatch"),
27
+ "55224": ("empty-instruction", "instruction contains only whitespace"),
28
+ "55457": ("empty-instruction", "instruction contains only whitespace"),
29
+ "55877": ("empty-instruction", "instruction contains only whitespace"),
30
+ }
31
+
32
+
33
+ def sha256_text(value: str) -> str:
34
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
35
+
36
+
37
+ def source_identity(task_id: str) -> str:
38
+ match = re.fullmatch(r"(\d+)-\d+", task_id)
39
+ return f"source:{match.group(1)}" if match else f"task:{task_id}"
40
+
41
+
42
+ def anonymous_group(identity: str) -> str:
43
+ return f"group-{sha256_text(f'spreadsheetbench-source-v1:{identity}')[:20]}"
44
+
45
+
46
+ def choose_test_groups(group_sizes: dict[str, int], target: int) -> set[str]:
47
+ namespace = "spreadsheetbench-700-201-source-group-v1"
48
+ ordered = sorted(
49
+ group_sizes,
50
+ key=lambda group: sha256_text(f"{namespace}:{group}"),
51
+ )
52
+ reachable: dict[int, tuple[str, ...]] = {0: ()}
53
+ for group in ordered:
54
+ size = group_sizes[group]
55
+ for total, selected in tuple(sorted(reachable.items(), reverse=True)):
56
+ candidate = total + size
57
+ if candidate <= target and candidate not in reachable:
58
+ reachable[candidate] = (*selected, group)
59
+ if target in reachable:
60
+ return set(reachable[target])
61
+ raise RuntimeError(f"cannot construct an exact {target}-task source-group split")
62
+
63
+
64
+ def effective_answer_position(record: dict[str, object]) -> str:
65
+ return str(record.get("answer_position") or "").strip()
66
+
67
+
68
+ def build_record(record: dict[str, object], data_root: Path) -> dict[str, object]:
69
+ task_id = str(record["id"])
70
+ task_dir = data_root / str(record["spreadsheet_path"])
71
+ cases: list[dict[str, str]] = []
72
+ for input_path in sorted(task_dir.glob("*_input.xlsx")):
73
+ answer_path = input_path.with_name(
74
+ input_path.name.replace("_input.xlsx", "_answer.xlsx")
75
+ )
76
+ if not answer_path.is_file():
77
+ raise FileNotFoundError(f"{task_id}: missing {answer_path.name}")
78
+ cases.append(
79
+ {
80
+ "input": f"spreadsheet/{task_id}/{input_path.name}",
81
+ "answer": f"spreadsheet/{task_id}/{answer_path.name}",
82
+ }
83
+ )
84
+ if not cases:
85
+ raise FileNotFoundError(f"{task_id}: no input cases")
86
+ instruction = str(record["instruction"])
87
+ if not instruction.strip():
88
+ raise ValueError(f"{task_id}: empty instruction was not excluded")
89
+ group = source_identity(task_id)
90
+ return {
91
+ "source_id": task_id,
92
+ "task_type": str(record["instruction_type"]),
93
+ "instruction": instruction,
94
+ "initial_observation": "",
95
+ "answer_position": effective_answer_position(record),
96
+ "cases": cases,
97
+ "source_group": anonymous_group(group),
98
+ }
99
+
100
+
101
+ def write_json(path: Path, payload: object) -> None:
102
+ path.parent.mkdir(parents=True, exist_ok=True)
103
+ path.write_text(
104
+ json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
105
+ encoding="utf-8",
106
+ )
107
+
108
+
109
+ def main() -> None:
110
+ repository = Path(__file__).resolve().parents[3]
111
+ data_root = repository / "data" / "spreadsheetbench"
112
+ raw_path = data_root / "dataset.json"
113
+ raw = json.loads(raw_path.read_text(encoding="utf-8"))
114
+ if len(raw) != 912:
115
+ raise ValueError(f"expected 912 official tasks, found {len(raw)}")
116
+ raw_ids = {str(record["id"]) for record in raw}
117
+ if not set(EXCLUSIONS) <= raw_ids:
118
+ raise ValueError("exclusion report contains IDs absent from the official release")
119
+
120
+ included: list[dict[str, object]] = []
121
+ for record in raw:
122
+ if str(record["id"]) in EXCLUSIONS:
123
+ continue
124
+ frozen = build_record(record, data_root)
125
+ frozen["task_idx"] = len(included)
126
+ included.append(frozen)
127
+ if len(included) != 901:
128
+ raise ValueError(f"expected 901 validated tasks, found {len(included)}")
129
+
130
+ grouped: dict[str, list[dict[str, object]]] = defaultdict(list)
131
+ for record in included:
132
+ grouped[str(record["source_group"])].append(record)
133
+ test_groups = choose_test_groups(
134
+ {group: len(records) for group, records in grouped.items()},
135
+ 201,
136
+ )
137
+ development = [
138
+ record for record in included if str(record["source_group"]) not in test_groups
139
+ ]
140
+ test = [
141
+ record for record in included if str(record["source_group"]) in test_groups
142
+ ]
143
+ if (len(development), len(test)) != (700, 201):
144
+ raise RuntimeError("unexpected SpreadsheetBench split sizes")
145
+
146
+ output = repository / "environments" / "spreadsheetbench" / "src" / "spreadsheetbench_env" / "assets" / "tasks"
147
+ common = {
148
+ "schema_version": 1,
149
+ "benchmark": "spreadsheetbench",
150
+ "source": "SpreadsheetBench complete v0.1 release, validated instruction-bearing tasks",
151
+ "source_revision": SOURCE_REVISION,
152
+ "split_policy": "source-group-disjoint deterministic subset-sum; namespace spreadsheetbench-700-201-source-group-v1",
153
+ }
154
+ write_json(output / "dev.json", {**common, "role": "development", "tasks": development})
155
+ write_json(output / "test.json", {**common, "role": "test", "tasks": test})
156
+ write_json(
157
+ output / "exclusions.json",
158
+ {
159
+ "schema_version": 1,
160
+ "benchmark": "spreadsheetbench",
161
+ "source_revision": SOURCE_REVISION,
162
+ "raw_task_count": 912,
163
+ "included_task_count": 901,
164
+ "exclusions": [
165
+ {"task_id": task_id, "category": category, "reason": reason}
166
+ for task_id, (category, reason) in EXCLUSIONS.items()
167
+ ],
168
+ },
169
+ )
170
+
171
+
172
+ if __name__ == "__main__":
173
+ main()
scripts/generate_schemas.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate checked-in JSON Schema snapshots from typed OpenEnv models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ from spreadsheetbench_env.models import (
9
+ SpreadsheetBenchAction,
10
+ SpreadsheetBenchObservation,
11
+ SpreadsheetBenchState,
12
+ )
13
+
14
+
15
+ def main() -> None:
16
+ root = Path(__file__).resolve().parents[1] / "src/spreadsheetbench_env/assets/schemas"
17
+ schemas = {
18
+ "action.schema.json": SpreadsheetBenchAction.model_json_schema(),
19
+ "observation.schema.json": SpreadsheetBenchObservation.model_json_schema(),
20
+ "state.schema.json": SpreadsheetBenchState.model_json_schema(),
21
+ }
22
+ for filename, schema in schemas.items():
23
+ (root / filename).write_text(
24
+ json.dumps(schema, indent=2, ensure_ascii=False) + "\n",
25
+ encoding="utf-8",
26
+ )
27
+
28
+
29
+ if __name__ == "__main__":
30
+ main()
src/spreadsheetbench_env/assets/schemas/action.schema.json CHANGED
@@ -2,17 +2,17 @@
2
  "additionalProperties": false,
3
  "description": "The single complete Python script submitted for an episode.",
4
  "properties": {
 
 
 
 
 
 
5
  "metadata": {
6
  "additionalProperties": true,
7
  "description": "Additional metadata for the action",
8
  "title": "Metadata",
9
  "type": "object"
10
- },
11
- "code": {
12
- "description": "One complete Python script. Read the injected INPUT_PATH variable and write the modified workbook to the injected OUTPUT_PATH variable. The same script is run independently on all hidden cases.\n\nSpreadsheetBench is a single-shot spreadsheet manipulation environment. The current observation contains one task instruction, the expected answer position, and a truncated preview of the first input workbook. Submit exactly one complete Python script in the code field. The server runs the same script independently on every hidden input case with INPUT_PATH and OUTPUT_PATH injected as variables. The script must read INPUT_PATH, preserve unrelated workbook content, and save the modified workbook to OUTPUT_PATH. The episode terminates after that one submission. All hidden cases must pass for reward 1.",
13
- "minLength": 1,
14
- "title": "Code",
15
- "type": "string"
16
  }
17
  },
18
  "required": [
 
2
  "additionalProperties": false,
3
  "description": "The single complete Python script submitted for an episode.",
4
  "properties": {
5
+ "code": {
6
+ "description": "One complete Python script. Read the injected INPUT_PATH variable and write the modified workbook to the injected OUTPUT_PATH variable. The same script is run independently on all hidden cases.",
7
+ "minLength": 1,
8
+ "title": "Code",
9
+ "type": "string"
10
+ },
11
  "metadata": {
12
  "additionalProperties": true,
13
  "description": "Additional metadata for the action",
14
  "title": "Metadata",
15
  "type": "object"
 
 
 
 
 
 
16
  }
17
  },
18
  "required": [
src/spreadsheetbench_env/models.py CHANGED
@@ -7,7 +7,6 @@ from typing import Any
7
  from openenv.core.env_server.types import Action, Observation, State
8
  from pydantic import BaseModel, ConfigDict, Field, model_validator
9
 
10
- from spreadsheetbench_env.interface import environment_description
11
 
12
 
13
  class SpreadsheetBenchSubmitScript(BaseModel):
@@ -20,8 +19,7 @@ class SpreadsheetBenchSubmitScript(BaseModel):
20
  description=(
21
  "One complete Python script. Read the injected INPUT_PATH variable and "
22
  "write the modified workbook to the injected OUTPUT_PATH variable. The "
23
- "same script is run independently on all hidden cases.\n\n"
24
- + environment_description()
25
  ),
26
  )
27
 
 
7
  from openenv.core.env_server.types import Action, Observation, State
8
  from pydantic import BaseModel, ConfigDict, Field, model_validator
9
 
 
10
 
11
 
12
  class SpreadsheetBenchSubmitScript(BaseModel):
 
19
  description=(
20
  "One complete Python script. Read the injected INPUT_PATH variable and "
21
  "write the modified workbook to the injected OUTPUT_PATH variable. The "
22
+ "same script is run independently on all hidden cases."
 
23
  ),
24
  )
25
 
tests/test_catalog.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contract tests for the standalone SpreadsheetBench catalog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import FrozenInstanceError
6
+ import hashlib
7
+ from importlib.resources import files
8
+ import json
9
+
10
+ import pytest
11
+
12
+ from spreadsheetbench_env.catalog import catalog_sha256, get_split, get_task
13
+
14
+
15
+ EXCLUDED_IDS = {
16
+ "189-9",
17
+ "283-32",
18
+ "73-45",
19
+ "118-8",
20
+ "130-9",
21
+ "532-3",
22
+ "CF_25745",
23
+ "52763",
24
+ "55224",
25
+ "55457",
26
+ "55877",
27
+ }
28
+
29
+
30
+ def test_catalog_is_the_only_packaged_task_authority() -> None:
31
+ assets = files("spreadsheetbench_env").joinpath("assets")
32
+ directories = {child.name for child in assets.iterdir() if child.is_dir()}
33
+ assert directories == {"tasks", "schemas"}
34
+ assert {child.name for child in assets.joinpath("tasks").iterdir()} == {
35
+ "dev.json",
36
+ "test.json",
37
+ "exclusions.json",
38
+ }
39
+
40
+
41
+ def test_catalog_freezes_validated_901_task_population_and_700_201_split() -> None:
42
+ development = get_split("development")
43
+ test = get_split("test")
44
+ assert len(development.tasks) == 700
45
+ assert len(test.tasks) == 201
46
+ assert development.role == "development"
47
+ assert test.role == "test"
48
+ assert development.source_revision == test.source_revision
49
+ assert "9cf7228b54f1edcdd4b372eb736774adf29cb4f804c9920229bac6c154833399" in development.source_revision
50
+
51
+ tasks = (*development.tasks, *test.tasks)
52
+ ids = [task.task_id for task in tasks]
53
+ assert len(ids) == len(set(ids)) == 901
54
+ assert set(ids) == set(range(901))
55
+ source_ids = [task.source_id for task in tasks]
56
+ assert len(source_ids) == len(set(source_ids)) == 901
57
+ assert EXCLUDED_IDS.isdisjoint(source_ids)
58
+ assert all(task.instruction.strip() for task in tasks)
59
+ assert all(task.cases for task in tasks)
60
+ assert all(task.answer_position for task in tasks)
61
+ assert all(get_task(task.task_id) is task for task in tasks)
62
+
63
+
64
+ def test_source_groups_never_cross_the_frozen_boundary() -> None:
65
+ development_groups = {task.source_group for task in get_split("development").tasks}
66
+ test_groups = {task.source_group for task in get_split("test").tasks}
67
+ assert development_groups.isdisjoint(test_groups)
68
+
69
+
70
+ def test_catalog_preserves_raw_official_answer_position_semantics() -> None:
71
+ assert get_task(19).source_id == "53-14"
72
+ assert get_task(19).answer_position == "B1:C5"
73
+ assert get_task(22).source_id == "60-7"
74
+ assert get_task(22).answer_position == "A3:E11"
75
+
76
+
77
+ def test_exclusion_report_is_explicit_and_complete() -> None:
78
+ report = json.loads(
79
+ files("spreadsheetbench_env")
80
+ .joinpath("assets", "tasks", "exclusions.json")
81
+ .read_text(encoding="utf-8")
82
+ )
83
+ assert report["raw_task_count"] == 912
84
+ assert report["included_task_count"] == 901
85
+ assert {item["task_id"] for item in report["exclusions"]} == EXCLUDED_IDS
86
+ assert {item["category"] for item in report["exclusions"]} == {
87
+ "time-dependent",
88
+ "invalid-metadata",
89
+ "empty-instruction",
90
+ }
91
+ report_bytes = (
92
+ files("spreadsheetbench_env")
93
+ .joinpath("assets", "tasks", "exclusions.json")
94
+ .read_bytes()
95
+ )
96
+ assert hashlib.sha256(report_bytes).hexdigest() == (
97
+ "48b0941be310e590f8a3cd22ee8717831724b273e502b3216ee81489d8a21c62"
98
+ )
99
+
100
+
101
+ def test_catalog_records_are_immutable() -> None:
102
+ task = get_split("development").tasks[0]
103
+ with pytest.raises(FrozenInstanceError):
104
+ task.task_id = "changed" # type: ignore[misc]
105
+
106
+
107
+ def test_catalog_digest_is_deterministic() -> None:
108
+ assert catalog_sha256() == (
109
+ "23eb892ee3d3610d41664f03f27503fda5cd148a1c7663ce593bb4cede063016"
110
+ )
tests/test_core.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Framework-neutral SpreadsheetBench episode tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ import shutil
8
+
9
+ import openpyxl
10
+ import pytest
11
+
12
+ from spreadsheetbench_env.catalog import SpreadsheetCase, SpreadsheetTask
13
+ from spreadsheetbench_env.core import SpreadsheetBenchCore
14
+ from spreadsheetbench_env.executor import ExecutionResult
15
+ from spreadsheetbench_env.grader import InfraError
16
+
17
+
18
+ def _workbook(path: Path, value: object) -> None:
19
+ path.parent.mkdir(parents=True, exist_ok=True)
20
+ workbook = openpyxl.Workbook()
21
+ workbook.active.title = "Data"
22
+ workbook.active["B2"] = value
23
+ workbook.save(path)
24
+ workbook.close()
25
+
26
+
27
+ def _task() -> SpreadsheetTask:
28
+ return SpreadsheetTask(
29
+ task_id=7,
30
+ source_id="task-1",
31
+ task_type="Cell-Level Manipulation",
32
+ instruction="Double the value in Data!B2.",
33
+ answer_position="Data!B2",
34
+ cases=(
35
+ SpreadsheetCase("spreadsheet/task-1/1_input.xlsx", "spreadsheet/task-1/1_answer.xlsx"),
36
+ SpreadsheetCase("spreadsheet/task-1/2_input.xlsx", "spreadsheet/task-1/2_answer.xlsx"),
37
+ ),
38
+ source_group="group-test",
39
+ )
40
+
41
+
42
+ @dataclass
43
+ class FakeExecutor:
44
+ root: Path
45
+ output_values: tuple[object, ...] = (4, 999)
46
+
47
+ def __post_init__(self) -> None:
48
+ self.root.mkdir(parents=True)
49
+ self.calls: list[tuple[str, Path, str]] = []
50
+ self.closed = False
51
+
52
+ def run(self, code: str, input_path: str | Path, *, case_name: str) -> ExecutionResult:
53
+ self.calls.append((code, Path(input_path), case_name))
54
+ output_path = self.root / case_name / "output.xlsx"
55
+ value = self.output_values[len(self.calls) - 1]
56
+ _workbook(output_path, value)
57
+ return ExecutionResult(True, output_path, "", "", "", False, 0)
58
+
59
+ def remove_case(self, case_name: str) -> None:
60
+ shutil.rmtree(self.root / case_name, ignore_errors=True)
61
+
62
+ def close(self) -> None:
63
+ shutil.rmtree(self.root, ignore_errors=True)
64
+ self.closed = True
65
+
66
+
67
+ class TimedOutExecutor(FakeExecutor):
68
+ def run(self, code: str, input_path: str | Path, *, case_name: str) -> ExecutionResult:
69
+ self.calls.append((code, Path(input_path), case_name))
70
+ return ExecutionResult(False, None, "", "", "timeout after 120s", True, -9)
71
+
72
+
73
+ def _data_root(tmp_path: Path) -> Path:
74
+ root = tmp_path / "runtime"
75
+ _workbook(root / "spreadsheet/task-1/1_input.xlsx", 2)
76
+ _workbook(root / "spreadsheet/task-1/1_answer.xlsx", 4)
77
+ _workbook(root / "spreadsheet/task-1/2_input.xlsx", 3)
78
+ _workbook(root / "spreadsheet/task-1/2_answer.xlsx", 6)
79
+ return root
80
+
81
+
82
+ def test_reset_returns_self_contained_single_shot_prompt_without_hidden_paths(
83
+ tmp_path: Path,
84
+ ) -> None:
85
+ executor = FakeExecutor(tmp_path / "session")
86
+ core = SpreadsheetBenchCore(
87
+ _data_root(tmp_path),
88
+ task_lookup=lambda task_id: _task(),
89
+ executor_factory=lambda root: executor,
90
+ work_root=tmp_path,
91
+ )
92
+
93
+ observation = core.reset(7)
94
+
95
+ assert observation.task_id == 7
96
+ assert observation.goal == "Double the value in Data!B2."
97
+ assert observation.step_limit == 1
98
+ assert observation.case_count == 2
99
+ for marker in (
100
+ "# Instruction",
101
+ "Instruction type:",
102
+ "Expected answer position:",
103
+ "# Input spreadsheet preview",
104
+ "# Task",
105
+ "INPUT_PATH",
106
+ "OUTPUT_PATH",
107
+ ):
108
+ assert marker in observation.text
109
+ assert "answer.xlsx" not in observation.text
110
+ assert core.state().diagnostics == {}
111
+ core.close()
112
+
113
+
114
+ def test_one_script_runs_sequentially_on_all_cases_and_uses_hard_reward(
115
+ tmp_path: Path,
116
+ ) -> None:
117
+ executor = FakeExecutor(tmp_path / "session")
118
+ core = SpreadsheetBenchCore(
119
+ _data_root(tmp_path),
120
+ task_lookup=lambda task_id: _task(),
121
+ executor_factory=lambda root: executor,
122
+ work_root=tmp_path,
123
+ )
124
+ core.reset(7)
125
+
126
+ transition = core.step("```python\nprint('run')\n```")
127
+
128
+ assert [call[0] for call in executor.calls] == ["print('run')", "print('run')"]
129
+ assert [call[2] for call in executor.calls] == ["case-1", "case-2"]
130
+ assert transition.terminated is True
131
+ assert transition.reward == 0.0
132
+ assert transition.observation.success is False
133
+ assert transition.observation.progress == 0.5
134
+ assert "expected=" not in transition.observation.text
135
+ state = core.state()
136
+ assert state.progress == 0.5
137
+ assert state.diagnostics["fail_reason"].startswith("eval-mismatch")
138
+ assert "expected=" in state.diagnostics["verification"]
139
+ assert state.diagnostics["code"] == "print('run')"
140
+ with pytest.raises(RuntimeError, match="terminated"):
141
+ core.step("print('again')")
142
+ core.close()
143
+
144
+
145
+ def test_all_cases_must_pass_for_success(tmp_path: Path) -> None:
146
+ executor = FakeExecutor(tmp_path / "session", output_values=(4, 6))
147
+ core = SpreadsheetBenchCore(
148
+ _data_root(tmp_path),
149
+ task_lookup=lambda task_id: _task(),
150
+ executor_factory=lambda root: executor,
151
+ work_root=tmp_path,
152
+ )
153
+ core.reset(7)
154
+
155
+ transition = core.step("print('run')")
156
+
157
+ assert transition.reward == 1.0
158
+ assert transition.observation.success is True
159
+ assert transition.observation.progress == 1.0
160
+ assert core.state().diagnostics["fail_reason"] == ""
161
+ core.close()
162
+
163
+
164
+ def test_script_timeout_does_not_repeat_same_hung_code_on_remaining_cases(
165
+ tmp_path: Path,
166
+ ) -> None:
167
+ executor = TimedOutExecutor(tmp_path / "session")
168
+ core = SpreadsheetBenchCore(
169
+ _data_root(tmp_path),
170
+ task_lookup=lambda task_id: _task(),
171
+ executor_factory=lambda root: executor,
172
+ work_root=tmp_path,
173
+ )
174
+ core.reset(7)
175
+
176
+ transition = core.step("print('hang')")
177
+
178
+ assert [call[2] for call in executor.calls] == ["case-1"]
179
+ assert transition.reward == 0.0
180
+ assert transition.terminated is True
181
+ assert core.state().diagnostics["fail_reason"] == "exec-error: timeout after 120s"
182
+ core.close()
183
+
184
+
185
+ def test_missing_hidden_answer_is_an_infrastructure_failure(tmp_path: Path) -> None:
186
+ root = _data_root(tmp_path)
187
+ (root / "spreadsheet/task-1/2_answer.xlsx").unlink()
188
+ executor = FakeExecutor(tmp_path / "session", output_values=(4, 6))
189
+ core = SpreadsheetBenchCore(
190
+ root,
191
+ task_lookup=lambda task_id: _task(),
192
+ executor_factory=lambda path: executor,
193
+ work_root=tmp_path,
194
+ )
195
+
196
+ with pytest.raises(InfraError, match="hidden answer"):
197
+ core.reset(7)
198
+ core.close()
199
+
200
+
201
+ def test_close_is_idempotent_and_removes_session_tree(tmp_path: Path) -> None:
202
+ executor = FakeExecutor(tmp_path / "session")
203
+ core = SpreadsheetBenchCore(
204
+ _data_root(tmp_path),
205
+ task_lookup=lambda task_id: _task(),
206
+ executor_factory=lambda root: executor,
207
+ work_root=tmp_path,
208
+ )
209
+ core.reset(7)
210
+
211
+ core.close()
212
+ core.close()
213
+
214
+ assert executor.closed is True
215
+ assert not executor.root.exists()
216
+ assert core.state().closed is True
tests/test_executor.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded subprocess tests for generated SpreadsheetBench scripts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+ import subprocess
8
+ import time
9
+
10
+ import openpyxl
11
+
12
+ from spreadsheetbench_env.executor import ExecutorLimits, ScriptExecutor
13
+
14
+
15
+ def _input_workbook(path: Path) -> None:
16
+ workbook = openpyxl.Workbook()
17
+ workbook.active["A1"] = 4
18
+ workbook.save(path)
19
+ workbook.close()
20
+
21
+
22
+ def test_executor_injects_private_paths_and_scrubs_parent_credentials(
23
+ tmp_path: Path,
24
+ monkeypatch,
25
+ ) -> None:
26
+ source = tmp_path / "source.xlsx"
27
+ _input_workbook(source)
28
+ monkeypatch.setenv("SPREADSHEETBENCH_TEST_SECRET", "must-not-leak")
29
+ executor = ScriptExecutor(tmp_path / "session")
30
+ code = """
31
+ import os
32
+ import openpyxl
33
+ INPUT_PATH = '/tmp/attacker-input.xlsx'
34
+ OUTPUT_PATH = '/tmp/attacker-output.xlsx'
35
+ wb = openpyxl.load_workbook(INPUT_PATH)
36
+ wb.active['A2'] = os.environ.get('SPREADSHEETBENCH_TEST_SECRET', 'scrubbed')
37
+ wb.active['A3'] = os.environ.get('OPENBLAS_NUM_THREADS')
38
+ wb.save(OUTPUT_PATH)
39
+ """
40
+
41
+ result = executor.run(code, source, case_name="case-1")
42
+
43
+ assert result.ok is True
44
+ assert result.output_path is not None
45
+ assert result.output_path.parent == executor.root / "case-1"
46
+ output = openpyxl.load_workbook(result.output_path, data_only=True)
47
+ assert output.active["A1"].value == 4
48
+ assert output.active["A2"].value == "scrubbed"
49
+ assert output.active["A3"].value == "1"
50
+ output.close()
51
+ assert not Path("/tmp/attacker-output.xlsx").exists()
52
+ executor.close()
53
+ assert not executor.root.exists()
54
+
55
+
56
+ def test_executor_uses_a_distinct_directory_for_each_case(tmp_path: Path) -> None:
57
+ source = tmp_path / "source.xlsx"
58
+ _input_workbook(source)
59
+ executor = ScriptExecutor(tmp_path / "session")
60
+ code = "import shutil\nshutil.copyfile(INPUT_PATH, OUTPUT_PATH)\n"
61
+
62
+ first = executor.run(code, source, case_name="case-1")
63
+ second = executor.run(code, source, case_name="case-2")
64
+
65
+ assert first.ok and second.ok
66
+ assert first.output_path != second.output_path
67
+ assert first.output_path is not None and second.output_path is not None
68
+ assert first.output_path.parent != second.output_path.parent
69
+ executor.close()
70
+
71
+
72
+ def test_executor_does_not_use_preexec_fn_in_threaded_server(
73
+ tmp_path: Path,
74
+ monkeypatch,
75
+ ) -> None:
76
+ source = tmp_path / "source.xlsx"
77
+ _input_workbook(source)
78
+ executor = ScriptExecutor(tmp_path / "session")
79
+ real_popen = subprocess.Popen
80
+ received_preexec: list[object] = []
81
+
82
+ def recording_popen(*args, **kwargs):
83
+ received_preexec.append(kwargs.get("preexec_fn"))
84
+ return real_popen(*args, **kwargs)
85
+
86
+ monkeypatch.setattr(subprocess, "Popen", recording_popen)
87
+
88
+ result = executor.run(
89
+ "import shutil\nshutil.copyfile(INPUT_PATH, OUTPUT_PATH)\n",
90
+ source,
91
+ case_name="no-preexec",
92
+ )
93
+
94
+ assert result.ok is True
95
+ assert received_preexec == [None]
96
+ executor.close()
97
+
98
+
99
+ def test_timeout_kills_the_generated_process_group(tmp_path: Path) -> None:
100
+ source = tmp_path / "source.xlsx"
101
+ _input_workbook(source)
102
+ executor = ScriptExecutor(
103
+ tmp_path / "session",
104
+ limits=ExecutorLimits(timeout_s=0.5, cpu_seconds=5),
105
+ )
106
+ code = """
107
+ import subprocess
108
+ import sys
109
+ import time
110
+ child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])
111
+ print(child.pid, flush=True)
112
+ time.sleep(60)
113
+ """
114
+
115
+ result = executor.run(code, source, case_name="timeout")
116
+
117
+ assert result.ok is False
118
+ assert result.timed_out is True
119
+ assert "timeout" in result.error.lower()
120
+ child_pid = int(result.stdout.strip().splitlines()[0])
121
+ deadline = time.monotonic() + 3
122
+ while time.monotonic() < deadline:
123
+ try:
124
+ os.kill(child_pid, 0)
125
+ except ProcessLookupError:
126
+ break
127
+ time.sleep(0.05)
128
+ else:
129
+ raise AssertionError(f"generated child process {child_pid} survived timeout")
130
+ executor.close()
131
+
132
+
133
+ def test_timeout_does_not_wait_for_detached_child_output_pipes(tmp_path: Path) -> None:
134
+ source = tmp_path / "source.xlsx"
135
+ _input_workbook(source)
136
+ executor = ScriptExecutor(
137
+ tmp_path / "session",
138
+ limits=ExecutorLimits(timeout_s=0.2, cpu_seconds=5),
139
+ )
140
+ code = """
141
+ import subprocess
142
+ import sys
143
+ import time
144
+ child = subprocess.Popen(
145
+ [sys.executable, '-c', 'import time; time.sleep(10)'],
146
+ start_new_session=True,
147
+ )
148
+ print(child.pid, flush=True)
149
+ time.sleep(10)
150
+ """
151
+
152
+ started = time.monotonic()
153
+ result = executor.run(code, source, case_name="detached-child")
154
+ elapsed = time.monotonic() - started
155
+
156
+ assert result.ok is False
157
+ assert result.timed_out is True
158
+ assert elapsed < 2.0
159
+ child_pid = int(result.stdout.strip().splitlines()[0])
160
+ try:
161
+ os.kill(child_pid, 0)
162
+ except ProcessLookupError:
163
+ pass
164
+ else:
165
+ os.kill(child_pid, 9)
166
+ executor.close()
167
+
168
+
169
+ def test_executor_rejects_unsafe_case_names(tmp_path: Path) -> None:
170
+ source = tmp_path / "source.xlsx"
171
+ _input_workbook(source)
172
+ executor = ScriptExecutor(tmp_path / "session")
173
+
174
+ try:
175
+ executor.run("", source, case_name="../escape")
176
+ except ValueError as error:
177
+ assert "case name" in str(error)
178
+ else:
179
+ raise AssertionError("unsafe case name was accepted")
180
+ finally:
181
+ executor.close()
182
+
183
+
184
+ def test_concurrent_executors_lease_distinct_runner_uids_and_release_them(
185
+ tmp_path: Path,
186
+ ) -> None:
187
+ limits = ExecutorLimits(run_uid_base=20_000, run_gid=65_534)
188
+ first = ScriptExecutor(tmp_path / "first", limits=limits)
189
+ second = ScriptExecutor(tmp_path / "second", limits=limits)
190
+
191
+ assert first.leased_uid == 20_000
192
+ assert second.leased_uid == 20_001
193
+
194
+ first.close()
195
+ replacement = ScriptExecutor(tmp_path / "replacement", limits=limits)
196
+ assert replacement.leased_uid == 20_000
197
+
198
+ second.close()
199
+ replacement.close()
tests/test_grader.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Framework-neutral SpreadsheetBench grader tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ from pathlib import Path
7
+
8
+ import openpyxl
9
+ import pytest
10
+
11
+ from spreadsheetbench_env.grader import InfraError, compare_workbooks, verification_report
12
+
13
+
14
+ def _workbook(path: Path, value: object, *, sheet: str = "Data") -> None:
15
+ workbook = openpyxl.Workbook()
16
+ worksheet = workbook.active
17
+ worksheet.title = sheet
18
+ worksheet["B2"] = value
19
+ workbook.save(path)
20
+ workbook.close()
21
+
22
+
23
+ def test_compare_workbooks_preserves_official_value_semantics(tmp_path: Path) -> None:
24
+ answer = tmp_path / "answer.xlsx"
25
+ output = tmp_path / "output.xlsx"
26
+ _workbook(answer, 5)
27
+ _workbook(output, "5.004")
28
+
29
+ passed, reason = compare_workbooks(answer, output, "Data!B2")
30
+
31
+ assert passed is True
32
+ assert reason == ""
33
+
34
+
35
+ def test_compare_workbooks_resolves_sheet_names_case_insensitively(
36
+ tmp_path: Path,
37
+ ) -> None:
38
+ answer = tmp_path / "answer.xlsx"
39
+ output = tmp_path / "output.xlsx"
40
+ _workbook(answer, 5, sheet="Step1")
41
+ _workbook(output, 5, sheet="Step1")
42
+
43
+ assert compare_workbooks(answer, output, "step1!B2") == (True, "")
44
+
45
+
46
+ def test_compare_workbooks_reports_first_mismatch_without_hiding_expected_value(tmp_path: Path) -> None:
47
+ answer = tmp_path / "answer.xlsx"
48
+ output = tmp_path / "output.xlsx"
49
+ _workbook(answer, datetime.datetime(2026, 8, 29))
50
+ _workbook(output, datetime.datetime(2026, 8, 28))
51
+
52
+ passed, reason = compare_workbooks(answer, output, "Data!B2")
53
+
54
+ assert passed is False
55
+ assert reason.startswith("value@Data!B2:")
56
+ assert "expected=" in reason and "got=" in reason
57
+
58
+
59
+ def test_broken_ground_truth_is_an_infrastructure_error(tmp_path: Path) -> None:
60
+ answer = tmp_path / "answer.xlsx"
61
+ output = tmp_path / "output.xlsx"
62
+ answer.write_text("not an xlsx", encoding="utf-8")
63
+ _workbook(output, 5)
64
+
65
+ with pytest.raises(InfraError, match="ground-truth"):
66
+ compare_workbooks(answer, output, "Data!B2")
67
+
68
+
69
+ def test_unreadable_agent_output_is_a_normal_failed_submission(tmp_path: Path) -> None:
70
+ answer = tmp_path / "answer.xlsx"
71
+ output = tmp_path / "output.xlsx"
72
+ _workbook(answer, 5)
73
+ output.write_text("not an xlsx", encoding="utf-8")
74
+
75
+ assert compare_workbooks(answer, output, "Data!B2") == (
76
+ False,
77
+ "agent output is not a readable workbook",
78
+ )
79
+
80
+
81
+ def test_verification_report_is_bounded_and_contains_cell_evidence(tmp_path: Path) -> None:
82
+ answer = tmp_path / "answer.xlsx"
83
+ output = tmp_path / "output.xlsx"
84
+ _workbook(answer, 5)
85
+ _workbook(output, 4)
86
+
87
+ report = verification_report(output, answer, "Data!B2", max_chars=200)
88
+
89
+ assert "Data!B2" in report
90
+ assert "expected=5" in report
91
+ assert len(report) <= 200
tests/test_models.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import pytest
4
+ from pydantic import ValidationError
5
+
6
+ from spreadsheetbench_env.models import (
7
+ SpreadsheetBenchAction,
8
+ SpreadsheetBenchSubmitScript,
9
+ native_tool_action,
10
+ native_tool_specs,
11
+ )
12
+
13
+
14
+ def test_native_tool_spec_is_generated_from_model_facing_action() -> None:
15
+ specs = native_tool_specs()
16
+
17
+ assert specs == (
18
+ {
19
+ "name": "submit_script",
20
+ "description": "Submit one complete Python script for SpreadsheetBench.",
21
+ "input_schema": SpreadsheetBenchSubmitScript.model_json_schema(),
22
+ },
23
+ )
24
+ schema = specs[0]["input_schema"]
25
+ assert schema["additionalProperties"] is False
26
+ assert set(schema["properties"]) == {"code"}
27
+ assert "metadata" not in schema["properties"]
28
+ assert "oneOf" not in schema
29
+ assert "discriminator" not in schema
30
+
31
+
32
+ def test_native_tool_action_validates_arguments_and_builds_wire_action() -> None:
33
+ action = native_tool_action("submit_script", {"code": "print('run')"})
34
+
35
+ assert isinstance(action, SpreadsheetBenchAction)
36
+ assert action.model_dump() == {"code": "print('run')", "metadata": {}}
37
+
38
+ with pytest.raises(ValidationError):
39
+ native_tool_action(
40
+ "submit_script",
41
+ {"code": "print('run')", "metadata": {"retry": 1}},
42
+ )
43
+
44
+
45
+ def test_action_accepts_native_envelope_without_changing_internal_shape() -> None:
46
+ action = SpreadsheetBenchAction.model_validate(
47
+ {
48
+ "name": "submit_script",
49
+ "arguments": {"code": "print('run')"},
50
+ }
51
+ )
52
+
53
+ assert action.model_dump() == {"code": "print('run')", "metadata": {}}
54
+
55
+ with pytest.raises(ValidationError, match="native tool envelope"):
56
+ SpreadsheetBenchAction.model_validate(
57
+ {
58
+ "name": "submit_script",
59
+ "arguments": {"code": "print('run')"},
60
+ "tool": "submit_script",
61
+ }
62
+ )
63
+
64
+
65
+ def test_native_tool_action_rejects_unknown_tool() -> None:
66
+ with pytest.raises(ValueError, match="unknown SpreadsheetBench native tool"):
67
+ native_tool_action("act", {"code": "print('run')"})
tests/test_openenv_app.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenEnv app and real WebSocket lifecycle tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from dataclasses import replace
7
+
8
+ from fastapi.testclient import TestClient
9
+ from starlette.websockets import WebSocketDisconnect
10
+
11
+ from spreadsheetbench_env.core import CoreObservation, CoreState, CoreStep
12
+ from spreadsheetbench_env.server.app import (
13
+ DisconnectedWebSocketMiddleware,
14
+ create_spreadsheetbench_app,
15
+ )
16
+ from spreadsheetbench_env.server.environment import SpreadsheetBenchEnvironment
17
+
18
+
19
+ class RecordingCore:
20
+ instances: list["RecordingCore"] = []
21
+
22
+ def __init__(self) -> None:
23
+ self.reset_calls: list[int] = []
24
+ self.step_calls: list[str] = []
25
+ self.close_calls = 0
26
+ self._state = CoreState(
27
+ task_id=None,
28
+ goal=None,
29
+ reward=0.0,
30
+ success=False,
31
+ progress=0.0,
32
+ terminated=False,
33
+ step_count=0,
34
+ step_limit=1,
35
+ diagnostics={},
36
+ closed=False,
37
+ )
38
+ self.instances.append(self)
39
+
40
+ def reset(self, task_id: int) -> CoreObservation:
41
+ self.reset_calls.append(task_id)
42
+ self._state = replace(self._state, task_id=task_id, goal="Goal")
43
+ return CoreObservation(
44
+ task_id=task_id,
45
+ text="Prompt",
46
+ goal="Goal",
47
+ task_type="Cell-Level Manipulation",
48
+ case_count=1,
49
+ answer_position="Data!A1",
50
+ success=False,
51
+ progress=0.0,
52
+ )
53
+
54
+ def step(self, code: str) -> CoreStep:
55
+ self.step_calls.append(code)
56
+ self._state = replace(
57
+ self._state,
58
+ reward=1.0,
59
+ success=True,
60
+ progress=1.0,
61
+ terminated=True,
62
+ step_count=1,
63
+ diagnostics={"verification": "private"},
64
+ )
65
+ return CoreStep(
66
+ observation=CoreObservation(
67
+ task_id=self._state.task_id if self._state.task_id is not None else 7,
68
+ text="PASS",
69
+ goal="Goal",
70
+ task_type="Cell-Level Manipulation",
71
+ case_count=1,
72
+ answer_position="Data!A1",
73
+ success=True,
74
+ progress=1.0,
75
+ ),
76
+ reward=1.0,
77
+ terminated=True,
78
+ )
79
+
80
+ def state(self) -> CoreState:
81
+ return self._state
82
+
83
+ def close(self) -> None:
84
+ if not self._state.closed:
85
+ self.close_calls += 1
86
+ self._state = replace(self._state, closed=True)
87
+
88
+
89
+ class RecordingEnvironment(SpreadsheetBenchEnvironment):
90
+ def __init__(self) -> None:
91
+ super().__init__(core_factory=RecordingCore, default_task_id=7)
92
+
93
+
94
+ def test_disconnected_websocket_middleware_swallows_disconnect() -> None:
95
+ async def disconnected_app(scope, receive, send) -> None:
96
+ raise WebSocketDisconnect(code=1006)
97
+
98
+ middleware = DisconnectedWebSocketMiddleware(disconnected_app)
99
+ asyncio.run(middleware({"type": "websocket"}, None, None))
100
+
101
+
102
+ def test_disconnected_websocket_middleware_swallows_send_after_close() -> None:
103
+ async def closed_app(scope, receive, send) -> None:
104
+ raise RuntimeError('Cannot call "send" once a close message has been sent.')
105
+
106
+ middleware = DisconnectedWebSocketMiddleware(closed_app)
107
+ asyncio.run(middleware({"type": "websocket"}, None, None))
108
+
109
+
110
+ def test_disconnected_websocket_middleware_preserves_other_errors() -> None:
111
+ async def broken_app(scope, receive, send) -> None:
112
+ raise RuntimeError("real server failure")
113
+
114
+ middleware = DisconnectedWebSocketMiddleware(broken_app)
115
+ try:
116
+ asyncio.run(middleware({"type": "websocket"}, None, None))
117
+ except RuntimeError as error:
118
+ assert str(error) == "real server failure"
119
+ else:
120
+ raise AssertionError("unrelated WebSocket error was suppressed")
121
+
122
+
123
+ def test_app_exposes_self_describing_routes_with_explicit_capacity(
124
+ monkeypatch,
125
+ ) -> None:
126
+ monkeypatch.setenv("ENABLE_WEB_INTERFACE", "true")
127
+ app = create_spreadsheetbench_app(
128
+ max_concurrent_envs=1,
129
+ environment_factory=RecordingEnvironment,
130
+ )
131
+ paths = {route.path for route in app.routes}
132
+ assert {"/health", "/metadata", "/schema", "/tools", "/ws", "/web/reset"} <= paths
133
+
134
+ with TestClient(app) as client:
135
+ metadata = client.get("/metadata")
136
+ schema = client.get("/schema")
137
+ web_reset = client.post("/web/reset")
138
+ assert metadata.status_code == 200
139
+ assert metadata.json()["name"] == "SpreadsheetBench"
140
+ assert schema.status_code == 200
141
+ assert schema.json()["action"]["properties"]["code"]["minLength"] == 1
142
+ assert web_reset.status_code == 200
143
+ assert web_reset.json()["observation"]["task_id"] == 7
144
+
145
+ assert SpreadsheetBenchEnvironment.SUPPORTS_CONCURRENT_SESSIONS is True
146
+ create_spreadsheetbench_app(max_concurrent_envs=24)
147
+
148
+
149
+ def test_websocket_owns_one_core_and_disconnect_closes_it(monkeypatch) -> None:
150
+ monkeypatch.setenv("ENABLE_WEB_INTERFACE", "false")
151
+ RecordingCore.instances.clear()
152
+ app = create_spreadsheetbench_app(
153
+ max_concurrent_envs=1,
154
+ environment_factory=RecordingEnvironment,
155
+ )
156
+
157
+ with TestClient(app) as client:
158
+ with client.websocket_connect("/ws") as websocket:
159
+ websocket.send_json(
160
+ {"type": "reset", "data": {"task_id": 7, "episode_id": "ep-1"}}
161
+ )
162
+ initial = websocket.receive_json()
163
+ websocket.send_json({"type": "step", "data": {"code": "print(1)"}})
164
+ stepped = websocket.receive_json()
165
+ websocket.send_json({"type": "state"})
166
+ state = websocket.receive_json()
167
+
168
+ assert initial["type"] == "observation"
169
+ assert initial["data"]["observation"]["task_id"] == 7
170
+ assert stepped["data"]["done"] is True
171
+ assert state["data"]["episode_id"] == "ep-1"
172
+ assert state["data"]["diagnostics"] == {"verification": "private"}
173
+
174
+ assert len(RecordingCore.instances) == 1
175
+ assert RecordingCore.instances[0].reset_calls == [7]
176
+ assert RecordingCore.instances[0].step_calls == ["print(1)"]
177
+ assert RecordingCore.instances[0].close_calls == 1
tests/test_openenv_client.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed-client contract for SpreadsheetBench."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+ from openenv.core.client_types import StepResult
7
+
8
+ from spreadsheetbench_env.client import SpreadsheetBenchClient
9
+ from spreadsheetbench_env.models import (
10
+ SpreadsheetBenchAction,
11
+ SpreadsheetBenchObservation,
12
+ SpreadsheetBenchState,
13
+ )
14
+
15
+
16
+ def test_client_serializes_code_and_derives_done_from_terminal_flags() -> None:
17
+ client = SpreadsheetBenchClient(base_url="http://localhost:8000")
18
+ action = SpreadsheetBenchAction(code="print('run')")
19
+ assert client._step_payload(action) == {"metadata": {}, "code": "print('run')"}
20
+
21
+ result = client._parse_result(
22
+ {
23
+ "observation": {
24
+ "metadata": {},
25
+ "task_id": 7,
26
+ "text": "PASS",
27
+ "goal": "Goal",
28
+ "task_type": "Cell-Level Manipulation",
29
+ "case_count": 3,
30
+ "answer_position": "Data!B2",
31
+ "success": True,
32
+ "progress": 1.0,
33
+ "terminated": True,
34
+ "truncated": False,
35
+ "step_limit": 1,
36
+ },
37
+ "reward": 1.0,
38
+ "done": False,
39
+ }
40
+ )
41
+ assert result == StepResult(
42
+ observation=SpreadsheetBenchObservation(
43
+ task_id=7,
44
+ text="PASS",
45
+ goal="Goal",
46
+ task_type="Cell-Level Manipulation",
47
+ case_count=3,
48
+ answer_position="Data!B2",
49
+ success=True,
50
+ progress=1.0,
51
+ terminated=True,
52
+ truncated=False,
53
+ done=True,
54
+ reward=1.0,
55
+ step_limit=1,
56
+ ),
57
+ reward=1.0,
58
+ done=True,
59
+ metadata={},
60
+ )
61
+
62
+ assert client._parse_state(
63
+ {
64
+ "episode_id": "ep-1",
65
+ "step_count": 1,
66
+ "task_id": 7,
67
+ "goal": "Goal",
68
+ "reward": 1.0,
69
+ "success": True,
70
+ "progress": 1.0,
71
+ "terminated": True,
72
+ "truncated": False,
73
+ "step_limit": 1,
74
+ "diagnostics": {"verification": "private"},
75
+ "closed": False,
76
+ }
77
+ ) == SpreadsheetBenchState(
78
+ episode_id="ep-1",
79
+ step_count=1,
80
+ task_id=7,
81
+ goal="Goal",
82
+ reward=1.0,
83
+ success=True,
84
+ progress=1.0,
85
+ terminated=True,
86
+ truncated=False,
87
+ step_limit=1,
88
+ diagnostics={"verification": "private"},
89
+ closed=False,
90
+ )
91
+
92
+
93
+ def test_bearer_authentication_requires_transport_security() -> None:
94
+ with pytest.raises(ValueError, match="HTTPS or WSS"):
95
+ SpreadsheetBenchClient(
96
+ base_url="http://private-space.example",
97
+ bearer_token="secret",
98
+ )
99
+ SpreadsheetBenchClient(
100
+ base_url="https://private-space.example",
101
+ bearer_token="secret",
102
+ )
tests/test_openenv_environment.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct typed OpenEnv boundary tests for SpreadsheetBench."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+
7
+ from spreadsheetbench_env.core import CoreObservation, CoreState, CoreStep
8
+ from spreadsheetbench_env.models import (
9
+ SpreadsheetBenchAction,
10
+ SpreadsheetBenchObservation,
11
+ SpreadsheetBenchState,
12
+ )
13
+ from spreadsheetbench_env.server.environment import SpreadsheetBenchEnvironment
14
+
15
+
16
+ class FakeCore:
17
+ def __init__(self) -> None:
18
+ self.reset_calls: list[int] = []
19
+ self.step_calls: list[str] = []
20
+ self.close_calls = 0
21
+ self._state = CoreState(
22
+ task_id=None,
23
+ goal=None,
24
+ reward=0.0,
25
+ success=False,
26
+ progress=0.0,
27
+ terminated=False,
28
+ step_count=0,
29
+ step_limit=1,
30
+ diagnostics={},
31
+ closed=False,
32
+ )
33
+
34
+ def reset(self, task_id: int) -> CoreObservation:
35
+ self.reset_calls.append(task_id)
36
+ self._state = replace(
37
+ self._state,
38
+ task_id=task_id,
39
+ goal="Double Data!B2.",
40
+ )
41
+ return CoreObservation(
42
+ task_id=task_id,
43
+ text="# Instruction\nDouble Data!B2.",
44
+ goal="Double Data!B2.",
45
+ task_type="Cell-Level Manipulation",
46
+ case_count=3,
47
+ answer_position="Data!B2",
48
+ success=False,
49
+ progress=0.0,
50
+ )
51
+
52
+ def step(self, code: str) -> CoreStep:
53
+ self.step_calls.append(code)
54
+ observation = CoreObservation(
55
+ task_id=7,
56
+ text="Case 1: grade PASS",
57
+ goal="Double Data!B2.",
58
+ task_type="Cell-Level Manipulation",
59
+ case_count=3,
60
+ answer_position="Data!B2",
61
+ success=True,
62
+ progress=1.0,
63
+ )
64
+ self._state = replace(
65
+ self._state,
66
+ reward=1.0,
67
+ success=True,
68
+ progress=1.0,
69
+ terminated=True,
70
+ step_count=1,
71
+ diagnostics={"verification": "private"},
72
+ )
73
+ return CoreStep(observation=observation, reward=1.0, terminated=True)
74
+
75
+ def state(self) -> CoreState:
76
+ return self._state
77
+
78
+ def close(self) -> None:
79
+ self.close_calls += 1
80
+ self._state = replace(self._state, closed=True)
81
+
82
+
83
+ def test_environment_is_lazy_and_delegates_one_typed_episode() -> None:
84
+ core = FakeCore()
85
+ constructed: list[FakeCore] = []
86
+
87
+ def factory() -> FakeCore:
88
+ constructed.append(core)
89
+ return core
90
+
91
+ environment = SpreadsheetBenchEnvironment(core_factory=factory)
92
+ metadata = environment.get_metadata()
93
+ assert metadata.name == "SpreadsheetBench"
94
+ assert constructed == []
95
+
96
+ initial = environment.reset(task_id=7, episode_id="episode-1")
97
+ assert constructed == [core]
98
+ assert core.reset_calls == [7]
99
+ assert initial == SpreadsheetBenchObservation(
100
+ task_id=7,
101
+ text="# Instruction\nDouble Data!B2.",
102
+ goal="Double Data!B2.",
103
+ task_type="Cell-Level Manipulation",
104
+ case_count=3,
105
+ answer_position="Data!B2",
106
+ success=False,
107
+ progress=0.0,
108
+ terminated=False,
109
+ truncated=False,
110
+ done=False,
111
+ reward=0.0,
112
+ step_limit=1,
113
+ )
114
+
115
+ result = environment.step(SpreadsheetBenchAction(code="print('run')"))
116
+ assert core.step_calls == ["print('run')"]
117
+ assert result.success is True
118
+ assert result.terminated is True
119
+ assert result.truncated is False
120
+ assert result.done is True
121
+ assert result.reward == 1.0
122
+ assert environment.state == SpreadsheetBenchState(
123
+ episode_id="episode-1",
124
+ step_count=1,
125
+ task_id=7,
126
+ goal="Double Data!B2.",
127
+ reward=1.0,
128
+ success=True,
129
+ progress=1.0,
130
+ terminated=True,
131
+ truncated=False,
132
+ step_limit=1,
133
+ diagnostics={"verification": "private"},
134
+ closed=False,
135
+ )
136
+
137
+ environment.close()
138
+ environment.close()
139
+ assert core.close_calls == 1
140
+
141
+
142
+ def test_task_provider_exposes_canonical_split_counts_and_hashes() -> None:
143
+ environment = SpreadsheetBenchEnvironment(core_factory=lambda: FakeCore())
144
+
145
+ splits = {item["name"]: item for item in environment.list_splits()}
146
+ assert splits["development"]["num_tasks"] == 700
147
+ assert splits["test"]["num_tasks"] == 201
148
+ assert len(splits["development"]["sha256"]) == 64
149
+
150
+ first = environment.get_task("development", 0)
151
+ assert first["id"] == 0
152
+ assert first["source_id"] == "13-1"
153
+ assert first["instruction"]
154
+ assert first["split"] == "development"
155
+ assert len(first["catalog_sha256"]) == 64
156
+ assert environment.num_tasks("test") == 201
157
+ assert len(environment.get_task_range("test", 0, 2)) == 2
158
+ environment.close()
tests/test_package_boundary.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent-package and deployment-boundary tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ import json
7
+ import subprocess
8
+ import sys
9
+
10
+ import tomllib
11
+
12
+ from spreadsheetbench_env.models import (
13
+ SpreadsheetBenchAction,
14
+ SpreadsheetBenchObservation,
15
+ SpreadsheetBenchState,
16
+ )
17
+
18
+
19
+ PACKAGE_ROOT = Path(__file__).resolve().parents[1]
20
+
21
+
22
+ def test_framework_neutral_imports_do_not_load_agent_or_transport_frameworks() -> None:
23
+ probe = """
24
+ import sys
25
+ import spreadsheetbench_env
26
+ import spreadsheetbench_env.catalog
27
+ import spreadsheetbench_env.core
28
+ import spreadsheetbench_env.executor
29
+ import spreadsheetbench_env.grader
30
+ import spreadsheetbench_env.interface
31
+ for forbidden in ("genmem", "skillopt", "openenv"):
32
+ loaded = [name for name in sys.modules if name == forbidden or name.startswith(forbidden + ".")]
33
+ assert not loaded, f"framework-neutral imports loaded {forbidden}: {loaded}"
34
+ """
35
+ subprocess.run([sys.executable, "-c", probe], check=True)
36
+
37
+
38
+ def test_pyproject_is_standalone_and_pins_the_transport_boundary() -> None:
39
+ project = tomllib.loads((PACKAGE_ROOT / "pyproject.toml").read_text(encoding="utf-8"))
40
+ assert project["project"]["name"] == "spreadsheetbench-env"
41
+ assert project["project"]["dependencies"] == ["openpyxl>=3.1,<4"]
42
+ assert project["project"]["optional-dependencies"]["openenv"] == ["openenv==0.4.1"]
43
+ assert "genmem" not in str(project).lower()
44
+ assert "skillopt" not in str(project).lower()
45
+
46
+
47
+ def test_deployment_starts_safe_before_capacity_is_measured() -> None:
48
+ dockerfile = (PACKAGE_ROOT / "Dockerfile").read_text(encoding="utf-8")
49
+ readme = (PACKAGE_ROOT / "README.md").read_text(encoding="utf-8")
50
+ assert readme.startswith("---\ntitle: SpreadsheetBench OpenEnv\nsdk: docker\napp_port: 8000\n")
51
+ assert "MAX_CONCURRENT_ENVS=1" in dockerfile
52
+ assert "SPREADSHEETBENCH_RUNNER_UID_BASE=20000" in dockerfile
53
+ assert "SPREADSHEETBENCH_DATA=/opt/spreadsheetbench" in dockerfile
54
+ assert "USER root" in dockerfile
55
+ assert "chmod 700 /opt/spreadsheetbench" in dockerfile
56
+ assert "ENABLE_WEB_INTERFACE=true" in dockerfile
57
+
58
+
59
+ def test_openenv_manifest_points_to_the_canonical_server() -> None:
60
+ manifest = (PACKAGE_ROOT / "openenv.yaml").read_text(encoding="utf-8")
61
+ assert "name: spreadsheetbench_env" in manifest
62
+ assert "app: spreadsheetbench_env.server.app:app" in manifest
63
+
64
+
65
+ def test_packaged_json_schemas_match_the_typed_models_exactly() -> None:
66
+ schema_root = PACKAGE_ROOT / "src/spreadsheetbench_env/assets/schemas"
67
+ expected = {
68
+ "action.schema.json": SpreadsheetBenchAction.model_json_schema(),
69
+ "observation.schema.json": SpreadsheetBenchObservation.model_json_schema(),
70
+ "state.schema.json": SpreadsheetBenchState.model_json_schema(),
71
+ }
72
+ for filename, schema in expected.items():
73
+ actual = json.loads((schema_root / filename).read_text(encoding="utf-8"))
74
+ assert actual == schema
tests/test_runtime_assets.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical runtime workbook archive tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ import subprocess
9
+
10
+
11
+ PACKAGE_ROOT = Path(__file__).resolve().parents[1]
12
+ TASK_ROOT = PACKAGE_ROOT / "src/spreadsheetbench_env/assets/tasks"
13
+ ARCHIVE = PACKAGE_ROOT / "runtime-data/spreadsheetbench-runtime-v0.1.tar.zst"
14
+ SIDECAR = ARCHIVE.with_suffix(ARCHIVE.suffix + ".sha256")
15
+
16
+
17
+ def _referenced_paths() -> set[str]:
18
+ paths: set[str] = set()
19
+ for filename in ("dev.json", "test.json"):
20
+ payload = json.loads((TASK_ROOT / filename).read_text(encoding="utf-8"))
21
+ for task in payload["tasks"]:
22
+ for case in task["cases"]:
23
+ assert case["input"] not in paths
24
+ assert case["answer"] not in paths
25
+ paths.add(case["input"])
26
+ paths.add(case["answer"])
27
+ return paths
28
+
29
+
30
+ def test_runtime_archive_contains_exactly_the_canonical_referenced_workbooks() -> None:
31
+ expected = _referenced_paths()
32
+ assert ARCHIVE.is_file()
33
+ assert SIDECAR.is_file()
34
+ listed = subprocess.run(
35
+ ["tar", "-tf", str(ARCHIVE)],
36
+ check=True,
37
+ capture_output=True,
38
+ text=True,
39
+ ).stdout.splitlines()
40
+ members = {name.removeprefix("./") for name in listed if not name.endswith("/")}
41
+ assert members == expected
42
+ assert "dataset.json" not in members
43
+ for excluded in ("189-9", "CF_25745", "55224"):
44
+ assert not any(path.startswith(f"spreadsheet/{excluded}/") for path in members)
45
+
46
+
47
+ def test_runtime_archive_sidecar_matches_exact_bytes() -> None:
48
+ actual = hashlib.sha256(ARCHIVE.read_bytes()).hexdigest()
49
+ fields = SIDECAR.read_text(encoding="utf-8").strip().split()
50
+ assert fields == [actual, ARCHIVE.name]