Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion INTERFACE.md
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ cheapest way to keep it from calcifying into one.
| `GET /project` | `{root, name, units, parts[], serve_mode, capabilities}` — the `open_project` projection, same serializer as `mcp/app.py` |
| `GET /parts` | `[{name, path, content_hash, snapshot_ref}]` — `list_parts` projection. **Same serializer** as `heph part list --json` (`hephaestus.core.project_store.listing`). |
| `GET /parts/{part}/script?offset_line&limit_lines` | `read_part` result verbatim, `_PAGING_FIELDS` intact. CLI counterpart: `heph script show --json`. |
| `GET /parts/{part}/build` | `BuildResult` projection: `{status, current, artifact_ref, project_snapshot_ref, effective_params, geometry_count, geometries[], metrics, checks, source_map_ref, warnings, error?, critique?}`. CLI counterpart: `heph part show --json` emits the engine `BuildResult` (same document `heph build --json` writes) or `{status:"not_built"}`. |
| `GET /parts/{part}/build` | `BuildResult` projection: `{status, current, artifact_ref, project_snapshot_ref, effective_params, geometry_count, geometries[], metrics, checks, source_map_ref, warnings, checkpoints[], error?, critique?}`. CLI counterpart: `heph part show --json` emits the engine `BuildResult` (same document `heph build --json` writes) or `{status:"not_built"}`. |
| `GET /parts/{part}/properties` | the enumerated `part.*` metadata projection (§6.2) |
| `GET /parts/{part}/checks` | the shared `heph check --json` serializer (§6.3) |
| `GET /parts/{part}/params` | `PARAMS` declarations `{name, value, default, min, max, step, scope}` + `state_hash`. CLI counterpart: `heph params [PART] --json` (script literals + last-build effective values; no sandbox, no `state_hash` — it does not write `set_params`). |
Expand Down
11 changes: 8 additions & 3 deletions architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,14 @@ Runs a part script in a sandboxed subprocess with the injected namespace from

- **Statement-level execution.** The script is split into top-level statements
via `ast`. Statements execute sequentially; after each one the executor
records a checkpoint: statement index, source span, names bound, and — for
names bound to build123d shapes — a metrics snapshot (solid count, bbox,
volume, face count, `sealed` = is-manifold, `genus`).
records a checkpoint: statement index, source span, names bound, the
verbatim statement text, and — for names bound to build123d shapes — a
metrics snapshot (solid count, bbox, volume, face count, `sealed` =
is-manifold, `genus`). Those checkpoints persist on the §8 `BuildResult`
and are projected by `GET /parts/{part}/build` as `checkpoints[]`. Metrics
and per-statement BRep writes stay lazy (mission rule 4): a checkpoint
carries an `artifact_ref` only when publication minted a last-good blob
for that stop.
- **Failure semantics.** On exception, the build result MUST include: the
failing line and column, exception type, a source frame (±2 lines), the last
successfully executed statement, the last-good metrics snapshot, and a
Expand Down
64 changes: 64 additions & 0 deletions core/schemas/build_result.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,13 @@
"type": "string"
},
"description": "\u00a75.2 manufacturing metadata as the worker evaluated it (runtime truth; empty for pre-2026-08-03 records)."
},
"checkpoints": {
"type": "array",
"description": "Incremental-executor per-statement checkpoints (architecture \u00a73.1). Absent from records written before the HTTP Timeline projection.",
"items": {
"$ref": "#/$defs/statementCheckpoint"
}
}
},
"$defs": {
Expand Down Expand Up @@ -361,6 +368,63 @@
}
}
},
"statementCheckpoint": {
"type": "object",
"required": [
"index",
"line",
"statement",
"span",
"bound",
"shapes",
"artifact_ref"
],
"additionalProperties": false,
"properties": {
"index": {
"type": "integer",
"minimum": 0
},
"line": {
"type": "integer",
"minimum": 1
},
"statement": {
"type": "string"
},
"span": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"minItems": 4,
"maxItems": 4
},
"bound": {
"type": "array",
"items": {
"type": "string"
}
},
"shapes": {
"type": "array",
"items": {
"type": "string"
}
},
"artifact_ref": {
"oneOf": [
{
"$ref": "#/$defs/artifactRef"
},
{
"type": "null"
}
]
}
}
},
"lastGood": {
"type": "object",
"required": [
Expand Down
53 changes: 52 additions & 1 deletion core/src/hephaestus/core/executor/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import json
import sys
from collections.abc import Mapping
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Literal, cast

Expand Down Expand Up @@ -51,6 +51,7 @@
GeometryEntry,
InputHashes,
Metrics,
StatementCheckpoint,
Warning,
)
from opstore.types import JSONValue
Expand Down Expand Up @@ -183,6 +184,53 @@ def _require_dict(value: JSONValue, what: str) -> dict[str, JSONValue]:
return value


def _checkpoints_from_worker(
raw: JSONValue | None,
last_good_ref: str | None,
error: ErrorRecord | None,
) -> tuple[StatementCheckpoint, ...]:
"""Lift the worker's per-statement checkpoints onto the §8 record.

The worker records index/span/bound/shapes (and, from this change, line +
verbatim statement text). Publication mints at most one checkpoint blob —
the last-good BRep of a failed build — and that ref is attached to the
checkpoint whose line is ``error.built_through.line``. Intermediate stops
carry ``artifact_ref=null``: mission rule 4 keeps per-statement BRep writes
lazy, and inventing a ref the store does not hold would be a lie.
"""
if raw is None:
return ()
if not isinstance(raw, list):
raise ValidationError("worker result: checkpoints must be a list", kind="evaluation")
parsed: list[StatementCheckpoint] = []
for item in raw:
if not isinstance(item, dict):
raise ValidationError("worker result: checkpoints must be objects", kind="evaluation")
record = dict(cast("dict[str, JSONValue]", item))
span = record.get("span")
if "line" not in record and isinstance(span, list) and span:
first = span[0]
if isinstance(first, int) and not isinstance(first, bool):
record["line"] = first
record.setdefault("statement", "")
record.setdefault("artifact_ref", None)
parsed.append(StatementCheckpoint.from_json(record))
if last_good_ref is None or error is None or error.built_through is None:
return tuple(parsed)
line = error.built_through.line
attached = False
out: list[StatementCheckpoint] = []
for checkpoint in parsed:
if not attached and checkpoint.line == line:
out.append(replace(checkpoint, artifact_ref=last_good_ref))
attached = True
else:
out.append(checkpoint)
if not attached and out:
out[-1] = replace(out[-1], artifact_ref=last_good_ref)
return tuple(out)


def import_hashes(request: BuildRequest) -> dict[str, str]:
"""§8 ``input_hashes.imports``: ``{declared path: sha256}`` of the frozen bytes.

Expand Down Expand Up @@ -469,6 +517,9 @@ def assemble_build(
).items()
if isinstance(v, str)
},
checkpoints=_checkpoints_from_worker(
worker_result.get("checkpoints"), last_good_ref, error
),
)
geometry_index_raw = worker_result.get("geometry_index")
geometry_index_json = geometry_index_raw if isinstance(geometry_index_raw, dict) else None
Expand Down
11 changes: 7 additions & 4 deletions core/src/hephaestus/core/executor/worker.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""The sandboxed build worker: one JSON job on stdin -> one JSON result on stdout.

Executes a part script statement by statement under the §2 injected
namespace, checkpointing after every statement (index, span, bound names;
shape refs are held eagerly, metrics are computed lazily — for the last-good
snapshot on failure and for the final compound on success, per mission
rule 4). On failure it emits the complete §8 error record (line/col, type,
namespace, checkpointing after every statement (index, line, verbatim
statement text, span, bound names; shape refs are held eagerly, metrics
are computed lazily — for the last-good snapshot on failure and for the
final compound on success, per mission rule 4). On failure it emits the
complete §8 error record (line/col, type,
message, ±2-line frame with a ``"> "`` marker, ``built_through``,
``last_good`` metrics) and writes the last-good BRep under the out dir; on
success it writes the final compound BRep plus geometry index, source map,
Expand Down Expand Up @@ -489,6 +490,8 @@ def execute_job(job: Mapping[str, JSONValue]) -> dict[str, JSONValue]:
last_good.update(statement, bound_shapes)
checkpoint: dict[str, JSONValue] = {
"index": statement.index,
"line": statement.lineno,
"statement": statement.text,
"span": list(statement.span),
"bound": list(bound),
"shapes": list(shape_names),
Expand Down
14 changes: 14 additions & 0 deletions core/src/hephaestus/core/project_store/publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,20 @@ def current_result(self, part: str) -> BuildResult | None:
raise ValidationError("current bundle has no result record", kind="contract")
return BuildResult.from_json(result_raw)

def last_failure_result(self, part: str) -> BuildResult | None:
"""The most-recent failed BuildResult of ``part`` (lock-free read).

Failed publishes store the §8 record (not a current bundle) at the
last-failure pointer. ``None`` when no failed build has been published.
"""
pointer = self._store.blobs.read_pointer(last_failure_pointer(part))
if pointer is None:
return None
raw = json.loads(self._store.blobs.get(pointer).decode("utf-8"))
if not isinstance(raw, dict):
raise ValidationError("last-failure record is not an object", kind="contract")
return BuildResult.from_json(cast("Mapping[str, JSONValue]", raw))

def baseline_for(self, part: str) -> FingerprintBaseline | None:
"""§5.3 fingerprint baseline: the current bundle's descriptors + ref.

Expand Down
89 changes: 85 additions & 4 deletions core/src/hephaestus/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

Mirrors ``script_contract.md`` §8 exactly — every field of the build-result
record, including the full ``error`` object with ``built_through``,
``last_good``, ``last_good_artifact_ref`` and ``hint`` — plus the CheckReport
shape from ``architecture.md`` §3.4 (check-set generation, immutable bundle
ref, per-file hashes, geometry ``project_snapshot_ref``, per-check
pass + measured).
``last_good``, ``last_good_artifact_ref`` and ``hint``, plus the incremental
executor's per-statement ``checkpoints`` (architecture §3.1) — and the
CheckReport shape from ``architecture.md`` §3.4 (check-set generation,
immutable bundle ref, per-file hashes, geometry ``project_snapshot_ref``,
per-check pass + measured).

Every record serializes with ``to_json()`` (a JSON-ready dict) and rebuilds
with ``from_json()``. The committed JSON Schema at
Expand Down Expand Up @@ -74,6 +75,16 @@ def _str_map(data: Mapping[str, JSONValue], key: str) -> dict[str, str]:
return out


def _str_tuple(data: Mapping[str, JSONValue], key: str) -> tuple[str, ...]:
raw = cast("list[JSONValue]", _req(data, key, list))
out: list[str] = []
for item in raw:
if not isinstance(item, str):
raise ValidationError(f"field {key!r}: expected list of str", kind="contract")
out.append(item)
return tuple(out)


@dataclass(frozen=True)
class InputHashes:
"""§8 ``input_hashes``: the immutable snapshot identity of a build."""
Expand Down Expand Up @@ -277,6 +288,56 @@ def from_json(cls, data: Mapping[str, JSONValue]) -> BuiltThrough:
return cls(line=_req(data, "line", int), statement=_req(data, "statement", str))


@dataclass(frozen=True)
class StatementCheckpoint:
"""One incremental-executor per-statement checkpoint (architecture §3.1).

The worker records these after every top-level statement that completed:
index, source span, names bound, and shape-binding names. ``statement`` is
the verbatim source slice so a Timeline (or a repair loop) can name the
stop without slicing the script itself. ``artifact_ref`` is set only when
publication minted a blob for that stop — today that is the last-good
checkpoint of a failed build, never an invented per-statement BRep.
"""

index: int
line: int
statement: str
span: tuple[int, int, int, int]
bound: tuple[str, ...]
shapes: tuple[str, ...]
artifact_ref: str | None = None

def to_json(self) -> dict[str, JSONValue]:
return {
"index": self.index,
"line": self.line,
"statement": self.statement,
"span": list(self.span),
"bound": list(self.bound),
"shapes": list(self.shapes),
"artifact_ref": self.artifact_ref,
}

@classmethod
def from_json(cls, data: Mapping[str, JSONValue]) -> StatementCheckpoint:
span_raw = cast("list[JSONValue]", _req(data, "span", list))
if len(span_raw) != 4 or not all(
isinstance(item, int) and not isinstance(item, bool) for item in span_raw
):
raise ValidationError("field 'span': expected four integers", kind="contract")
span = cast("tuple[int, int, int, int]", tuple(span_raw))
return cls(
index=_req(data, "index", int),
line=_req(data, "line", int),
statement=_req(data, "statement", str),
span=span,
bound=_str_tuple(data, "bound"),
shapes=_str_tuple(data, "shapes"),
artifact_ref=_opt_str(data, "artifact_ref"),
)


@dataclass(frozen=True)
class LastGood:
"""§8 ``error.last_good``: metrics of the last-good checkpoint geometry."""
Expand Down Expand Up @@ -395,6 +456,11 @@ class BuildResult:
#: downstream reader into literal-only static script parsing — the
#: nest-gusset "missing" blank_size the model had in fact written).
metadata: Mapping[str, str] = field(default_factory=dict[str, str])
#: Incremental-executor per-statement checkpoints. Empty on records written
#: before this field existed — the worker always recorded them; the §8
#: record used to drop them, which left ``GET /parts/{part}/build`` unable
#: to name the stops the Timeline is a projection of.
checkpoints: tuple[StatementCheckpoint, ...] = ()

def __post_init__(self) -> None:
if self.status not in ("ok", "failed"):
Expand Down Expand Up @@ -423,6 +489,7 @@ def to_json(self) -> dict[str, JSONValue]:
"warnings": [warning.to_json() for warning in self.warnings],
"error": None if self.error is None else self.error.to_json(),
"metadata": dict(self.metadata),
"checkpoints": [checkpoint.to_json() for checkpoint in self.checkpoints],
}

@classmethod
Expand Down Expand Up @@ -487,6 +554,9 @@ def from_json(cls, data: Mapping[str, JSONValue]) -> BuildResult:
error=error,
# Absent from pre-2026-08-03 records; {} is the honest reading.
metadata=_str_map(data, "metadata") if "metadata" in data else {},
# Absent from records written before the HTTP Timeline projection;
# () is the honest reading of "this build named no statement stops".
checkpoints=_checkpoints(data) if "checkpoints" in data else (),
)

def __eq__(self, other: object) -> bool:
Expand Down Expand Up @@ -571,6 +641,16 @@ def __hash__(self) -> int:
return hash((self.part, self.check_set_generation, self.check_bundle_ref))


def _checkpoints(data: Mapping[str, JSONValue]) -> tuple[StatementCheckpoint, ...]:
raw = cast("list[JSONValue]", _req(data, "checkpoints", list))
out: list[StatementCheckpoint] = []
for item in raw:
if not isinstance(item, dict):
raise ValidationError("checkpoints: expected list of objects", kind="contract")
out.append(StatementCheckpoint.from_json(cast("dict[str, JSONValue]", item)))
return tuple(out)


__all__: Sequence[str] = (
"AuditHashes",
"BuildResult",
Expand All @@ -583,5 +663,6 @@ def __hash__(self) -> int:
"InputHashes",
"LastGood",
"Metrics",
"StatementCheckpoint",
"Warning",
)
5 changes: 5 additions & 0 deletions core/tests/test_executor_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@ def test_checkpoints_cover_every_statement(self, golden: UnpublishedBuild) -> No
for name in bound:
by_bound.setdefault(str(name), []).append(str(index))
assert "base" in by_bound and "slotted" in by_bound and "posts" in by_bound
# The §8 record carries the same stops the worker recorded — this is
# the projection GET /parts/{part}/build reads, not a second list.
assert [c.index for c in golden.result.checkpoints] == list(range(STATEMENT_COUNT))
assert all(c.artifact_ref is None for c in golden.result.checkpoints)
assert golden.result.checkpoints[0].statement.startswith("PARAMS")

def test_checkpoint_spans_are_exact(self, golden: UnpublishedBuild) -> None:
checkpoints_raw = golden.worker_result["checkpoints"]
Expand Down
Loading
Loading