8000 A build result is a sum with an exception in it · Issue #608 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

A build result is a sum with an exception in it #608

Closed

Description

@Lillecarl

DONE. All four stages are written and the gate is green.
buildPathsWithResults
is the last shape of Store.build_paths that is not bound, and it
cannot be declared the way the other returns were. The reason is one
line of upstream:

using Failure = BuildError;

What upstream has

nix/store/store-api.hh:665

virtual std::vector<KeyedBuildResult> buildPathsWithResults(
    const std::vector<DerivedPath> & paths,
    BuildMode buildMode = bmNormal,
    std::shared_ptr<Store> evalStore = nullptr);

and upstream's own doc comment says what makes it different from
buildPaths:

Note that in case of a build/substitution error, this function
won't throw an exception, but return a BuildResult containing an
error message.

nix/store/build-result.hh

struct BuildResult {
    struct Success {
        using Status = enum BuildResultSuccessStatus;
        Status status;
        SingleDrvOutputs builtOutputs;
    };
    using Failure = BuildError;
    std::variant<Success, Failure> inner = Failure{};

    unsigned int timesBuilt = 0;
    time_t startTime = 0, stopTime =
8000
 0;
    std::optional<std::chrono::microseconds> cpuUser, cpuSystem;
};

struct KeyedBuildResult : BuildResult { DerivedPath path; };

struct BuildError : public CloneableError<BuildError, Error> {
    Status status = MiscFailure;
    bool isNonDeterministic = false;
};

So a result is a SUM, and one arm of that sum is an exception class -
BuildError inherits Error and is throwable. Upstream even keeps
tryThrowBuildError() on the struct, which turns the value back into
the raise that buildPaths would have done.

The two enums are the easy half. BuildResultSuccessStatus has four
words and BuildResultFailureStatus has twelve, and #607's
marker handles both without learning anything new - upstream has no
parser for either, so they take the from_word shape BuildMode
took.

The decision

How does a FAILED result reach Python?

Three answers, and they are different APIs rather than different
spellings of one.

  1. As a value, with a status word. result.status() answers
    "permanent-failure" and result.message() carries the text.
    Closest to what the C++ hands back, and the reason the method
    exists at all: a caller building twenty targets wants nineteen
    results and one failure, not one exception.

    Costs: the failure arm's Error half is thrown away, so a caller
    who wants the typed error the SYNC surface gives cannot have it
    here. And 059 declared a sum type as an ALIAS of its arms; this
    sum's arms are not two declared classes, they are a struct and an
    exception.

  2. As the exception, raised. Which is buildPaths, and makes
    buildPathsWithResults pointless.

  3. As a value that CARRIES the exception. result.error()
    answers a NixError subclass - the one A typed error has to survive the wire #573 already gets
    across the wire with its class and its colour - and
    result.raise() mirrors upstream's tryThrowBuildError.

    This is the only one that loses nothing. It costs a declaration
    that says an error class is a FIELD of a value, which nothing
    declares today: 036 made an error CROSS as an error, and this
    would make one be a part of something else.

Answer 3 looks right and it is the most work, so it is a decision
rather than a default.

DECIDED, 2026-09-01: it does not raise

Carl: "buildresult doesn't raise in Nix so it shouldn't raise in
Python either."

That rules out answer 2 outright, and it settles the SEMANTICS rather
than the shape: reading a failed result is never an exception. A
caller building twenty targets gets twenty results.

Answer 3 is what that leaves, and it does not conflict. Nothing about
it raises on its own - error() ANSWERS with the typed error rather
than throwing it, and that is the whole difference from build_paths.
Upstream's tryThrowBuildError is a method a caller may call, not
something the value does; binding it is binding what Nix has, and it
is the caller who chooses. If even that is too close to raising, the
method goes and error() stays - the value semantics are the part
that was decided.

Answer 1 stays rejected for the reason already written: it throws
away the Error half, so this surface would tell a caller LESS than
the sync one does about the same failure.

What else was unsettled, and two of the three are decided

  • KeyedBuildResult adds path, a DerivedPath - which is the
    union The hpp files hold mappings, and must not #600 and A caster, instead of a conversion named at every call site #604 already made cross. So the key
    half is free.

  • Success::builtOutputs is SingleDrvOutputs, which upstream
    declares as std::map<OutputName, Realisation>.

    DECIDED, and DONE. Carl: the DSL should learn more complicated
    maps. It has: dict[str, T] over a declared class now spells
    std::map<std::string, T>, the same way list[T] already spelled
    a vector. So built_outputs needs nothing new when this is
    written.

    Two things went with it rather than beside it. The hard-coded
    "dict[str, int]": nb::dict table entry is deleted, because a body
    building an nb::dict by hand IS the mapping the emitter exists to
    derive - gc_stats returns the map now. And a container passes its
    alias's C++ spelling DOWN, which was a latent bug in the list
    branch too: list[I64] would have deduced a bare int with no
    width.

    Over RPC a map's values cross the way any value does. Carl again:
    a stateful unserializable object goes as a HANDLE - which is
    already what wire_blocker says, and it currently REFUSES a
    container of proxies outright ("one lease per element, and nothing
    grants leases in bulk", Track every handle that crosses, however deeply nested #568). Bulk leases are that task,
    not this one.

  • cpuUser/cpuSystem are std::optional<std::chrono::microseconds>.

    DECIDED, and DONE. Carl, twice: Python's own time
    representation - datetime.timedelta - and MICROSECONDS on the
    wire.

    So the DSL wants a Duration alias the way it has Path, and the
    two ends differ on purpose. nanobind ships the caster:
    <nanobind/stl/chrono.h> maps a std::chrono::duration to a
    datetime.timedelta both ways, so the in-process surface is a
    timedelta with no code of ours. The wire carries an int64 of
    microseconds and the codec rebuilds the timedelta on arrival,
    which is the same shape a vocabulary has: one Python type, a
    simpler thing on the wire, and a generated mapping at each end.

    Not a protobuf well-known Duration message, which was the
    alternative. It costs an import and a message where an int64 does,
    and google.protobuf.Duration splits into seconds plus nanos -
    a second representation to convert through for no gain over the
    unit upstream already uses.

  • timesBuilt, startTime, stopTime are plain and need nothing.
    startTime/stopTime are time_t, which is a POINT in time
    rather than a span, so the timedelta answer does not cover them.

Why it is worth doing

build_paths raises on the first failure and says nothing about what
succeeded. That is the wrong shape for the thing a caller most wants
to do with a store - build a list and find out what happened to each
element - and it is the only reason to bind this second method at
all.

What is NOT done

All the CODE. Upstream was read on 2026-09-01, and the three
questions the task opened with are now answered: the map is built,
the duration is decided, and the result does not raise.

What is left to write, roughly in order:

  1. DONE. The two status vocabularies. BuildSuccessStatus has
    four words and BuildFailureStatus has twelve, both with every
    enumerator named in spelled - upstream spells them CamelCase and
    a word is kebab-case, so the default spelling is right for none of
    the sixteen. Neither carries parsed_by, the same way BuildMode
    carries none: upstream parses neither from a string.

    The claim that a vocabulary emits nothing until something names it
    is MEASURED, not assumed. bindings-src after this commit has one
    occurrence of the string "BuildResult" in the whole tree, and it
    is inside build_paths's docstring, which already said this task
    was coming. No as_word, no from_word, no include.

    What it DOES emit is the Python half: the StrEnum in
    huggorm_bindings/words.py and its stub entry. That found the
    thing The manifest is a runtime interpreter, not an IR #601 is about - both front doors carry hand-written
    re-export lines, so the stub gate failed with __init__.pyi exports [...BuildFailureStatus...], the package exports [...]
    until two names were added to each by hand. Four lines of a fact
    the emitter already knows.

  2. DONE. The Duration alias, its <nanobind/stl/chrono.h>
    caster, and the microsecond form on the wire.

  3. DONE. BuildResult itself, which is where the new DSL is: a
    value one of whose fields is a declared ERROR class. A typed error has to survive the wire #573
    made an error CROSS as an error; nothing yet made one be PART of
    something else.

  4. DONE. Store.build_paths_with_results, which needed nothing new: a list of a declared value, and the same
    BuildMode build_paths takes.

The ORDER changed while 3 was written. 2 emits nothing until
something names it, the same way 1 does, so a commit of it alone
proves nothing. Duration now lands WITH its first user, which is
cpu_user/cpu_system on the result, after 3 and 4 work without
them.

Where 3 stands, 2026-09-01

Declared: decl/build_result.py with BuildSuccess over
nix::BuildResult::Success and KeyedBuildResult over
nix::KeyedBuildResult. Only the KEYED one, because only it is ever
produced - buildPathsWithResults returns a vector of them - so a
Python caller never meets a result that has forgotten what it is
about. errors.py declares BuildError with two parts more than a
NixError, and no cxx: a catch clause would change what
build_paths raises today, and this task is about the method that
does not raise at all.

One reader bug found and fixed on the way. An imported UNION did not
bring its arms: DerivedPath is declared in derived_path.py and
one arm of it is the StorePath that file imported from path.py,
so a third file naming the union could NAME it and not spell it. It
failed as KeyError: 'StorePath' inside the emitter, a long way from
the import that caused it. _uses now takes the imported file's own
uses first, one level deep.

The one hand-written C++ line was ASKED FOR and granted. The
accessor hands back a live Python exception OBJECT rather than
raising one, and cpp/errors.hpp already did all of that except the
last step - so raise_as splits into as_error, which builds the
instance, and a PyErr_SetObject that raises it. Net +8 lines, and
it DELETES the hand-rolled PyObject_GetAttrString /
PyObject_CallFunction refcounting in favour of nanobind's own API.
The fallback stays, because the translator calls this from inside
catch(...) where letting nanobind's exception out would lose the
error entirely.

Carl's reasoning matched pyerrors.py's own: turning a
std::exception into a live Python exception is nanobind's protocol
rather than anything a declaration knows.

What the codegen had to learn, 2026-09-01

Four things, and each has a gate.

  1. An imported UNION did not bring its arms. DerivedPath is
    declared in derived_path.py and one arm of it is the StorePath
    that file imported from path.py, so a THIRD file naming the
    union could name it and not spell it. It failed as KeyError: 'StorePath' inside the emitter, a long way from the import that
    caused it. _uses takes the imported file's own uses first, one
    level, its own classes winning on a clash.

  2. The reader skipped every EXCEPTION class. An error declaration
    wears no decorator - cxx = "nix::Error" is a bare assignment -
    and the class loop takes only decorated ones, so read() on
    errors.py returned no classes at all. Fine while only the errors
    emitter read the file; not fine once a VALUE had a field of one.
    Module.errors is read from the BASE - a class deriving from
    Exception, or from one the file already recognised - so nothing
    is listed and no decorator is invented.

    pyerrors.declared() was already returning [] because of this,
    which makes it a gate that has never tested anything. Not fixed
    here; it is a task.

  3. @spells. A vocabulary a BODY names and a signature does not.
    error() builds an exception carrying a failure word, and -> BuildError | None says nothing about it, so the twelve-word
    switch was never emitted. @needs one level up. It takes NAMES
    rather than classes, because a decorator argument is a constant
    here, and the emitter refuses a name that is not an enum-backed
    vocabulary - which is the gate the typed argument would have been.

  4. An error is a wire field. _wire_kinds gains an error kind,
    _msg_arg_type points it at the <Class>Fault message the status
    details already carry, check_wire_contract takes the names, and
    the codec gains error_to_msg/error_from_msg reading the same
    ERROR_FIELDS the fault codec reads. One shape for one error
    class, whether it arrives as a failed call or as a field.

Three things the build refuted

nanobind refuses None for an nb::object PARAMETER. A
KeyedBuildResult with no failure arm could not be rebuilt at all, and
the message listed every parameter as compatible - Invoked with types: StorePath, BuildSuccess, NoneType, int, int, int against a
signature reading error: object. The caster accepts anything; the
ARGUMENT is what refuses, so "error"_a.none(). Found by passing a
real BuildError and watching the same call succeed.

what() cannot be round-tripped through HintFmt. nix::Error
writes "error: " in front of its hint when it renders, and what()
is what crosses - so rebuilding from the crossed string and
rendering again says "error: error: ...", once more per hop. The
_from_parts body takes the prefix off. Caught by the round-trip
gate, which is what that gate is for.

A declared error compared by IDENTITY. Python's default, right
for an exception and wrong for this hierarchy: every class here
declares _wire_fields, which says it is rebuilt from its parts on
the far side. It became load-bearing the moment a value held one -
KeyedBuildResult.__eq__ is over its parts. NixError gains
__eq__ and __hash__ over to_dict(), same class only.

And one thing the TEST had wrong. Its sample wrote the error's two
message forms out by hand, which is restating libstore - the prefix
and the colour are both libstore's own rendering. It asks instead:
a seed goes in, error() renders it, and the rendering is what the
round trip runs on.

DECIDED, 2026-09-01: two vocabularies, not one merged list

The open shape question, which was a reading of upstream rather than
Carl's call. Upstream's own comment on both status enums says "Names
must be disjoint with" the other, which WOULD license one Python
vocabulary of sixteen words over two defaultless switches.

Declined, for two reasons found in the code.

Enumerated names ONE C++ enum, and both directions are keyed by it.
A merged list would have to answer which from_word<T> the word
"built" belongs to, and the only thing that knows is the arm the
result holds - which the caller already has. So the merge buys a
shorter word list and pays with an ambiguity the DSL has no way to
say.

And the arms carry different things. A success holds builtOutputs;
a failure holds a message and isNonDeterministic. A caller branches
on which arm it got whatever the word list looks like, so a single
status would let a caller THINK the branch was optional.

The shape that follows is upstream's own: tryGetSuccess and
tryGetFailure return pointers, so Python gets two optional arms
rather than one flat value with empty fields.

Declining the merge does not make the invariant stop mattering, so
test_the_two_build_statuses_keep_upstream_disjoint asserts it -
both the enumerator names and our sixteen words. PERTURBED: setting
MISC_FAILURE = "built" in the declaration fails it with our words collide: {'built'}, so the gate is known to test something.

Where 2 stands, 2026-09-02

Done, and it landed with its two users the way the order above says.
Duration = Annotated[datetime.timedelta, Cxx("microseconds")] in
declare.py, and cpu_user/cpu_system on KeyedBuildResult.

Four tables, one word each, and no fifth. microseconds is the
alias's Cxx spelling, so every layer translates it the way it
translates string or int64_t: nbemit.CXX_PARAM says
std::chrono::microseconds and the chrono caster,
manifest.PYTHON says datetime.timedelta, and the wire says
int. Nothing keyed by the PYTHON name, which was the other shape
considered - CXX_PYTHON is for a type with no alias behind it, and
a duration has one.

The in-process half is nanobind's, entirely. The chrono caster
maps std::chrono::duration<Rep, Period> to a datetime.timedelta
both ways, so @reads("cpuUser") emits a lambda returning
std::optional<std::chrono::microseconds> and nothing of ours
converts anything. Read at nanobind/stl/chrono.h:225.

The wire half is two functions and one table. _wiretypes.SPELLED
says a datetime.timedelta goes in an int field, which is what the
schema builder, the contract check and the codec all needed; the
codec's _SPELLED says what to put there and what to read back.
Two entries per type rather than one, unlike a vocabulary: a StrEnum
member IS a str, so one constructor serves both directions, and a
timedelta is not an int.

scalar() gained a sibling rather than a flag. It answers the
INCOMING direction and three call sites read it that way; to_wire()
is the outgoing one and defaults to it, so only a spelled scalar ever
has two.

Microseconds is not a preference. A timedelta's finest unit IS
the microsecond, so an int of them is lossless in both directions,
and upstream keeps the same resolution. A coarser wire would round a
build's CPU time silently.

datetime.timedelta is the first DOTTED type to cross.
pathlib.Path is declared and blocked - wire_blocker says it "is
not in the manifest, so it has no wire policy" - so nothing had ever
put a module-qualified name in a protobuf field. It needed no new
machinery: dotted_heads already writes import datetime into an
emitted module that annotates with one.

The gate, PERTURBED both ways

test_a_duration_crosses_as_whole_microseconds builds the real
KeyedBuildResultMsg, reads the int off it and reads the timedelta
back. The round-trip gate above it cannot see this boundary: it never
builds a message.

  • _duration_out divided by a millisecond: assert 1000 == 1000250.
  • _duration_in reading milliseconds: the timedelta comes back a
    thousand times too long.

The sample carries timedelta(seconds=1, microseconds=250) on
purpose. A wire that carried whole SECONDS would round-trip a whole
second happily, so a case that is a whole second proves nothing.

Absence is asserted separately, and the round-trip gate's own
"no part holds one value in every case" check forces it: the success
sample carries two durations and the failure sample carries None, so
neither field can be dropped from _from_parts unseen.

One thing this refuted, and it was mine

A collapse in smoke_test._same that no gate needs. nanobind's
chrono caster reads datetime.timedelta | float and writes
datetime.timedelta, so a duration PARAMETER renders wider than the
declaration - and I wrote the collapse before seeing it fire.
Removing the line changed nothing: the only durati 7D1D on parameters are
_from_parts's, and an _-prefixed name reaches no stub. Removed,
and the reason is recorded in _same's own docstring so the next
reader does not add it back.

That is #609's failure mode in miniature, and it was caught
this time because the line was taken out and the build was run again.

Migrated from tasks/071-a-build-result-is-a-sum-with-an-exception-in-it.md.done.


Assisted-By: Opus 5

Activity

  1. added
    source: huggorm
    on Oct 19, 2026
  2. added theissue type on Oct 19, 2026
  3. transferred this issue fromnixidae/huggormon Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source: huggorm

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0