160 lines
10 KiB
Markdown
160 lines
10 KiB
Markdown
# Service ownership, lifecycle and replacement plan
|
||
|
||
Status: PLANNED feature work. Baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`,
|
||
inspected 2026-11-24. Requirements R-004, R-009, R-010 and R-013–R-016 apply.
|
||
[Architecture](../ARCHITECTURE.md) C-02–C-05 and C-09 owns shared semantics.
|
||
|
||
## Existing source baseline
|
||
|
||
[Service.hpp](../../../include/Void/Service/Service.hpp) defines
|
||
`Void::Service::IService`, with `service_name`, `on_start`, and `on_stop`.
|
||
[Registry.hpp](../../../include/Void/Service/Registry.hpp) defines
|
||
`ServiceRegistry`: type-indexed shared_ptr providers, replacement/removal, local-first
|
||
parent lookup, and registration/reverse-registration lifecycle order. `get<I>()`
|
||
returns an owning shared_ptr, but `require<I>()` returns `I&` after a temporary owning
|
||
lookup; concurrent replacement can invalidate that reference. `start_all`/`stop_all`
|
||
invoke callbacks while holding a registry shared lock. Parent lifetime is borrowed.
|
||
Lifecycle has no dependency DAG, readiness or failed-start rollback contract.
|
||
|
||
[PluginService.hpp](../../../include/Void/Service/PluginService.hpp) provides
|
||
`PluginServiceBinding<I>` using `void_plugin_service`, RTTI cross-cast validation and
|
||
an aliasing shared_ptr that retains a `PluginHandle`. Its existing generation pin is
|
||
valuable; C linkage for the factory does not make the returned C++ IService stable
|
||
across toolchains. [module.cmake](../../../src/Service/module.cmake) declares Functional
|
||
and Log, while the optional plugin bridge's includes reach Plugin. Packaging that
|
||
bridge separately is part of the target dependency cleanup, not a reason for Plugin
|
||
and Service core to depend cyclically on one another.
|
||
|
||
Existing [registry tests](../../../tests/standalone/Service/Registry.cpp) cover provider
|
||
lookup/replacement/removal and lifecycle order;
|
||
[scoped tests](../../../tests/standalone/Service/ScopedRegistry.cpp) cover parent
|
||
fallback/shadowing; [orchestrator tests](../../../tests/standalone/Service/Orchestrator.cpp)
|
||
exercise consumers in Fsm. Graph paths were coverage-checked; PluginService line 52
|
||
was directly read. Important callback and ownership conclusions were source-verified.
|
||
|
||
## NEW owning API and registry model
|
||
|
||
Design sketch; these additions are not existing declarations:
|
||
|
||
```cpp
|
||
namespace Void::Service {
|
||
template<class I> class ServiceHandle { // owns provider and code pin
|
||
public:
|
||
I* operator->() const noexcept;
|
||
std::uint64_t generation() const noexcept;
|
||
};
|
||
// NEW registry methods:
|
||
// acquire<I>() -> Result<ServiceHandle<I>>;
|
||
// prepare_batch(ProviderSet, ExpectedEpoch) -> Result<PreparedPublication>;
|
||
// publish(PreparedPublication&&) -> Result<PublicationEpoch>;
|
||
// start(options) / close_and_join(options) use Async::OperationOptions.
|
||
}
|
||
```
|
||
|
||
ServiceHandle owns an immutable provider record: interface pointer, shared provider
|
||
owner, generation pin and publication epoch. Copies extend lifetime. Acquisition of
|
||
an absent provider returns `missing_service`; a stopped admission gate returns
|
||
`service_stopping`. The handle is held across an entire call/await. Removing a registry
|
||
entry prevents new lookup but never invalidates acquired handles or releases plugin
|
||
code while a continuation is active. Provider retirement is distinct from destruction.
|
||
|
||
Use immutable registry snapshots and one atomic retained-snapshot pointer. A batch
|
||
publication atomically replaces all interfaces belonging to a generation; a request
|
||
needing a coherent group acquires one snapshot. Type-index keys remain same-toolchain
|
||
only; stable C interface IDs and version negotiation belong to [Plugin](Plugin.md).
|
||
ProviderSet rejects duplicate interface IDs, null providers, missing required
|
||
dependencies and cycles. Aliases of one lifecycle object have a single lifecycle node.
|
||
|
||
The base registry is native standard containers/shared ownership, without Runtime,
|
||
Plugin or a concrete telemetry dependency. Async lifecycle support and the plugin
|
||
binding are higher adapters. A child snapshot retains its parent snapshot, so it can
|
||
outlive the parent registry object; new parent publications are observed only through
|
||
explicit child refresh/new acquisition policy. Choose snapshot parent semantics for
|
||
NEW scoped handles and document the difference from today's live borrowed fallback.
|
||
|
||
## Startup, rollback and safe replacement
|
||
|
||
Provider descriptions declare stable local service IDs and required/optional edges.
|
||
Topologically sort required edges with registration sequence as a deterministic tie
|
||
break. Prepare a retained lifecycle snapshot under a short guard, then release the
|
||
guard before invoking any application callback. Lifecycle operations are serialized
|
||
by a coordinator state machine; ordinary lookups do not wait for callback execution.
|
||
Reentrant lookup is supported. Reentrant lifecycle mutation queues a bounded request
|
||
for the next epoch rather than recursively starting/stopping services.
|
||
|
||
Start transitions constructed → starting → ready. A provider's start/ready call may
|
||
fail; then stop every provider whose start succeeded in reverse dependency order.
|
||
Also call the failed provider's specified abort-start cleanup to release partial work.
|
||
Aggregate cleanup errors while retaining the original startup error. Providers are
|
||
unpublished until the required set is ready. Legacy void callbacks adapt by catching
|
||
exceptions at the C++ boundary and mapping them into structured failures.
|
||
|
||
Replacement prepares candidate providers in a private snapshot and validates readiness
|
||
before publication. ExpectedEpoch prevents stale concurrent replacements. The publish
|
||
guard performs only a preallocated pointer swap; the old snapshot is retired outside
|
||
the guard so final shared_ptr destruction cannot run user destructors under a lock.
|
||
Notification callbacks run outside locks. A failed candidate keeps the old snapshot.
|
||
Publication success is not a durable Update commit; that belongs to VersionStore.
|
||
|
||
Retired providers stop admitting new mutations when their owner requests quiescence,
|
||
while existing handles remain valid for their documented operations. Their owned Async
|
||
scope drains before `on_stop`/destruction. Do not call stop merely because a newer
|
||
provider was published if that would invalidate an acquired handle. A retired-generation
|
||
coordinator retains cleanup responsibility until all calls and async pins end. Stateless
|
||
readers may overlap generations; stateful writers require Plugin's quiescence protocol.
|
||
Shutdown stops publication and lookup admission, stops dependents before dependencies,
|
||
joins their work, then releases owners. Noncooperative work yields a shutdown report
|
||
and keeps owners retained; a deadline never licenses freeing live providers.
|
||
|
||
## Bounds, failures and observability
|
||
|
||
Default 256 providers/registry, 16 parent levels, 1,024 dependency edges, 64 staged
|
||
changes, 128 lifecycle requests and four retained publication generations. Admission
|
||
over these limits returns overload before invoking callbacks. At most one lifecycle
|
||
transaction prepares per registry; concurrent requests have expected-epoch conflicts
|
||
or bounded waiting using [Async](Async.md) options. Retention exhaustion refuses new
|
||
replacement until pins drain. No forced eviction of old code or provider objects.
|
||
|
||
Errors distinguish missing, conflict, cycle, start failure, not-ready, stop failure,
|
||
cancelled, timed-out and retained-generation limit. Emit optional bounded observations
|
||
for epochs, retained handles, callback duration and rollback outcomes, with
|
||
[Observability](../subsystems/Observability.md) adapters above the registry. Do not log
|
||
configuration payloads or capture transient thread-local context. Stable interface IDs
|
||
are not authorization; application policy controls which providers may be registered.
|
||
|
||
## Ordered implementation backlog
|
||
|
||
Every row is PLANNED.
|
||
|
||
| ID | Phase / depends on | Intended scope | Acceptance / recommended role |
|
||
| --- | --- | --- | --- |
|
||
| M-SERVICE-01 | P0 / baseline | Characterize borrowed require, lock-held callbacks, parent and alias lifetime; package bridge map | Regression cases distinguish owning get from borrowed require; declared dependencies recorded / sol_implementer |
|
||
| M-SERVICE-02 | P1 / M-SERVICE-01; Functional error gate | Owning handles, immutable snapshots, retained parents, atomic provider batches | Old handles survive remove/replace/parent destruction; batch readers see one epoch / astra_implementer |
|
||
| M-SERVICE-03 | P2 / M-SERVICE-02; Async scopes | Dependency lifecycle coordinator, readiness, failed-start cleanup and reverse rollback | Callback can acquire services without deadlock; middle-node failure leaves nothing newly published / astra_implementer |
|
||
| M-SERVICE-04 | P2 / M-SERVICE-03; Plugin pin gate | Separate plugin bridge adapter, staged publication, retired-provider drain | In-flight async call pins exact generation through completion; no callback/destructor under registry guard / astra_implementer |
|
||
| M-SERVICE-05 | P3 / M-SERVICE-04; Configuration snapshot gate | Bounded retention, Runtime/Fsm composition and migration | Retention saturation rejects reload; shutdown joins dependency graph and reports incomplete owners / sol_implementer |
|
||
|
||
## Validation, performance and migration
|
||
|
||
CURRENT aggregate command:
|
||
`ctest --test-dir /tmp/voidlibrary-discovery-f1f9ba3 --output-on-failure --timeout 60`;
|
||
not rerun here. PROPOSED tests require NEW APIs: concurrent remove/acquire, provider
|
||
destructor reentering registry, start callback registering another service, duplicate
|
||
lifecycle aliases, parent destruction, dependency cycles, readiness timeout, second
|
||
provider start failure, stop throws, reader held across four reloads, and async callback
|
||
completion after publication. Lifetime/race sanitizers supplement deterministic barriers.
|
||
|
||
Measure acquisition and publication p50/p95/p99, lookup throughput under read/write
|
||
contention, allocations, retained provider RSS/CPU, shutdown latency and template build
|
||
cost per [PERFORMANCE](../PERFORMANCE.md). Compare immutable snapshots with the existing
|
||
shared-mutex path using identical service sets; do not assert universal improvement.
|
||
|
||
EXISTING `auto& svc = registry.require<I>();` migrates to NEW
|
||
`auto svc = registry.acquire<I>();` and retaining `*svc` through the call. Existing
|
||
`get<I>()` remains a safe ownership bridge for simple same-toolchain providers.
|
||
Deprecate borrowed require before removal at the major boundary. Legacy registration
|
||
order is retained in the no-dependency adapter; dependency-aware startup is explicit.
|
||
Never roll back a published generation by destroying live handles: publish another
|
||
validated snapshot. See [MIGRATION](../MIGRATION.md), [VALIDATION](../VALIDATION.md),
|
||
[Runtime](../subsystems/Runtime.md), [Fsm](Fsm.md), and [DELIVERY](../DELIVERY.md).
|