8000 Real-Nix binding spike · Issue #552 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

Real-Nix binding spike #552

Closed
Closed

Description

@Lillecarl

DONE. The spike answered its question: this repo binds real
libstore, and every declaration names a real header. What the file
records afterwards - what the real methods are NOT tested on - is handed
to #574, w 8000 hich holds it.

Swap the mock for a first real type: bind genuine nix::StorePath from
the fetched Nix source (store path 2ijv0g6069dsh55z3bdr5ln2iv69mw7r),
keeping the mock alongside. Surfaces the last unknowns: real build
linkage, header quirks, namespace depth, boehmgc linkage against the
real library.

Gate: the review's verdict cluster (001/002/006) should be closed
first - runner lifecycle flaws convert from leaks to native crashes
against real libstore.

Update 2026-08-25

The verdict cluster is closed: 001, 002 and 006 are all done, and 002's
escrow lease leak - found 2026-08-25 - is fixed with an invariant
check behind it.

Two NEW gates matter more than that cluster did, both blocking in
practice rather than in principle:

  • 019 (typed Acquire). Real stores come from openStore(uri). An
    argument-less Acquire can construct nothing worth constructing
    against real libstore.
  • 020 (binding-to-C++ link). The generator maps pxd types to Python
    ones by stripping a leading "C". Real headers will not cooperate.

021 (free functions) is not blocking but is where a lot of the real
libstore surface lives.

Findings from reading the real source (2026-08-25)

Read while verifying 017's claim about StorePath. Store path
2ijv0g6069dsh55z3bdr5ln2iv69mw7r.

  • nix::StorePath() = delete. Real Nix FORBIDS default construction.
    Our mock declares StorePath() = default "as binding glue", and
    store.pyx depends on it: every produced value does
    StorePath.__new__(StorePath) and then assigns _ptr. That pattern
    does not survive contact with libstore. The binding will need a
    different produced-value shape - a pointer that starts null and is
    set by a factory, or construction in place.
  • StorePath holds one std::string. Its accessors return string_view
    INTO that member, so a Cython binding must copy before the owner
    dies, and must not hand a dangling view to Python.
  • StorePath already has nlohmann JSON serialization upstream
    (adl_serializer, json_avoids_null). The _wire = "value" policy
    matches a category Nix already has, rather than inventing one -
    and there may be a real serializer to reuse instead of _parts().
  • DerivedPath::to_string takes a const StoreDirConfig &. Wire-value
    serialization is not always a pure method of the value; some of it
    needs store context. _wire_fields assumes a self-contained
    _parts(); that assumption breaks here.
  • The header layout is src/libstore/include/nix/store/*.hh, so the
    pxd include paths are "nix/store/path.hh" and friends.

Starting 2026-08-25

Carl: "At this point it feels like we're implementing quite a lot of
Nix. Maybe it's better if we abort 034 and start linking against real
Nix?" Building function values into the mock was the point where mock
fidelity stopped paying.

Two things landed first, both because they make this step safer rather
than because they are part of it: the Python layers are now
huggorm-bindings / huggorm-generated / huggorm, and the suites are
73 pytest tests under anyio instead of three scripts with one main().
Against real Nix a failure can be a native crash, and a subprocess
server plus per-test isolation is what keeps one from taking the run.

What the packaged headers give us

nixpkgs nix is 2.34.8 with a dev output. Everything this file
predicted from the source checkout holds against the packaged headers:

  • nix::StorePath() = delete, a single std::string baseName member,
    and to_string() returning a std::string_view INTO it;
  • headers at include/nix/store/path.hh, so the pxd include is
    "nix/store/path.hh";
  • pkg-config files for every library: nix-store.pc, nix-expr.pc,
    nix-util.pc and the C-api ones. nix-store.pc carries
    -std=c++23, -lnixstore, and a Requires: nix-util, nlohmann_json >= 3.9.

So the build side is pkg-config, not hand-rolled include paths. That
is a real difference from the mock, where setup.py takes one
FAKE_LIBRARY prefix and joins include and lib onto it.

There is also a C API

nix_api_store.h, nix_api_value.h, nix_api_expr.h and friends
ship in the same dev output, with their own pkg-config files. That is
a second possible binding target and it is NOT obviously the wrong
one: a stable C ABI avoids every C++-in-Cython problem this repo has
worked around (except +, template types the pxd parser cannot
render, StorePath() = delete versus __new__-then-assign).

It is also a different project. The whole design here rests on reading
C++ declarations out of a pxd, and the C API would make the generator
read a C header instead. Worth a decision before the first binding is
written, not after.

Decided 2026-08-25. Carl: "The C API is not feature complete at
all which is why we're binding C++, we are doing 100% C++."

So the C API is not a fallback for the awkward cases either. Every
C++-in-Cython problem gets solved rather than routed around:
StorePath() = delete needs a produced-value shape that does not
default-construct, except + stays, and a template type in a pxd
renders as itself and maps to nothing until something maps it.

Done 2026-08-25: nix::StorePath is bound

It parses, validates, and crosses the wire. StorePath( "7rjjfrn5w3z1kb2v9v0ilxmvmb2n5k1y-hello-2.12.1") gives the base name,
the name part and the 32-character hash; "not-a-store-path" raises
with libstore's own message. The whole generator chain ran over it
unchanged: a manifest entry, a StorePathMsg wire message, a typed
constructor, and PEP 561 stubs carrying its docstrings.

The predicted problems, and which were real

  • StorePath() = delete breaks the produced-value pattern. NOT
    real. The pattern is __new__ then assign a POINTER; nothing ever
    default-constructs the C++ object. Declaring a default constructor
    in the pxd would have been the mistake, and not declaring one costs
    nothing.
  • Accessors return views into a member. Real, and handled: one
    _view() helper copies, and nothing that leaves the binding is a
    view. A view outliving its owner is a dangling pointer, not an
    exception, so there is no second chance to notice.
  • The pxd parser could not render the declarations. NOT real.
    string_view, the "hashPart" C-name rename and the copy
    constructor all parse; the parser even drops the copy constructor
    from the constructor list on its own. One line was needed:
    string_view maps to str, because a binding copies.

What actually bit

__cinit__ runs on EVERY __new__, including the argument-less one a
copy needs, so it cannot also be where construction happens. The real
constructor lives in __init__, and a _get() guard raises rather
than dereferencing NULL for an object that was __new__ed and never
initialised. The mock never hit this because its __init__ refuses:
it is produced, never constructed.

Linking

Against the SPLIT components, not the nix package (Carl,
2026-08-25): nix.libs.nix-{util,store,expr,fetchers,flake}. nix
itself is the CLI and drags its closure - 158.6 MiB against 143.1 MiB
for nix-store alone, and only the libraries are ever loaded.

setup.py reads pkg-config rather than joining include and lib onto
a prefix. That is not a style choice: nix-store.pc carries
-std=c++23, a Requires chain into nix-util and nlohmann_json, and
a private link line nobody should reconstruct by hand. rpath comes
from the same place, because Nix has no global library path to fall
back on.

Naming

Carl: "Let's not prefix everything with Nix when we're just getting
started, naming is important and a PITA to change later."

So the REAL type takes the real name and the mock yields it. Each mock
class gets its Mock prefix exactly when its real counterpart lands,
and the prefix disappears when the mock does. StorePath is real now;
MockStorePath is the mock's, and CMockStorePath its pxd alias.

Modules mirror Nix's own header layout rather than inventing one:
nix/store/path.hh is bound by path.pyx and declared by
c_path.pxd. When the mock leaves, store.pyx and eval.pyx are
free for nix/store/store-api.hh and nix/expr/eval.hh.

Errors keep their type, and their colour

Both of the things above are done, because every type from here
inherits whatever this boundary does.

except +translate_nix_error names a C++ function Cython calls from
inside catch(...), and whatever Python error it sets is what the
caller sees. nix_error.hpp catches most-derived first and raises out
of huggorm_bindings.errors, whose hierarchy mirrors libnixutil's
own: BadStorePathName under BadStorePath under NixError, so
catching the middle one still catches the leaf. The classes are
imported lazily, on the first failure, so nothing runs while the
package is still importing itself.

The message is carried TWICE. Carl: "The color should be available as
a field, useful when printing error messages to users tty (which is
why it exists)." So str(e) is stripped - escape codes are wrong in a
traceback and wrong over the wire - and e.colored is exactly what
libstore wrote. Stripping at the boundary and nowhere else would take
the colour from every caller who has a terminal.

Only what a binding can actually raise is listed. Adding a Nix type
means adding whatever it throws, beside the catch that produces it.

One thing that surfaced with it

A stubs package REPLACES the runtime package for a typechecker, so
errors.py - hand-written Python, right there in the bindings -
vanished behind stubs that never mention it. The stubs are marked
partial now, which is PEP 561's answer: fall back to the real
package for anything not stubbed. That is exactly right here. These
stubs exist because a compiled extension carries no signatures, and a
.py file needs no help.

Still open

A typed Nix error does not survive the WIRE yet. The server wraps an
unknown exception in InternalError with cause_type and
cause_message, and the client rebuilds the cause by NAME from a map
of builtins - so a BadStorePath arrives as a plain Exception with
the right message and the wrong type. Teaching that map about the nix
errors means the generated runtime importing from the bindings, which
it does not do today.

Done 2026-08-25: nix::Store, through openStore

Store("dummy://") opens an in-memory store - nothing on disk, so it
works in a build sandbox - and prints, parses and checks paths.
Store("bogus://nowhere") raises NixError: don't know how to open Nix store with scheme 'bogus', and parsing a path outside the store
directory raises BadStorePath.

Three things the header does not tell you

libstore ABORTS if it has not been initialised. Not an exception -
The program must call nix::initNix() before calling any libstore library functions, and the process is gone. So the binding calls it
on import, before anything can reach libstore. initLibStore, not
initNix: initNix lives in libnixmain and does what a COMMAND needs -
argv0, signal handlers, a logger on stderr - and a library embedded in
someone else's process should not take those over. initLibStore calls
initLibUtil itself.

There is no getUri(). 2.34 moved it to getHumanReadableURI() on
the config, which Store reaches through a reference member. Upstream is
explicit that it is for logging only: it does not round-trip as a store
reference and is not a cache key.

Construction is a factory. nix::Store is abstract and the URI picks
the implementation, so there is no constructor for a pxd to describe.
The binding declares _ctor_from = "open_store" and the generator
reads the FACTORY's parameters as the constructor's - which is how a
typed Acquire keeps working (#19) for a type C++ never lets you
construct.

Structure, before there is more of it

Carl: "There's going to be a lot of dependent bindings all of the time
[...] All intermediary bindings need to be treated with care and
respect as well [...] Put thought into where to put all code to keep
the structure easy to understand and maintainable."

So the layout is written down in huggorm_bindings/__init__.py rather
than left to accrete:

  • one Nix header, one binding module, named after it. Nix's own layout
    is the map, so nobody learns a second one;
  • three files per module: c_<name>.pxd for what C++ declares,
    <name>.pxd for what OUR cdef classes declare, <name>.pyx for the
    binding. The middle one is what makes DEPENDENT bindings work -
    Cython will not share a cdef class's fields across modules without
    it, and store.pyx needs StorePath._ptr;
  • _cpp/ for C++ this repo writes, one header per binding plus a
    shared errors.hpp. Its README carries the rule for what belongs
    there - shapes a pxd cannot say - and the sharper rule for what does
    not: anything that computes, decides or holds state is a binding
    written in the wrong language.

queryAllValidPaths, and the repeated field it needed

Simple in C++ and not simple anywhere above it. It returns a
StorePathSet, so the Python surface is list[StorePath] - and a
method returning a list had no schema representation.

Repeated fields were the answer and they were small. wiretypes grew
list_value() beside map_value(), and both got stricter at once:
proto3 nests NEITHER container inside the other, so list[list[T]]
and dict[str, list[T]] are refused with the reason rather than
accepted and exploded at the first call. _add_field emits a repeated
field, the codec grew the encode/decode pair, and map_c_type learned
that vector[T] is list[T] - element first, so a pointer element
maps like a value one. A list of PROXIES stays refused, for the same
reason a map of them is: one lease per element, and nothing grants
leases in bulk.

Two things fell out. names_in existed in THREE copies - model,
emitter, and nowhere at all for the stub generator, which read the
head of an annotation and so would have missed the StorePath inside
list[StorePath]. It is one function in wiretypes now, which is
where the reading of an annotation belongs. And
returned_types_from_api read the return type as one name, so a type
that only ever appeared inside a container would not have been
discovered as a returned type.

What the real one is NOT tested on

Store.query_all_valid_paths is covered for the answer being a list,
for the empty case, and for the store that refuses it - dummy://
raises "not supported by store", which is nix::Store's own default and
is honest, because a substituter has no such list to give.

It is NOT covered on a store that holds anything. Two things are
missing and neither is small. Nothing in these bindings WRITES to a
store yet. And the suite runs in the build sandbox, which has no db to
read and no daemon to ask - so the loop that takes ownership of each
element never runs there. By hand against the ambient store it answers
23163 paths, twice, with a full free in between.

That second half is not specific to this method, and it gets worse
from here: an evaluator needs a store to substitute from. #574
holds it.

The mock covers the multi-element path end to end, over a real socket,
which is what it is for.

Migrated from tasks/015-real-nix-spike.md.done.


Assisted-By: Opus 5

Activity

  1. added
    source: huggorm
    on Oct 19, 2026
  2. transferred this issue fromnixidae/huggormon Oct 19, 2026
  3. added theissue type on 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