armnet-core 0.3.2__tar.gz → 0.3.4__tar.gz

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 (31) hide show
  1. {armnet_core-0.3.2 → armnet_core-0.3.4}/.gitignore +2 -0
  2. {armnet_core-0.3.2 → armnet_core-0.3.4}/PKG-INFO +1 -1
  3. {armnet_core-0.3.2 → armnet_core-0.3.4}/pyproject.toml +1 -1
  4. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/__init__.py +44 -2
  5. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/enums.py +4 -0
  6. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/env.py +4 -0
  7. armnet_core-0.3.4/src/armnet_core/evals.py +260 -0
  8. armnet_core-0.3.4/src/armnet_core/image_refs.py +154 -0
  9. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/models.py +525 -22
  10. armnet_core-0.3.4/tests/test_cell_device_config.py +414 -0
  11. armnet_core-0.3.4/tests/test_eval_policy.py +30 -0
  12. armnet_core-0.3.4/tests/test_image_refs.py +91 -0
  13. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_robot_cell_config.py +167 -2
  14. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_yam_cell_config.py +30 -3
  15. armnet_core-0.3.2/tests/test_cell_device_config.py +0 -138
  16. {armnet_core-0.3.2 → armnet_core-0.3.4}/LICENSE +0 -0
  17. {armnet_core-0.3.2 → armnet_core-0.3.4}/README.md +0 -0
  18. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/auth.py +0 -0
  19. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/environment.py +0 -0
  20. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/manual_reset.py +0 -0
  21. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/markers.py +0 -0
  22. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/scene_calibration.py +0 -0
  23. {armnet_core-0.3.2 → armnet_core-0.3.4}/src/armnet_core/volume_sync.py +0 -0
  24. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_job_ids.py +0 -0
  25. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_job_spec.py +0 -0
  26. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_manual_reset.py +0 -0
  27. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_manual_reset_size_guide.py +0 -0
  28. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_package_version.py +0 -0
  29. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_scene_calibration.py +0 -0
  30. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/test_volume_sync.py +0 -0
  31. {armnet_core-0.3.2 → armnet_core-0.3.4}/tests/yam_fixtures.py +0 -0
@@ -194,6 +194,8 @@ terraform.tfstate.backup
194
194
 
195
195
  # experimental
196
196
  experimental/*/images/*.png
197
+ # A checkout of github.com/villekuosmanen/vla-vlm-benchmarks
198
+ experimental/vla_vlm_benchmarks/
197
199
  *.p12
198
200
  build_log.txt
199
201
  outputs
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: armnet-core
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: Shared wire types for the armnet platform: Embodiment, Task, JobSpec, JobResult, Job, JobStatus.
5
5
  Project-URL: Homepage, https://armnet.dev
6
6
  Project-URL: Documentation, https://docs.armnet.dev/packages/core/
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
  name = "armnet-core"
7
7
  # 0.2.0 is a wire break: a cell reports the `environment` it is set up for in
8
8
  # place of a single `task`, so 0.1.x cannot read a cell-status response.
9
- version = "0.3.2"
9
+ version = "0.3.4"
10
10
  description = "Shared wire types for the armnet platform: Embodiment, Task, JobSpec, JobResult, Job, JobStatus."
11
11
  readme = "README.md"
12
12
  requires-python = ">=3.12,<3.13"
@@ -9,8 +9,8 @@ from importlib.metadata import PackageNotFoundError as _PackageNotFound
9
9
  from importlib.metadata import version as _package_version
10
10
 
11
11
  from armnet_core.auth import API_KEY_ENV, API_KEY_HEADER
12
- from armnet_core.enums import (DEFAULT_EMBODIMENT, DEFAULT_ENVIRONMENT,
13
- DEFAULT_TASK, Embodiment)
12
+ from armnet_core.enums import (CELL_ID_PATTERN, DEFAULT_EMBODIMENT,
13
+ DEFAULT_ENVIRONMENT, DEFAULT_TASK, Embodiment)
14
14
  from armnet_core.enums import Environment as EnvironmentName
15
15
  from armnet_core.enums import Task
16
16
  from armnet_core.environment import (CompletionStatus, Environment,
@@ -37,6 +37,14 @@ from armnet_core.manual_reset import (
37
37
  ShirtSize,
38
38
  sample_manual_reset_layout,
39
39
  )
40
+ from armnet_core.image_refs import (
41
+ ImageReferenceError,
42
+ canonical_customer_image,
43
+ customer_image_selector,
44
+ customer_registry_slug,
45
+ require_owned_customer_image,
46
+ validate_image_selector,
47
+ )
40
48
  from armnet_core.models import (BIMANUAL_YAM_EMBODIMENT, TELEOP_EVENT_NEXT_EPISODE,
41
49
  TELEOP_EVENT_RERECORD_EPISODE,
42
50
  TELEOP_EVENT_STOP_RECORDING, TELEOP_EVENTS,
@@ -51,13 +59,21 @@ from armnet_core.models import (BIMANUAL_YAM_EMBODIMENT, TELEOP_EVENT_NEXT_EPISO
51
59
  OffCurrentGateConfig,
52
60
  PercentileCurrentGateConfig, RailConfig,
53
61
  RailVariation, RegistryCredentials,
62
+ ArmKeepOutConfig, JointMapEntry,
63
+ KeepOutBoxConfig, KeepOutConfig, KeepOutPlaneConfig,
64
+ RailCalibrationPoint,
54
65
  RemoteExecutionError, RobotArmConfig,
55
66
  RobotCellConfig, SecretCreateRequest,
67
+ TopCameraWallsConfig, VelocityDamperConfig,
56
68
  SecretInfo, SecretList, TaskInfo, TaskList,
57
69
  TeleopAction, TeleopEvent, TerminalStatus,
58
70
  TrackingStallConfig, UniformCurrentGateConfig, VariationAxis,
59
71
  VolumeCredentials, WhoAmI, YamArmDriverConfig,
60
72
  canonical_job_id)
73
+ from armnet_core.evals import (ArmnetBaseline, EvalDataset, EvalDeclaration,
74
+ EvalPlanSlot, EvalPlanTrial, EvalPolicy,
75
+ EvalReport, EvalRolloutRecord, EvalTrialRecord,
76
+ pick_baseline, policy_type_key)
61
77
  from armnet_core.scene_calibration import (
62
78
  FULL_FRAME_VERTICES,
63
79
  MIN_NORMALIZED_POLYGON_AREA,
@@ -74,8 +90,20 @@ from armnet_core.scene_calibration import (
74
90
  __all__ = [
75
91
  "API_KEY_ENV",
76
92
  "API_KEY_HEADER",
93
+ "ArmnetBaseline",
94
+ "EvalDataset",
95
+ "EvalDeclaration",
96
+ "EvalPlanSlot",
97
+ "EvalPlanTrial",
98
+ "EvalPolicy",
99
+ "EvalReport",
100
+ "EvalRolloutRecord",
101
+ "EvalTrialRecord",
102
+ "pick_baseline",
103
+ "policy_type_key",
77
104
  "BIMANUAL_YAM_EMBODIMENT",
78
105
  "BOX_LENGTH_SCALES",
106
+ "CELL_ID_PATTERN",
79
107
  "DEFAULT_LAYOUT_ATTEMPTS",
80
108
  "DEFAULT_EMBODIMENT",
81
109
  "DEFAULT_ENVIRONMENT",
@@ -96,10 +124,14 @@ __all__ = [
96
124
  "EnvironmentNotFound",
97
125
  "FULL_FRAME_VERTICES",
98
126
  "InstrumentedCell",
127
+ "ImageReferenceError",
99
128
  "Reading",
100
129
  "TaskSpec",
101
130
  "available_environments",
102
131
  "canonical_job_id",
132
+ "canonical_customer_image",
133
+ "customer_image_selector",
134
+ "customer_registry_slug",
103
135
  "environment_for",
104
136
  "task_environment",
105
137
  "Job",
@@ -127,8 +159,17 @@ __all__ = [
127
159
  "RailVariation",
128
160
  "RegistryCredentials",
129
161
  "RemoteExecutionError",
162
+ "require_owned_customer_image",
163
+ "ArmKeepOutConfig",
164
+ "JointMapEntry",
165
+ "KeepOutBoxConfig",
166
+ "KeepOutConfig",
167
+ "KeepOutPlaneConfig",
168
+ "RailCalibrationPoint",
130
169
  "RobotArmConfig",
131
170
  "RobotCellConfig",
171
+ "TopCameraWallsConfig",
172
+ "VelocityDamperConfig",
132
173
  "SceneCalibration",
133
174
  "ShirtSize",
134
175
  "SecretCreateRequest",
@@ -165,6 +206,7 @@ __all__ = [
165
206
  "sample_scene_target",
166
207
  "sample_manual_reset_layout",
167
208
  "validate_normalized_polygon",
209
+ "validate_image_selector",
168
210
  ]
169
211
 
170
212
  # Read from installed metadata so the version lives in pyproject.toml only; a
@@ -30,6 +30,10 @@ Embodiment = str
30
30
  Environment = str
31
31
  Task = str
32
32
 
33
+ # A cell id is also a NATS subject token and a JetStream consumer name (a job
34
+ # can be routed to one cell), so it is limited to characters valid in both.
35
+ CELL_ID_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$"
36
+
33
37
  # Convenience defaults for local dev and SDK call sites, not an authoritative
34
38
  # list. Keep in sync with the seed rows in db/data_core/data_core.sql.
35
39
  DEFAULT_EMBODIMENT: Embodiment = "lerobot/so-101"
@@ -60,3 +60,7 @@ LEGACY_VOLUME_HOME = "REMOTEROBOT_VOLUME_HOME"
60
60
 
61
61
  # JSON-encoded mapping of injected secret env var names to values.
62
62
  SECRETS = "ARMNET_SECRETS"
63
+
64
+ # JSON-encoded `EvalDeclaration` of an eval job; unset for any other job. The
65
+ # runtime exposes it as `ctx.eval`.
66
+ EVAL = "ARMNET_EVAL"
@@ -0,0 +1,260 @@
1
+ """Eval jobs: what a job declares it evaluates, and the report its cell sends back.
2
+
3
+ A job submitted with an :class:`EvalDeclaration` (``JobSpec.eval``) is an eval
4
+ job. It evaluates one policy over a number of episodes (``single``), or ranks two
5
+ to four policies against each other over trials in which each runs once on the
6
+ same scene, in an order and under labels drawn for the trial (``ranked``).
7
+
8
+ While it runs, the cell records what it sees of each rollout: when it began and
9
+ ended, the operator's success or fail (or the cell's automated check), the
10
+ staging layout, and how the operator ranked each trial. The job's code adds what
11
+ only it knows (which policy each label was, where the rollout is in its
12
+ dataset, its own milestones and notes) through ``ctx.eval``. When the job ends
13
+ the cell sends both, as an :class:`EvalReport`, with the job's result.
14
+
15
+ Outcomes and rankings in the report are the cell's (``outcome``,
16
+ ``outcome_source``); the job's own view of an outcome is kept apart
17
+ (``claimed_outcome``) and is shown, never used to rate a policy.
18
+
19
+ A policy's checkpoint (``ref`` at ``revision``) is what connects its results
20
+ across eval jobs: every eval of the same checkpoint rates the same model. An
21
+ experiment groups models: the checkpoints of one approach, across robots and
22
+ tasks, rated as one. Make one in the Armnet console; a policy that names it
23
+ (``EvalPolicy.experiment``, its slug) puts its checkpoint in it, or link the
24
+ checkpoint from the console afterwards. An Armnet baseline
25
+ (:class:`ArmnetBaseline`) is one of Armnet's own checkpoints, versioned, in
26
+ Armnet's experiment for its version; a policy that names one
27
+ (``EvalPolicy.baseline``) runs that baseline's checkpoint, and its results are
28
+ the baseline's.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import re
34
+ from datetime import datetime
35
+ from typing import Any, Literal, Optional
36
+
37
+ from pydantic import BaseModel, ConfigDict, Field, model_serializer, model_validator
38
+
39
+ EVAL_REPORT_FORMAT = 1
40
+ MAX_EVAL_POLICIES = 4
41
+ MAX_EVAL_ROLLOUTS = 2000
42
+
43
+ POLICY_NAME_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$"
44
+ DATASET_REPO_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}/[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$"
45
+ UUID_PATTERN = r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
46
+ EXPERIMENT_SLUG_PATTERN = r"^[a-z0-9]+(-[a-z0-9]+)*$"
47
+ VOLUME_REF_PREFIX = "volume:"
48
+
49
+
50
+ class EvalPolicy(BaseModel):
51
+ """One policy an eval job evaluates, as its results are recorded."""
52
+
53
+ model_config = ConfigDict(extra="forbid")
54
+
55
+ name: str = Field(..., pattern=POLICY_NAME_PATTERN,
56
+ description="How the job and its results refer to the policy, e.g. 'baseline'.")
57
+ kind: str = Field(default="custom", pattern=r"^[a-z0-9_.-]{1,32}$",
58
+ description="How it is served, e.g. 'lerobot'.")
59
+ policy_type: Optional[str] = Field(default=None, min_length=1, max_length=64,
60
+ description="The model, as people call it, e.g. 'ACT'. It names the policy "
61
+ "in the results and is not checked.")
62
+ ref: Optional[str] = Field(default=None, max_length=300,
63
+ description="The checkpoint: a Hub repo, optionally with a subfolder "
64
+ "(org/repo/checkpoint-20000), or a path in your volume as "
65
+ "'volume:<path>'.")
66
+ revision: Optional[str] = Field(default=None, max_length=100, description="The Hub commit of ref.")
67
+ baseline: Optional[str] = Field(default=None, pattern=UUID_PATTERN,
68
+ description="An Armnet baseline's id: the policy is that baseline, and runs "
69
+ "its checkpoint.")
70
+ experiment: Optional[str] = Field(default=None, pattern=EXPERIMENT_SLUG_PATTERN, max_length=64,
71
+ description="The slug of one of your experiments: the policy's checkpoint "
72
+ "(on this job's embodiment and task) is put in it, so its "
73
+ "results count for the experiment. A checkpoint is in at most one "
74
+ "experiment.")
75
+ settings: dict[str, Any] = Field(default_factory=dict,
76
+ description="Inference settings worth showing with the results.")
77
+
78
+ @model_serializer(mode="wrap")
79
+ def _without_an_unset_experiment(self, handler: Any) -> dict[str, Any]:
80
+ # The orchestrator takes ``experiment`` off a job before a cell sees it; leaving the unset key out keeps a
81
+ # job readable by cells and jobs built with an armnet-core from before it (EvalPolicy forbids extra keys).
82
+ data = handler(self)
83
+ if self.experiment is None:
84
+ data.pop("experiment", None)
85
+ return data
86
+
87
+ @model_validator(mode="after")
88
+ def _experiment_needs_a_checkpoint(self) -> "EvalPolicy":
89
+ if self.experiment is not None:
90
+ if self.baseline is not None:
91
+ raise ValueError(f"policy {self.name!r} is an Armnet baseline, which is in Armnet's experiment "
92
+ "already; name an experiment only for your own checkpoints")
93
+ if self.ref is None:
94
+ raise ValueError(f"policy {self.name!r} names an experiment but no checkpoint (ref) to put in it")
95
+ return self
96
+
97
+
98
+ def policy_type_key(policy_type: str) -> str:
99
+ """A policy type as lookups compare it: 'π0.5', 'Pi0.5' and 'pi05' are the same."""
100
+ return re.sub(r"[^a-z0-9]", "", policy_type.lower().replace("π", "pi"))
101
+
102
+
103
+ def version_key(version: str) -> tuple[int, ...]:
104
+ return tuple(int(x) for x in version.split("."))
105
+
106
+
107
+ class ArmnetBaseline(BaseModel):
108
+ """One version of an Armnet baseline: Armnet's canonical checkpoint of a policy type, fine-tuned for (or run
109
+ zero-shot on) one embodiment and task. A better training pipeline makes a new version, with a new checkpoint;
110
+ old versions stay."""
111
+
112
+ model_config = ConfigDict(extra="ignore")
113
+
114
+ id: str
115
+ embodiment: str
116
+ task: str
117
+ policy_type: str
118
+ variant: Literal["fine-tuned", "zero-shot"] = "fine-tuned"
119
+ version: str = Field(..., pattern=r"^[0-9]+\.[0-9]+\.[0-9]+$")
120
+ runtime: str = Field(..., description="How a job serves it, e.g. 'lerobot', or 'external'.")
121
+ source: Literal["huggingface", "external"] = "huggingface"
122
+ ref: str = Field(..., description="Its Hub repo (org/repo, with an optional subfolder), or the external id.")
123
+ revision: Optional[str] = Field(default=None, description="Its Hub commit.")
124
+ notes: str = ""
125
+ created_at: Optional[datetime] = None
126
+
127
+ def policy(self, name: Optional[str] = None, *, settings: Optional[dict[str, Any]] = None) -> EvalPolicy:
128
+ """The baseline as an eval job's policy, named ``name`` (default: its policy type, e.g. 'pi05')."""
129
+ default = policy_type_key(self.policy_type) + ("-zero-shot" if self.variant == "zero-shot" else "")
130
+ kind = self.runtime if re.fullmatch(r"[a-z0-9_.-]{1,32}", self.runtime) else "custom"
131
+ return EvalPolicy(name=name or default, kind=kind, policy_type=self.policy_type, ref=self.ref,
132
+ revision=self.revision, baseline=self.id, settings=settings or {})
133
+
134
+
135
+ def pick_baseline(baselines: list[ArmnetBaseline], policy_type: str, *, variant: str = "fine-tuned",
136
+ version: Optional[str] = None, where: str = "") -> ArmnetBaseline:
137
+ """The baseline of ``policy_type`` and ``variant`` among one task's ``baselines``: at ``version``, or the latest.
138
+ LookupError, naming what there is, if there is none (``where``: the task, for the message)."""
139
+ key = policy_type_key(policy_type)
140
+ mine = [b for b in baselines if policy_type_key(b.policy_type) == key and b.variant == variant]
141
+ if version is not None:
142
+ mine = [b for b in mine if b.version == version]
143
+ if mine:
144
+ return max(mine, key=lambda b: version_key(b.version))
145
+ there = sorted({f"{b.policy_type}" + (f" ({b.variant})" if b.variant != "fine-tuned" else "") + f" {b.version}"
146
+ for b in baselines})
147
+ wanted = f"{policy_type}" + (f" ({variant})" if variant != "fine-tuned" else "") + (f" {version}" if version else "")
148
+ raise LookupError(f"no Armnet baseline {wanted}" + (f" for {where}" if where else "")
149
+ + (f"; there are: {', '.join(there)}" if there else "; there are none"))
150
+
151
+
152
+ class EvalDataset(BaseModel):
153
+ """Where the job records its episodes (a LeRobot dataset on the Hugging Face Hub)."""
154
+
155
+ model_config = ConfigDict(extra="forbid")
156
+
157
+ repo_id: str = Field(..., pattern=DATASET_REPO_PATTERN)
158
+ private: bool = True
159
+
160
+
161
+ class EvalDeclaration(BaseModel):
162
+ """What an eval job evaluates. Set as ``JobSpec.eval``."""
163
+
164
+ model_config = ConfigDict(extra="forbid")
165
+
166
+ kind: Literal["single", "ranked"]
167
+ policies: list[EvalPolicy] = Field(..., min_length=1, max_length=MAX_EVAL_POLICIES)
168
+ episodes: Optional[int] = Field(default=None, ge=1, le=1000,
169
+ description="single: the rollouts to run.")
170
+ trials: Optional[int] = Field(default=None, ge=1, le=500,
171
+ description="ranked: trials, each one rollout of every policy.")
172
+ dataset: Optional[EvalDataset] = None
173
+ name: Optional[str] = Field(default=None, max_length=120, description="A name to show the results under.")
174
+ benchmark: Optional[str] = Field(default=None, max_length=100,
175
+ description="The benchmark these results are for, if any.")
176
+
177
+ @model_validator(mode="after")
178
+ def _consistent(self) -> "EvalDeclaration":
179
+ names = [p.name for p in self.policies]
180
+ if len(set(names)) != len(names):
181
+ raise ValueError(f"eval policy names must differ, got {names}")
182
+ if self.kind == "single":
183
+ if len(self.policies) != 1:
184
+ raise ValueError("a single-policy eval names exactly one policy")
185
+ if self.episodes is None:
186
+ raise ValueError("a single-policy eval sets episodes")
187
+ if self.trials is not None:
188
+ raise ValueError("trials apply to ranked evals; a single-policy eval sets episodes")
189
+ else:
190
+ if not 2 <= len(self.policies) <= MAX_EVAL_POLICIES:
191
+ raise ValueError(f"a ranked eval compares 2 to {MAX_EVAL_POLICIES} policies")
192
+ if self.trials is None:
193
+ raise ValueError("a ranked eval sets trials")
194
+ if self.episodes is not None:
195
+ raise ValueError("episodes apply to single-policy evals; a ranked eval sets trials")
196
+ return self
197
+
198
+ def policy_names(self) -> list[str]:
199
+ return [p.name for p in self.policies]
200
+
201
+
202
+ class EvalPlanSlot(BaseModel):
203
+ label: str = Field(..., max_length=8)
204
+ policy: str = Field(..., pattern=POLICY_NAME_PATTERN)
205
+
206
+
207
+ class EvalPlanTrial(BaseModel):
208
+ """One trial of the plan the job commits to before its first rollout."""
209
+
210
+ number: int = Field(..., ge=1)
211
+ layout: Optional[int] = Field(default=None, ge=0)
212
+ slots: list[EvalPlanSlot] = Field(..., min_length=1, max_length=MAX_EVAL_POLICIES)
213
+
214
+
215
+ class EvalRolloutRecord(BaseModel):
216
+ """One rollout, as the cell saw it and as the job described it."""
217
+
218
+ seq: int = Field(..., ge=1, description="Its place among the job's rollouts, from 1.")
219
+ trial: Optional[int] = None
220
+ label: Optional[str] = None
221
+ policy: Optional[str] = Field(default=None, description="From the job's committed plan or its record.")
222
+ layout: Optional[int] = Field(default=None, description="The staging layout the cell showed the operator.")
223
+ outcome: Optional[Literal["success", "failure"]] = Field(
224
+ default=None, description="The cell's: the operator's verdict or its automated check. None if neither came.")
225
+ outcome_source: Optional[Literal["operator", "automated"]] = None
226
+ rank: Optional[int] = Field(default=None, description="Its rank in its trial, 1 best; None if unranked.")
227
+ claimed_outcome: Optional[str] = Field(default=None, max_length=20,
228
+ description="The job's own view (success, failure, timeout).")
229
+ score: Optional[float] = None
230
+ stages: dict[str, Any] = Field(default_factory=dict)
231
+ notes: str = Field(default="", max_length=4000)
232
+ dataset_episode: Optional[int] = Field(default=None, ge=0)
233
+ detail: dict[str, Any] = Field(default_factory=dict)
234
+ started_at: Optional[datetime] = None
235
+ ended_at: Optional[datetime] = None
236
+
237
+
238
+ class EvalTrialRecord(BaseModel):
239
+ """How a ranked trial ended."""
240
+
241
+ number: int = Field(..., ge=1)
242
+ layout: Optional[int] = None
243
+ labels: list[str] = Field(default_factory=list, description="Its rollouts' labels, in the order they ran.")
244
+ status: str = Field(..., description="ranked / dropped / timeout / cancelled / unranked")
245
+ decided_by: Optional[Literal["operator", "outcomes"]] = None
246
+ ranks: Optional[list[Optional[int]]] = Field(default=None, description="Per label, 1 best; None no progress.")
247
+
248
+
249
+ class EvalReport(BaseModel):
250
+ """What an eval job found, sent by its cell with the job's result."""
251
+
252
+ format: int = EVAL_REPORT_FORMAT
253
+ kind: Literal["single", "ranked"]
254
+ plan: Optional[list[EvalPlanTrial]] = Field(
255
+ default=None, description="Committed by the job before its first rollout; None if it committed none.")
256
+ rollouts: list[EvalRolloutRecord] = Field(default_factory=list, max_length=MAX_EVAL_ROLLOUTS)
257
+ trials: list[EvalTrialRecord] = Field(default_factory=list)
258
+ dataset_repo_id: Optional[str] = Field(default=None, max_length=200)
259
+ errors: list[str] = Field(default_factory=list,
260
+ description="What the cell refused from the job's code, e.g. a late plan.")
@@ -0,0 +1,154 @@
1
+ """Canonical customer-container image references.
2
+
3
+ The authenticated username, registry host, and repository prefix are trusted
4
+ platform state. Customers choose only the image selector beneath their own
5
+ namespace (for example ``policy:sha-abc``). A fully-qualified SDK-produced ref
6
+ is accepted for compatibility, but its supplied username is discarded and the
7
+ canonical prefix is rebuilt server-side.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ _NAME_COMPONENT = re.compile(r"^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$")
15
+ _TAG = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")
16
+ _SHA256 = re.compile(r"^sha256:[0-9a-f]{64}$")
17
+ _CUSTOMER_SLUG = re.compile(r"^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$")
18
+
19
+
20
+ class ImageReferenceError(ValueError):
21
+ """An image ref cannot be safely canonicalized for one customer."""
22
+
23
+
24
+ def customer_registry_slug(username: str) -> str:
25
+ """Current username→registry mapping, validated as one path component.
26
+
27
+ Existing production namespaces use lowercase usernames, so preserve that
28
+ mapping. Account provisioning must prevent case-fold collisions (e.g.
29
+ ``Alice`` and ``alice``); this function rejects path separators and other
30
+ characters rather than silently sanitizing them into collisions.
31
+ """
32
+
33
+ slug = username.strip().lower()
34
+ if not slug or not _CUSTOMER_SLUG.fullmatch(slug):
35
+ raise ImageReferenceError(
36
+ f"username {username!r} cannot be represented as a registry namespace"
37
+ )
38
+ return slug
39
+
40
+
41
+ def validate_image_selector(selector: str) -> str:
42
+ """Validate a repository path plus explicit tag or sha256 digest."""
43
+
44
+ if not selector or selector != selector.strip():
45
+ raise ImageReferenceError("image selector must be nonempty with no surrounding whitespace")
46
+ if any(ch.isspace() for ch in selector) or "\\" in selector:
47
+ raise ImageReferenceError("image selector must not contain whitespace or backslashes")
48
+ if selector.startswith(("-", "/", ".")) or "//" in selector:
49
+ raise ImageReferenceError("invalid image selector path")
50
+
51
+ name_and_tag, at, digest = selector.partition("@")
52
+ if at:
53
+ if not _SHA256.fullmatch(digest):
54
+ raise ImageReferenceError("image digest must be lowercase sha256:<64 hex>")
55
+ elif "@" in digest:
56
+ raise ImageReferenceError("invalid image digest")
57
+
58
+ last_slash = name_and_tag.rfind("/")
59
+ last_colon = name_and_tag.rfind(":")
60
+ tag = None
61
+ name = name_and_tag
62
+ if last_colon > last_slash:
63
+ name, tag = name_and_tag[:last_colon], name_and_tag[last_colon + 1 :]
64
+ if not _TAG.fullmatch(tag):
65
+ raise ImageReferenceError("invalid image tag")
66
+
67
+ if tag is None and not at:
68
+ raise ImageReferenceError("image selector must include an explicit tag or digest")
69
+ components = name.split("/")
70
+ if not components or any(not _NAME_COMPONENT.fullmatch(part) for part in components):
71
+ raise ImageReferenceError(
72
+ "image name must use lowercase path components containing letters, "
73
+ "digits, '.', '_', or '-'"
74
+ )
75
+ return selector
76
+
77
+
78
+ def customer_image_selector(
79
+ requested: str,
80
+ *,
81
+ registry: str,
82
+ namespace_prefix: str,
83
+ ) -> str:
84
+ """Return the customer-controlled suffix from a relative or platform ref.
85
+
86
+ For a full ref, the shape must be
87
+ ``<registry>/<namespace-prefix>/<supplied-user>/<selector>``. The supplied
88
+ user component is deliberately ignored; callers reconstruct it from the
89
+ authenticated identity.
90
+ """
91
+
92
+ registry = registry.strip().rstrip("/")
93
+ prefix = namespace_prefix.strip().strip("/")
94
+ if not registry or "/" in registry or not prefix:
95
+ raise ImageReferenceError("platform image registry configuration is invalid")
96
+
97
+ first = requested.split("/", 1)[0]
98
+ explicit_registry = "/" in requested and (
99
+ "." in first or ":" in first or first == "localhost"
100
+ )
101
+ if not explicit_registry:
102
+ return validate_image_selector(requested)
103
+
104
+ platform_base = f"{registry}/{prefix}/"
105
+ if not requested.startswith(platform_base):
106
+ raise ImageReferenceError(
107
+ f"image must come from the platform registry {registry}/{prefix}"
108
+ )
109
+ remainder = requested[len(platform_base) :]
110
+ supplied_user, separator, selector = remainder.partition("/")
111
+ if not separator or not _CUSTOMER_SLUG.fullmatch(supplied_user):
112
+ raise ImageReferenceError(
113
+ "fully-qualified customer image must include a user namespace and image selector"
114
+ )
115
+ return validate_image_selector(selector)
116
+
117
+
118
+ def canonical_customer_image(
119
+ requested: str,
120
+ *,
121
+ registry: str,
122
+ namespace_prefix: str,
123
+ username: str,
124
+ ) -> str:
125
+ """Build the only image ref an authenticated customer may execute."""
126
+
127
+ selector = customer_image_selector(
128
+ requested,
129
+ registry=registry,
130
+ namespace_prefix=namespace_prefix,
131
+ )
132
+ slug = customer_registry_slug(username)
133
+ return f"{registry.rstrip('/')}/{namespace_prefix.strip('/')}/{slug}/{selector}"
134
+
135
+
136
+ def require_owned_customer_image(
137
+ image: str,
138
+ *,
139
+ registry: str,
140
+ namespace_prefix: str,
141
+ username: str,
142
+ ) -> None:
143
+ """Reject a persisted/dispatch image unless it is already canonical."""
144
+
145
+ canonical = canonical_customer_image(
146
+ image,
147
+ registry=registry,
148
+ namespace_prefix=namespace_prefix,
149
+ username=username,
150
+ )
151
+ if image != canonical:
152
+ raise ImageReferenceError(
153
+ f"image is not owned by authenticated user {username!r}; expected {canonical!r}"
154
+ )