8000 API: each engine must inherit its contract, not restate it · Issue #65 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

API: each engine must inherit its contract, not restate it #65

Closed

Description

@Lillecarl

TL;DR

The two engines state the same contract twice, and 41 of 77 shared methods
state it differently. The fix is not a base class that carries code, because
there is no code to carry. The fix is to make each engine inherit its
contract from protocols.py, so a docstring exists once and a missing method
is a TypeError instead of a silent no-op.

A Protocol supports this. Protocol's metaclass is ABCMeta, so a
protocol member marked @abstractmethod enforces itself on an explicit
subclass, and still accepts an outside implementation that inherits nothing.

Why not merge the engines

A refactor to "share the method bodies" was proposed from the file sizes:
rpc/client is 5,420 lines against inproc/_impl.py at 1,798. Those numbers
do not say what they look like they say. Counted by AST instead:

count
public methods, rpc client 96
public methods, inproc 81
the same name on both 77
body lines across all 77, rpc 298
body lines across all 77, inproc 336
a single statement on both sides 21
an identical docstring on both sides 36 of 77

The bodies are one line each, and the two lines are not the same line:

# rpc/client/store.py
return (await self.rpc.is_valid_path(IsValidPathRequest(path=str(path)))).valid

# inproc/_impl.py
return await self._session.run(self._require_core().is_valid_path, str(path))

One builds a request message and unwraps a field. The other dispatches to the
thread executor. There is no shared body to lift out. The methods with a real
body are the ones where the mechanics genuinely differ: close (5 lines rpc,
12 inproc), open (1 / 7). Those are process lifetime and thread confinement,
which is exactly the thing rpc has and inproc does not.

The remaining bulk of rpc/client is not a second copy of anything. It is
_pool.py, _status_details.py, _handle_registry.py and the lease
machinery. inproc has no counterpart because it needs none.

Do not merge the engines. This section exists so the proposal is not made
again from the file sizes.

The mechanism

protocols.py today declares 6 protocols, and no engine class inherits from
any of them. Conformance is structural, proven by pyright and by
tests/nanopynix/test_protocols.py. That works, and it leaves the prose
duplicated, because a class that does not inherit cannot inherit a docstring.

Make each engine class subclass the protocol it already satisfies, and mark
each protocol member @abstractmethod. Measured on Python 3.14 with this
repository's beartype configuration:

today an ABC Protocol + @abstractmethod
the docstring is stated once, and inherited no yes yes
a missing method raises TypeError at instantiation no yes yes
a forgotten method becomes a silent None no-op n/a no no
an outside class conforms without inheritance yes no yes
beartype checks the annotation yes yes yes
isinstance cost 0.41 us 0.27 us 0.41 us

Evidence for each row:

  • type(Protocol).__mro__ is [_ProtocolMeta, ABCMeta, type, object].
  • An explicit subclass that omits an abstract member raises
    Can't instantiate abstract class Incomplete without an implementation for abstract method 'close'.
  • An explicit subclass that omits a non-abstract member inherits the ...
    body. await session.close() then returns None and leaks. This is why
    @abstractmethod is required and not optional.
  • A class that inherits nothing still passes isinstance and beartype against
    the same protocol.
  • inspect.getdoc walks the MRO, so an engine method with no docstring reports
    the protocol's. Note that __doc__ stays None; the tests and the
    documentation build must use inspect.getdoc.

Two blockers were checked and are clear:

  1. No import cycle. The runtime imports of protocols.py are
    nanopynix._typechecking and nanopynix._wire. Both are a subset of what
    inproc/_impl.py, rpc/client/session.py and rpc/client/_session.py
    already import unconditionally. models and settings, which
    protocols.py imports under BEARTYPING, are also already there.
  2. line_editors needs no redesign. It is already a @property on
    AsyncReplSession and on both engines. It becomes @property above
    @abstractmethod.

The work

1. Add AsyncSession (size: S)

Session is the entry point, and it is the one shared class with no protocol:

shared class (inproc / rpc) protocol
Value / ValueProxy AsyncValue
Store / Store AsyncStore
LockedFlake / LockedFlakeHandle AsyncLockedFlake
EvalSession / EvalSession AsyncEvalSession
ReplSession / ReplSession AsyncReplSession
Session / Session none

The 8 methods that both engines carry and no protocol declares belong to
Session, and to nothing else: capture_logs, log_stream, repl,
set_settings, settings, settings_provenance, store, subscribe. So
this is not eight scattered gaps. It is one missing protocol.

AsyncSession declares the 13 members both engines share: the 8 above plus
close, eval, get_verbosity, open and set_verbosity. It extends
AsyncVerbosityController[LogLevel], as AsyncEvalSession does, and it
declares __aenter__ and __aexit__.

2. Mark every protocol member @abstractmethod, and inherit (size: M)

Each of the 7 protocols marks its members abstract. Each engine class names its
protocol as a base:

class Session(AsyncSession): ...
class ReplSession(EvalSession, AsyncReplSession[Value]): ...

The hierarchy already lines up: AsyncReplSession extends AsyncEvalSession,
and ReplSession extends EvalSession on both engines.

3. Delete the duplicated prose (size: M)

Remove the docstring from each engine method that only restates the protocol.
41 of 77 currently disagree with the other engine. Where an engine must add
something -- the rpc timeout, for one -- keep a docstring that adds to the
protocol text and does not replace it.

Add a test beside tests/nanopynix/test_protocols.py that fails when an engine
method defines its own __doc__ without the protocol text in it. The test
names the method and both texts.

4. Hand #44 its worklist (size: S)

19 names are public on the rpc client and on nothing else. Most are not API --
they are the lease and handle machinery, reachable because nothing hid them:

child, claim, claim_eval, deactivate, defer, drain,
drain_deferred_releases, generation, handle, new_lease, nix_type,
owns, release_eval, release_locked_flake, resolve_timeout, rpc,
store_handle, value, with_timeout

4 are public on inproc only: acquire, has_pending_work,
mark_initialized, run.

On Session alone the split is run (inproc) against claim_eval and
release_eval (rpc). Each name is either a leading underscore away from being
internal, or an entry the other engine owes. That decision belongs to #44; this
issue supplies the list.

What does not change

test_protocols_declare_the_whole_shared_surface stays, and it is the most
important test in the file. @abstractmethod enforces one direction only: an
implementer must have every declared member. It cannot report that the
declaration is missing a member both engines have. That is the drift that
actually occurred -- AsyncValue declared 6 of 21 shared members, and
AsyncEvalSession 6 of 8 -- so the check that caught it must remain.

test_every_protocol_is_runtime_checkable also stays. beartype skips a
callable it cannot pass to isinstance, and inheritance does not change that.

Acceptance criteria

  1. protocols.py declares every method that both engines carry, AsyncSession
    included.
  2. Every protocol member is @abstractmethod. A test asserts this, because a
    member that is not abstract turns a missing method into a silent no-op.
  3. Every engine class names its protocol as a base.
  4. Each shared operation states its behaviour once. An engine adds to that
    statement and never replaces it.
  5. A test fails when an engine restates an operation in its own words.
  6. A test proves that a class which inherits nothing still satisfies each
    protocol, so structural conformance is not lost.
  7. The 23 asymmetric names are decided in API: the public surface disagrees with itself #44.
  8. No method body moves. This issue removes duplicated prose and declarations,
    and does not touch the transports.

Not in scope

Merging the engines, and a table that generates both sides. The measurement
above says the return would be about 200 lines, against a layer of indirection
through which pyright, beartype and a human reader all have to work. The two
engines stay two engines.

Converting the protocols to plain ABCs is also out of scope, and the table
above gives the reason: a Protocol with abstract members is a superset. It
gives the enforcement of an ABC and keeps structural conformance, which an ABC
gives up.

Refs #44

Activity

  1. changed the title [-]API: the two engines state the same contract twice, and 41 of 77 state it differently[/-] [+]API: each engine must inherit its contract, not restate it[/+] on Jul 31, 2026
  2. Lillecarl commented on Aug 2, 2026

    @Lillecarl
    ContributorAuthor

    e3a3595 lands criterion 7, the last one open. Criteria 1-6 and 8 landed earlier, each with a test in tests/nanopynix/test_protocols.py:

    criterion test
    1. every shared member declared, AsyncSession included test_protocols_declare_the_whole_shared_surface
    2. every protocol member abstract test_every_protocol_member_is_abstract
    3. every engine class names its protocol as a base test_every_engine_class_inherits_its_protocol
    4, 5. each operation stated once test_no_engine_repeats_the_protocol_word_for_word
    6. a class that inherits nothing still conforms test_a_class_that_inherits_nothing_still_conforms

    Criterion 7, and one correction to how it was framed

    This issue said each asymmetric name is "either a leading underscore away from
    being internal, or an entry the other engine owes". The second half was
    already decided and recorded.
    Every entry in test_engine_parity.py's ledger
    is marked TRANSPORT, which is that file saying no engine owes anything. So the
    open question was only ever the first half.

    Re-measured on this tree: not 23 names, but 11 ledger entries, 10 presence
    asymmetries and one parameter difference. The count in the issue body came from
    inspect.getmembers over the rpc client's classes without the pairing that
    PAIRS does, so it counted names the other engine has under a base class.

    Four had no caller outside the engine that defines them, and are private now:

    • Session.claim_eval / Session.release_eval -- add and discard the session's
      own set of open evaluators. Three internal call sites, no test, no consumer.
    • EvalSession.release_locked_flake -- LockedFlakeHandle.release is how a
      caller releases one, and it exists on both engines. Its two siblings,
      _eval_locked_flake and _write_lock_file, were already private with that
      reason written down. This was the one the rule missed.
    • Store.store_handle -- its own docstring read "Worker-side handle for
      internal session integration", which is the whole finding.

    Six stay public, and the ledger now says why rather than only what. The
    interesting one is Value.handle: it is the identity of a worker-side value, so
    a walk over an attrset can keep a visited set, and tests/pynix/test_build.py
    does exactly that. id(proxy) cannot stand in -- two proxies for one worker
    value share a handle and not an id. That is the single place in the ledger
    where a caller need can only be met by one engine.

    Store.rpc also stays, and the distinction from inproc's Store.call that #44
    deleted is worth stating: that one was call(method, *args, **kwargs) -> Any,
    and this is a typed generated service the class docstring advertises.

    One doc correction

    docs/nanopynix/decisions.md Q7 recommended the opposite direction -- that
    inproc adopt rpc's claim_eval/release_eval spelling as the cheap step
    towards removing cross-class private access. Those names are private on rpc
    now, so that step no longer exists. Q7 records why and keeps the question that
    is left.

    Cost

    Hiding the four needs nine inline suppressions for cross-class access 10000 , in the
    form this file already uses for _session_id. Recording it because it is a
    real cost paid for the change and not a free win: the facade and the
    implementation collaborate inside one package, and Python has no word for that.

    Gates

    ruff check, ruff check --config ruff-strict.toml, ruff format --check and
    pyright all clean. Ledger reconciles with no unlisted and no stale entries.
    Full suite 2044 passed, 0 failed, 4 skipped -- the pre-change baseline.

    Co-Authored-By: Claude Opus 5 noreply@anthropic.com

  3. added
    source: nanopynix
    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: nanopynix

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0