Skip to content

Registration and discovery

How a node service announces itself to the platform (2.40.0): the Consul service and its namespaced id, the KV keys that carry the schema envelope and the static configuration, the registration monitor, the bootstrap retry budget, the process-wide shared registry client, and how the node engine turns those records into the palette and into a resolvable endpoint at configure time. The node-author checklist is Deploying on an engine; the schema fields are in Schema file reference.

Custom application services (2.44.0)

set_grpc_services() installs an explicit startup registration set. Each GrpcServiceRegistration combines an author-owned generated service descriptor, generated binder, and factory receiving the configured NodeServiceConfig. start_grpc_service() freezes that set, checks fully qualified names against framework reservations, constructs instances, validates/attaches generated handlers, and enables reflection before starting the listener. Validation uses public descriptors and gRPC handler interfaces, not private server collections.

Python's node-list guard permits zero nodes only when custom application services are registered. The controller receives an empty list and registers no fake capability. Existing NodeServiceBase hooks and node registry behavior remain.

Public methods use descriptor-qualified paths; the JWT interceptor and its existing public v1alpha reflection exception remain active. Factories/binders that fail or register inconsistent handlers abort startup. There is no hot registration or catch-all transport RPC.

C++ setGrpcServices() and the three-argument NodeManagerService::run() own synchronous generated services through shutdown. GrpcServiceRegistration::create uses the generated service type to couple its factory and descriptor, and since SDK 2.47.0 takes an Authentication policy first. gRPC 1.73 offers no supported hook to stop a synchronous handler on insecure credentials, so the host cannot replace Python's interceptor: InHandlers services call authenticate(context) in each handler, None services log a startup warning. Existing two-argument run() remains available. Reflection and TLS/mTLS remain native server facilities. The application must link its generated descriptors.

neuraverse-generate-protos is the shared build-time command implemented in neuraverse_sdk/proto_codegen.py. The wheel exports a console entry point and the Dockerfile installs the same standard-library-only script in /usr/local/bin for native builds and downstream applications. Python invokes the current interpreter's grpc_tools.protoc; C++ invokes the native compiler/plugin selected by the caller. This does not change runtime registration or contract ownership.

Custom service lifetime is independent of StopExecutionNode, StopAndCleanupNode, and the deprecated StopNode. Whole-host shutdown drains gRPC for five seconds before cancellation while instances are still owned. The sample's in-memory store resets on restart. The SDK inherits entities 2.58.0 from main; custom services require no additional entities, engine, or command-stream contract changes.

Python run() captures the registered NodeServiceBase class and invokes on_shutdown() once when bootstrap unwinds, after the gRPC drain and before asyncio joins its executor. This order lets the hook stop service-owned watches that keep executor workers alive. A fallback covers interruption before the bootstrap coroutine starts. SIGTERM starts unwinding and subsequent SIGTERMs are ignored during shutdown. The synchronous hook also runs on normal return, Ctrl+C, and startup failure; an exception is logged and sets exit status 1. Forced exit remains in the outer finally, including if cleanup or output flushing fails. Node stop/cleanup RPCs never invoke this host-level hook.

The shared wire_tests/custom_services suite launches real Python/C++ hosts, uses generated clients and reflection, and supplies a controlled JWKS peer. Only the example database is replaced with an in-memory store. Existing in-process routing tests do not substitute for this boundary.

What happens at startup

sequenceDiagram
    participant R as node_manager_service.run
    participant C as NodeController / NodesRegistry
    participant N as NodeBase instance
    participant P as ServiceRegistryRepository
    participant S as ServiceRegistryClient (shared)
    participant K as Consul agent
    R->>C: DI wiring: NodeController(...)
    C->>N: add_node_class: instantiate, register_node(config)
    N->>N: get_schema(), _build_schema_envelope(), static configurations
    N->>P: ServiceRegistryRepository(endpoint, retry settings)
    P->>S: _get_shared_client((endpoint, token))
    P->>S: register_node(endpoint, class name, configs, namespace, envelope)
    S->>K: agent.service.register(name, id, address, port, TCP check, meta)
    S->>K: kv.put(capability/.../configurations)
    S->>K: kv.put(available-nodes/.../schema)
    S->>S: start ConsulHealthCheck monitor (once per client)
    R->>R: then service.start(): gRPC and HTTP servers

Registration runs inside NodeController.__init__ during dependency-injection wiring, before service.start() opens the gRPC and HTTP ports (node_manager_service.py). NodeBase.register_node(node_service_config) (node_base.py) stores the config and calls the private __register_service(), which:

  1. Returns with a warning when registry_config.registry_endpoint is empty (no registration, no error).
  2. Picks the advertised endpoint: registry_config.node_cluster_target when set, otherwise grpc.address:grpc.port.
  3. Builds the static configuration map (node_external_target, is_remote, node_deployment_host, see below) and the schema envelope.
  4. Creates a ServiceRegistryRepository with the retry settings from RegistryConfig and calls register_node(node_endpoint, capability_name=<ClassName>, node_configurations, namespace=registry_config.node_namespace, schema_envelope).

ServiceRegistryRepository.register_node() (controllers/service_registry_repository.py) validates the endpoint with a host, optional port, optional path regex and wraps every failure, including an invalid endpoint, in NodeRegisteryError. NodesRegistry.bind_node_instance_with_id() calls register_node() again whenever it mints a fresh instance (a second node of the same class in one graph, or the re-init after a stop), which is an idempotent overwrite in Consul.

The Consul service

ServiceRegistryClient.register_node() (api/consul/clients/service_registry_api.py) registers with consul.agent.service.register:

Field Value
name capability-<ClassName> (the Python class name, which is also schema.executionContext.className)
service_id capability-<ClassName>-<namespace> and, when the envelope has a container, capability-<ClassName>-<namespace>-<container>. Passed only when a namespace is set; without one the id equals the name.
address, port Split from the advertised endpoint
check consul.Check.tcp(check_address, check_port, interval="10s", timeout="5s", deregister="1m"). The check target is node_external_target (host:port) when the static configuration carries one, otherwise the registered address and port.
meta node_external_target always; with a namespace also namespace, container, name (the schema name) and version.

The namespaced id is what lets the same class run on the gateway and on several edge devices, or ship in two node containers on one host, without overwriting itself in a central registry. RegistryConfig.node_namespace defaults to gateway. The node's identity in the registry is its schema name; the class name appears only in the service name and in executionContext.className, which the engine uses to resolve capability-<ClassName> at configure time. Instances registered by SDKs older than 2.27.0 carry no name meta, so readers fall back to the class name embedded in the service name.

KV layout

Two blobs are written per registration, after the service call:

Key Written by Content
available-nodes/<namespace>/<container>/<name>/schema, or available-nodes/<namespace>/<name>/schema when the container is empty _store_schema_in_kv(); skipped without a namespace or without an envelope The envelope built by NodeBase._build_schema_envelope(): namespace, container (from container_name), name (schema name, class name as fallback), version (node_version class attribute or the service descriptor version, 1.0.0 as last fallback), node_cluster_target, node_external_target, and schema (the Node proto as a dict, empty when get_schema() failed).
capability/<service_name>/<namespace>/<container>/configurations, capability/<service_name>/<namespace>/configurations without a container, or the flat capability/<service_name>/configurations without a namespace _store_configurations_in_kv() JSON of the static configuration map with each NodeConfigEntry rendered by MessageToDict(preserving_proto_field_name=True).

The static configuration map (NodeBase.__get_static_configuraions) contains exactly three entries: node_external_target (string, from registry_config.node_external_target), is_remote (toggle, False; the engine recalculates it) and node_deployment_host (string, the registry endpoint). The schema's own configuration block is not part of it; it lives inside the envelope's schema.

The configuration blob is keyed like the schema blob. Before 2.39.1 every registration wrote the flat capability/<service_name>/configurations, so devices running the same class raced for one key and the last registrant won. Un-namespaced registration keeps the flat key. No engine, proxy or studio code reads this blob (they resolve nodes through the Consul service Meta), so only external tooling reading it directly needs the new path.

Registration monitor

Every shared client runs at most one daemon thread named ConsulHealthCheck, started by the first successful registration (_start_health_check_monitoring, guarded by a lock because registrations arrive from concurrent gRPC workers). Each cycle, every 30 s:

  1. One agent.services() call covers every registration the client tracks in _registrations (keyed by service id).
  2. A transport or HTTP error (Consul down, 429) is inconclusive: the worker backs off (5 s doubling to 60 s) without re-registering, because re-registration traffic against an already rate-limited agent sustains the flood it is recovering from.
  3. A registration that Consul answered about but does not list is re-registered with _do_register(), including both KV writes; success resets the backoff.

stop_monitoring() and unregister_node() exist for tests and controlled teardown only. NodeBase.stop() deliberately does not touch the monitor: the registration belongs to the running service, not to one instance, and stop() also runs on every graph re-init. (2.29.1 fixed the per-instance stop chain that used to kill the monitor and lose the capability permanently after a Consul restart.)

Since 2.49.0 the monitor also feeds the liveness probe (consul_monitor in /health/live, Check(service="liveness")): when a registry endpoint is configured and a node registered, liveness fails if the monitor thread is no longer running, because nothing else would re-register the node. The probe reads the thread state only and never calls Consul. The Consul check itself stays TCP on the gRPC port. See specifications/prompts/260-service-health.md.

Bootstrap resilience

A Consul agent that is not listening yet no longer wedges the node process. The first registration on a client (bootstrap, detected as "the monitor is not running yet") retries errors that mean the agent could not be reached, requests.exceptions.RequestException, consul.ConsulException and OSError, with exponential backoff: initial registry_config.registration_retry_delay_s (default 2 s, env NEURAVERSE_CONSUL_REGISTRATION_RETRY_DELAY_S, floored at 0.1 s), doubling to a 60 s cap, for up to registry_config.registration_timeout_s (default 120 s, env NEURAVERSE_CONSUL_REGISTRATION_TIMEOUT_S; 0 fails on the first attempt). A falsey register response or a malformed endpoint is a defect and surfaces immediately.

When the budget runs out the exception propagates, the registration is not recorded in _registrations and the monitor is not started, so nothing can later advertise a port that nothing serves. Registrations after bootstrap (instance churn, servers already up) are recorded first and attempted once; a transient failure there is left to the monitor. run() catches the propagated error, logs it, and exits the process with code 1 through os._exit after flushing logging (0 on a clean return or KeyboardInterrupt), turning a failed bootstrap into a container restart. Before 2.38.0 the failed process stayed alive with no gRPC server while the monitor re-registered a dead endpoint every 90 s.

The brief is specifications/prompts/240-service-registry-resilience.md; the scenarios are specifications/specs/service-registry/ (bootstrap waits for Consul, registration after bootstrap, failed bootstrap ends the process), run by tests/specs/test_service_registry_specs.py.

One shared client per (endpoint, token)

ServiceRegistryRepository is created per node instance, but it obtains its ServiceRegistryClient from a process-level cache keyed by (endpoint, token) (_get_shared_client, controllers/service_registry_repository.py). One client owns one Consul HTTP session and one monitor thread and tracks all of the process's registrations. The retry settings of the first caller stick, since only the first (bootstrap) registration uses them. Before 2.31.1 every instance minted its own client and monitor, and instance churn on each graph stop and re-init cycle accumulated keep-alive connections until Consul's per-IP http_max_conns_per_client limit (default 200) turned every call into HTTP 429 (NRV-10272). _reset_shared_clients() is the test hook that stops all monitors and clears the cache; tests/test_service_registry_shared_client.py pins the behaviour.

Engine side: aggregation and configure-time resolution

The statements in this section describe the node engine (neuraverse-node-engine), not this SDK; they are checked against the engine source at the time of writing and against MIGRATION.md and CHANGELOG.md (2.27.0), and can drift independently of the SDK.

  • GetAvailableNodes reads the catalog for each capability-* service, takes name, namespace, container, version and node_external_target from the service Meta, and loads the envelope from the KV key above (available-nodes/<ns>/<container>/<name>/schema, or without the container segment), logging a warning when it is missing. Instances with the same (container, name) are grouped into one palette entry with one selectable location per namespace; the engine's own namespace sorts first and is the default. The selectable locations are delivered as a comma-separated value in the schema's configuration.node_namespace (for example gateway,robot1), which is why the schema file itself must not declare node_namespace, node_deployment_host or is_remote.
  • At configure time the engine normalizes the node's node_namespace back to one location (a list falls back to the first entry), resolves capability-<className> for that namespace through the registry, fails with No 'capability-<Class>' instance registered under namespace '<ns>' when nothing matches, computes is_remote as "namespace differs from the engine's own", writes both is_remote and the chosen node_namespace back onto the node configuration, and picks the internal endpoint or, for a remote node, node_external_target. The namespace pairing also drives the per-connection transport choice described on Transports.
  • Minimum versions for discovery are SDK 2.29.1 and engine 2.13.0 (MIGRATION.md); 2.27.x and 2.28.x SDKs have the monitor bug fixed in 2.29.1.

Local verification

With the localstack (~/Neuraverse/localstack on dev machines: start_infra.sh with Consul on host networking, run_engine.sh, plus a run_node_*.sh per node repo), after starting the node service:

# the service instances, with Meta and the namespaced ServiceID
curl -s localhost:8500/v1/catalog/service/capability-<ClassName> | python3 -m json.tool

# the schema envelope the palette is built from
curl -s 'localhost:8500/v1/kv/available-nodes/gateway/<container>/<Name>/schema?raw' | python3 -m json.tool

# the static configuration blob (2.39.1 layout)
curl -s 'localhost:8500/v1/kv/capability/capability-<ClassName>/gateway/<container>/configurations?raw' | python3 -m json.tool

Then call GetAvailableNodes through the engine (or refresh the UI palette) and verify the node appears once, under the category from its schema id, with configuration.node_namespace listing every location where the container runs. The expected startup log order is Registering node 'capability-<Class>' with Consul, Registered instance capability-<Class> ..., Node <Class> registered per class, then gRPC server thread pool size: N and Serving HTTP.

Version notes

Version Change
2.27.0 Schema self-registration: get_schema(), namespaced service id, extended meta, envelope in KV.
2.29.1 stop() no longer stops the registration monitor.
2.31.1 One shared client per (endpoint, token); tristate registration check.
2.38.0 Bootstrap retry budget; failed bootstrap exits the process.
2.39.1 Namespaced configuration key.