8000 The declaration becomes the only source · Issue #602 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

The declaration becomes the only source #602

Closed

Description

@Lillecarl

DONE, all four phases. The plan for #601. Carl: "ditch the IR in favor of
using the Python DSL decl as the source of truth always, this will
need us to make helpful functions for both analyzing the AST and
importing to get full type information."

One correction to 064 first

064 says the first step is to teach the declaration the wire facts,
because wire.py calls them "out of the manifest, which got it from
a _wire / _wire_fields"
.

That is no longer true, and it changes the size of the job. Read
cppgen/manifest.py:entry(): it takes a DSL Class and derives
wire, wire_fields, threading, the service names, the whole
entry. pygen/generate.py then takes that dict WHOLE, through
declared_entries(). No class fact is reflected any more.

What actually happens is a round trip:

decl/pathinfo.py
  -> nbemit writes  cls.attr("_wire_fields") = ...   (a C++ string)
  -> the C++ compiler
  -> import huggorm_bindings
  -> getattr(cls, "_wire_fields")
  -> manifest.json
  -> run time

The declaration states the fact at the top. The bottom reads it back
off a compiled object. Every step between is a courier.

What pygen still reflects, and where each fact is declared

Six sites, and five of them read something cppgen itself emitted:

site in pygen reads already declared in
_wrapper_classes classes with _threading every NANOBIND decl
_enum_classes str+Enum subclasses decl/words.py
_free_functions module-level callables nbemit.public
extract_enum members and doc decl/words.py
extract_errors the hierarchy, _wire_fields decl/errors.py
getattr(bindings, name) a type object, for its name declared_returned()

So the compiled extension answers nothing a declaration does not
already say. It is used to ENUMERATE, and the enumeration is a list
this repo wrote.

Two facts are the exception, and both live in the one hand-written
file in huggorm-bindings:

  • _errors_module - which module holds the exceptions
  • _async_twins - {"pathlib.Path": "anyio.Path"}

They are the whole gap. Not the wire facts.

One more thing found while reading: _wrapper_classes excludes a
class with _async = False. Nothing emits _async. That filter is
dead, left from the deleted mock.

The plan, in four phases

Each phase leaves the tree green and states the perturbation that
proves it.

0. A corpus, not a loop over a list - DONE

Five functions in cppgen/generate.py open with the same three
lines - for name in NANOBIND: mod = read(DECLARATIONS / name). Each
one then re-derives what it needs. read() answers about ONE file,
and cross-file names arrive through a uses dict each caller walks
itself.

Add the missing type: a set of declarations, read once, that answers
the questions an emitter asks. classes, unions, functions,
enums, errors, returned, and by_name across the whole set.

It belongs in huggorm-dsl, beside read.py, because "a set of
declarations" is a fact about the language. huggorm-decl builds the
instance from its own lists, which is where those lists already are.

This is the "helpful functions" Carl asked for, and it is the phase
that makes the next three small.

Pure refactor. Nothing about the output changes.

Proof: the emitted tree is byte-identical before and after.

1. The last two markers move into declarations - DONE

_errors_module is derivable: ERRORS = "errors.py" already names
the declaration, and PACKAGE already names where a module lands.

_async_twins needs one new word in the DSL. It is keyed by a
FOREIGN type - pathlib.Path - so it is not a decorator on a
declared class. A module-level table in a declaration fits, the way a
union alias already does.

Then huggorm_bindings/__init__.py is emitted, and the leaf holds no
hand-written source at all. huggorm/__init__.py's thirty re-export
lines - 064's runner-up - are the same emitter and go with it.

Proof: delete a re-export by hand; the next build puts it back.
Remove a class from a declaration; the name leaves both __init__
files.

2. pygen stops importing the compiled extension - DONE

Replace all six sites with corpus queries. Delete the dead _async
filter.

The consequence is the point. huggorm-generated stops build-
depending on huggorm-bindings. The two leaves become siblings
rather than a chain, they build in parallel, and a change to the
Python surface stops waiting on a C++ compiler.

One decision this phase forces. check_error_contract BUILDS an
error and reads its parts back, to prove cls(*parts) round-trips.
That is a real runtime check, not reflection standing in for a fact.
It moves to the suite, where importing the compiled package is
honest. It does not move to run time.

smoke_test.py keeps its imports. It is a GATE - it compares what
was emitted against what compiled - and that is the one job import
reflection is right for.

Proof, and it is the strong one: build huggorm-generated with
huggorm_bindings not installed. An ImportError cannot be
faked. If it builds, the reflection is gone.

3. The manifest dies, because nothing needs a courier - DONE (3b)

This phase is much smaller than 064 and this file first claimed,
and the correction is measured rather than argued.
Carl asked the
right question: "obviously there has to be some Python glue that
wraps up the generated raw bindings"
. There does, and almost all of
those four files ARE that glue.

The measurement

server.py  441 code lines    94 of them manifest-driven
wire.py    360               4 tables, built in __init__
remote.py  300               2 lookups, both name-keyed
faults.py  190               1 table, built in __init__
----------------
           1291 code lines, 12 sites that read the manifest

So 064's "server.py alone is about 500 lines of it" is wrong.
server.py is 441 lines and 94 of them - _service, _acquire,
_free_service - build handlers from the manifest. The other 347 are
the handle table, the leases, the fixed Session service, serve()
and the sweeper. None of that names a type or ever could.

The line, and it is CLAUDE.md's own

A RUNTIME does the same thing for every type: walk a list, fill a
map, hold a handle, run a lease, encode a scalar, keep a thread. It
needs no per-type knowledge, so there is nothing in it a declaration
could state. That is a HELPER in the C++ sense, and it stays
hand-written.

A MAPPING says "this Python name means that wire call". That is the
generated code, in Python exactly as in C++.

manifest.json is a mapping table in JSON, interpreted by a runtime.
Phase 3 does not delete the runtime. It moves the mapping out of JSON
and into emitted Python.

The client already does this

rpc.py carries _rpc per class - the call spec, emitted inline as
a dict literal - and remote.invoke() says so itself: "Nothing is
resolved here - the build already did it."
So remote.py is already
a runtime. Its two remaining manifest reads are acquire(cls_name)
and call_function(name), which are the by-NAME entry points: a
directory lookup, not a per-call interpretation.

The server is the half that was never done. Dispatcher.__init__
loops the manifest and builds one closure per method, and that
closure reads proto["rpc"]["req"], proto["params"] and
proto["return_type"] at call time.

So phase 3 is: make the server look like the client already does,
and emit wire.py's four tables and faults.py's one as Python.

The design question, which is Carl's

rpc.py's _rpc is emitted Python holding a dict literal. That wins
one of the two prizes and not the other:

  • won - the table ships with the code that reads it, so
    check_manifest has nothing left to defend against. Its own
    comment is the reason it exists: "A manifest from another
    generator would not fail here - it would answer wrong, one lookup
    at a time."
  • not won - it is still dict[str, Any], so --strict still
    proves nothing about any of it.

Two ways to finish, and it is a real choice:

3a, small. Emit every table and spec as a Python literal, the way
rpc.py already does. Delete manifest.json, check_manifest and
grpc_pb.load_manifest. Mechanical, low risk, changes no signature.
Keeps dict[str, Any].

3b, real. Emit the CALL. The server gets one real async def per
RPC with its types spelled, and the client's _rpc dicts go away
with it. Typechecked end to end, and the four files shrink to the
runtime they should have been. Much larger.

3a is a step toward 3b rather than a detour: both need the same
emitter, and 3b is 3a with the spec inlined into a body instead of
into a dict.

grpc_schema.pb STAYS either way. It is the descriptor set, for
reflection and for building messages. It is not a mapping table.

Proof: manifest.json deleted from an installed
huggorm_generated, and the library run against it. PKG resolves,
the codec builds its 15 kinds, 2 enums and 2 unions, and the
dispatcher builds all 53 rpc handlers.

What 3b turned out to be

Carl chose 3b: "emit real Python. The emitted code should be correct
Python that passes static type checking and provides autocompletion
for people who consume the project as a library."

The consumer surface already met that. The protocols, the async
wrappers and the RPC classes carried real signatures, real return
types and the declaration's own docstrings before any of this. What
was untyped was everything a caller never sees.

Where the Any actually was. Six tables, all dict[str, Any]
off a JSON load: the client's _rpc specs, the server's six, the
codec's four, the fault codec's two. Emitting them as frozen
dataclasses is what a checker can read - proved by emitting
Arg(1, "int") and watching zuban --strict answer "Argument 1 to
Arg has incompatible type int; expected str"
. A dict could not
produce that error.

Emitting the call BODY would have been wrong, and this is the one
place the plan was.
3b was written as "one real async def per
RPC"
on the server. The server's handler body is a RULE - decode the
arguments, call the method, encode the result - and it reads the same
for all fifty-three. Emitting fifty-three copies restates that rule
fifty-three times, which is what goal 3 in CLAUDE.md forbids. What is
per-method is the SPEC, and that is what the build emits.

The client is the opposite case and that is why it emits methods: a
method's SIGNATURE differs per method, and the signature is the
autocompletion surface.

One statement per call. The specs first landed in rpc.py, which
made them the client's; the server then built the same specs a second
time. They live in _policy.py now and both ends import them, so the
two halves of one call cannot disagree about its shape.

Two facts that looked like one. Acquire.required is ARITY and
Acquire.optional is proto PRESENCE. Conflating them broke
Store("auto") - caught by the suite as "Field
Store_AcquireReq.uri does not have presence"
.

The manifest survives as the build's report. It is not an IR and
not a dispatch table; the suite reads it to hold OTHER artifacts up
against - the descriptor set, the front door's __all__, the stubs.
load_manifest moved into conftest.py, so the library ships no
reader at all. check_manifest is deleted: it defended against a
file from another generator, which mattered only while something
dispatched on one.

Why the order cannot change

Phase 3 emits a dispatcher, so something must READ the declaration to
write it. Today those facts still arrive by reflection. Do 3 before 2
and the reflection is not removed - it is moved to run time, which is
the worse of the two.

Phase 2 needs phase 1, because two facts have no declaration yet.
Phase 1 is easier to get right after phase 0, because the emitter for
an __init__ wants the whole set at once.

What happened

Phases 0 to 2 landed in six commits. Three things came out different
from the plan, and each is worth the next reader's attention.

The corpus paid twice. read() calls over a full emit went from
265 to 45, but only after corpus() itself was cached. A Corpus
caching within itself bought nothing: pygen calls the six declared_*
functions once each, so six instances read the same nine declarations.
The remaining 45 are read()'s own _uses recursion, which a Corpus
cannot see. That is the next easy win if one is wanted.

Two facts were stated twice, not one. Renaming the errors
declaration to prove errors_module() was load-bearing exposed a
second statement of the same fact, introduced in the same commit:
main() wrote "errors.py" hardcoded while errors_module() derived
the stem. The perturbation found it; reading the diff had not.

_async_twins had a better home than the plan guessed. The plan
said it needed a module-level table in a declaration, because it is
keyed by a foreign type. It is keyed by a VOCABULARY WORD:
Path = Annotated[pathlib.Path, Cxx("string")] in declare.py. So
Async("anyio.Path") sits beside Cxx("string") and the two
spellings of one word are together. Cxx says how a word is spelled
below the boundary; Async says how it is spelled above one.

The wrapper set and the function set needed no derivation at all.
The plan listed six reflection sites to replace. Three needed a new
derivation - enums, errors, bases. The other three were enumerating
what declared_entries and declared_functions already answered,
name for name.

The gate is in packages/huggorm-generated/setup.py: an assertion
that huggorm_bindings is absent from sys.modules once generation
has run. Absence of the PACKAGE would prove nothing - it is
propagated, because the emitted wrappers import it at run time - so
what is checked is that nothing reached for it. Perturbed by adding
one import huggorm_bindings to pygen.

huggorm-bindings has left huggorm-generated's build-system. The
two leaves are siblings, not a chain.

What is NOT in scope

The huggorm / huggorm-generated package boundary. 064 notes it
moves once server.py is mostly emitted. That is a consequence of
phase 3, and it is a separate decision after the sizes are known.

Migrated from tasks/065-the-declaration-becomes-the-only-source.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