Skip to content

Commit 4f64253

Browse files
authored
Merge pull request #164 from LimiNode/feat/config-registration-contract
docs(architecture): define atomic configuration registration
2 parents e837a17 + 21c3fbb commit 4f64253

3 files changed

Lines changed: 312 additions & 2 deletions

File tree

Lines changed: 307 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,307 @@
1+
# ADR 0010: Atomic registration of prepared configuration batches
2+
3+
- Status: Proposed
4+
- Date: 2026-11-12
5+
- Last revised: 2026-11-20
6+
7+
## Context
8+
9+
`prepare_configuration()` produces a complete `ConfigurationPreparedSet`.
10+
Each entry owns an `ILogger` and an `ILogFormatter` through `std::shared_ptr`,
11+
and the prepared result is copyable. Shared lifetime does not imply that these
12+
objects support concurrent use or registration in multiple strategies.
13+
The live `Logger` registry currently stores each pair in `LoggerStrategy` as
14+
`std::unique_ptr` and exposes `add_logger()` for one-at-a-time registration.
15+
16+
Converting a shared pointer to a unique pointer through `get()` would create
17+
double ownership or dangling references. Registering entries one by one would
18+
also publish a partially applied configuration if a later entry is invalid.
19+
Each `LoggerStrategy` has its own `exec_mx`. Registering the same backend or
20+
formatter in two strategies could bypass serialization for a non-concurrent
21+
object and call the same backend's `shutdown()` twice. The existing
22+
copy-on-write strategy snapshot must remain the dispatch publication boundary.
23+
24+
The existing `add_logger()` also appends to `m_loggers` before allocating its
25+
dispatch snapshot. Allocation failure can therefore leave the mutable registry
26+
ahead of the snapshot. The implementation follow-up must fix this existing
27+
exception-safety defect as part of a consistent registry publication contract.
28+
29+
## Decision
30+
31+
This ADR specifies future implementation, not an API delivered by this PR.
32+
Add a separate configuration-registration layer with a complete prepared set,
33+
explicit registration options, diagnostics, and a caller-visible result. Keep
34+
parsing, binding resolution, and broad dispatcher refactoring outside this
35+
slice. Preserve the existing `Logger::add_logger()` signature and observable
36+
successful append behavior.
37+
38+
### Append-only registration and identity
39+
40+
Registration preserves existing strategies, their indices, flags, and backend
41+
state. It appends the whole new batch in prepared-entry order with one
42+
immutable dispatch snapshot publication. There is no replacement or hot reload.
43+
An already registered configuration ID is rejected, so repeating the same
44+
batch fails rather than becoming idempotent or appending duplicate loggers.
45+
A later batch with fresh IDs and fresh runtime objects may append normally.
46+
47+
Legacy `add_logger()` entries remain unnamed and do not acquire configuration
48+
IDs. The result maps each incoming configuration ID to its appended runtime
49+
index after all existing strategies. Callers use this mapping for the existing
50+
index-based APIs; IDs are not inferred from backend types. Later appends do not
51+
change any previously returned index.
52+
53+
### Validate every prepared batch
54+
55+
`ConfigurationPreparedSet` is publicly constructible and mutable. Registration
56+
must not assume it was returned unchanged by `prepare_configuration()`. Before
57+
any live mutation, validate:
58+
59+
- supported `schema_version` (`1` in v1), even for an empty batch;
60+
- non-empty IDs, unique within the batch and absent from the live configured-ID
61+
map;
62+
- non-null backend and formatter for every entry;
63+
- absence of object aliases as defined below, within the batch and against
64+
existing strategies;
65+
- a representable final registry count and public logger indices;
66+
- valid per-entry registration options, keyed only by IDs in this batch.
67+
68+
The v1 options contain only Boolean `enabled` and `single_mode` flags, defaulting
69+
to `true` and `false` respectively. Unknown option IDs are errors, not ignored
70+
settings for future or existing entries; no other option fields are supported.
71+
Prepared `level` metadata must be a declared `LogLevel` value. Registration
72+
does not reapply levels, rebuild formatters, or otherwise mutate the shared
73+
objects: applying schema strategy remains `prepare_configuration()`'s job.
74+
Callers supplying objects manually are responsible for preparing their state.
75+
76+
For minimal compatibility, cap the final registry **count** at `INT_MAX`, not
77+
`INT_MAX + 1`. Existing readers compare an index with `static_cast<int>(size)`;
78+
the supported index range is therefore `0` through `INT_MAX - 1`. Compute the
79+
capacity check as `batch_size <= limit - current_size` after validating
80+
`current_size <= limit`, before addition or narrowing. Apply the same limit
81+
to legacy appends. Allowing index `INT_MAX` would require auditing and changing
82+
those readers and is outside v1. Test this boundary with a private count seam,
83+
not a registry containing billions of loggers.
84+
85+
A valid empty batch is a successful no-op with an empty result mapping and no
86+
snapshot publication, provided shutdown has not won. Unknown option IDs,
87+
invalid schema, and shutdown are still failures for an empty batch.
88+
89+
### Ownership boundary
90+
91+
The recommended implementation changes `LoggerStrategy`'s internal owners to
92+
`std::shared_ptr`. The unchanged public `add_logger(std::unique_ptr<...>)` API
93+
will construct each internal shared pointer by moving the unique pointer.
94+
The new batch operation can share the prepared logger and formatter without raw
95+
pointer conversion or an ownership transfer that invalidates the prepared
96+
set. This is a lifetime mechanism only; it does not add object-level locks.
97+
98+
Reject the entire batch if a backend or formatter object would belong to more
99+
than one strategy. Check both the incoming entries and all live strategies,
100+
including prior configuration batches and legacy unnamed entries. Reject such
101+
aliases regardless of concurrent-dispatch capability, preventing ambiguous
102+
state mutation and repeated backend shutdown as well as concurrent invocation.
103+
104+
Use object identity, not `shared_ptr::use_count()` or control-block ownership.
105+
For these polymorphic interfaces, the most-derived address obtained via
106+
`dynamic_cast<const void*>(pointer.get())` identifies the complete object even
107+
when interface subobject addresses differ. One complete object must not appear
108+
in different strategies, including across backend/formatter roles. Distinct
109+
objects sharing one control block are not aliases merely for that reason.
110+
Within one strategy, a combined backend/formatter object still has only one
111+
execution mutex and must satisfy both interface contracts. If both interfaces
112+
refer to the same complete object, their shared pointers must also share one
113+
ownership control block, checked in C++11 by symmetric `owner_before()`:
114+
`!backend.owner_before(formatter) && !formatter.owner_before(backend)`.
115+
Independent control blocks for that same object are rejected before publication.
116+
Distinct complete objects sharing one control block remain valid. No global
117+
object-lock registry or new hot-path synchronization is introduced in v1.
118+
119+
The prepared set remains caller-owned after successful registration. Clearing
120+
or destroying it must not invalidate the live registry. A failed registration
121+
must leave both the caller's prepared set and the live registry unchanged.
122+
Externally retained pointers preserve lifetime but do not authorize
123+
unsynchronized external invocation, mutation, or shutdown. Use `Logger`'s
124+
registered-object APIs; direct use must satisfy the existing interface and
125+
lifecycle contracts and be synchronized with registry-mediated operations by
126+
the caller. Callers must not concurrently modify the prepared set, options, or
127+
result slot during registration. Holding an external shared owner does not
128+
prevent `Logger::shutdown()` from shutting down the object.
129+
130+
### Strong exception safety and result publication
131+
132+
All registry membership writers, including legacy `add_logger()`, must use a
133+
complete candidate registry and preconstructed immutable dispatch snapshot.
134+
Do not `push_back()` into the live `m_loggers` and then allocate its snapshot.
135+
The batch path also prepares a candidate configured-ID map and a complete result
136+
mapping before commit. Existing strategy objects are shared into the candidate,
137+
not mutated or reconstructed.
138+
139+
Use a caller-owned `std::shared_ptr<const RegistrationResult>` result slot
140+
(conceptual type name) for the new operation. The immutable result contains
141+
the fully allocated ID-to-`int`-index map for this batch. Prepare its object and
142+
control block before commit, then hand it off with `shared_ptr::swap`, which
143+
is non-throwing in C++11. Do not build or copy a map after registry publication
144+
or rely on optional return-value optimization to make a by-value map safe.
145+
The previous caller result remains unchanged on any pre-commit failure.
146+
147+
While holding the registry write lock, the commit sequence is:
148+
149+
1. Finish all validation and candidate allocations, including the snapshot,
150+
live configured-ID map, and immutable caller result.
151+
2. Swap the candidate registry and ID map into live storage using proven
152+
non-throwing operations (default allocators/comparators; no user hooks).
153+
3. Release-store the prepared `shared_ptr<const StrategyList>` snapshot once.
154+
This is the successful registration's linearization point for dispatch.
155+
4. Swap the prepared result handle into the caller's result slot, release the
156+
registry lock, and return success with no further throwing work.
157+
158+
Lock-based readers cannot observe the intermediate swaps; lock-free dispatch
159+
retains the old snapshot until the release-store and then can see the entire
160+
batch. There must be no allocation, diagnostic formatting, callback, or
161+
throwing result construction after the first live swap. Keep old snapshot and
162+
old result owners alive through commit; release displaced owners and failed
163+
candidates after unlocking so user destructors/deleters cannot run under the
164+
registry mutex. Custom destructors/deleters must be non-throwing.
165+
166+
On validation failure, diagnostics may change but the registry, configured-ID
167+
map, dispatch snapshot, prepared input, and previous result stay unchanged.
168+
Allocation exceptions may propagate before commit rather than trying to
169+
allocate an error diagnostic during `std::bad_alloc`; they must have the same
170+
strong preservation guarantee. No path may publish successfully and then
171+
report failure due to a result allocation or copy.
172+
173+
Legacy `void add_logger()` keeps its unique-pointer parameters, defaults,
174+
successful append behavior, and no-op behavior after shutdown. Its ownership
175+
arguments remain consumed by value; a failure need not return them to the
176+
caller. A pre-commit allocation failure must leave its registry and dispatch
177+
snapshot unchanged. Exhausting the index domain must fail before mutation
178+
(for the legacy void API, a `std::length_error`, not a truncated index).
179+
180+
### Registration/shutdown linearization and locks
181+
182+
Build new strategy objects, pointer identities, and capability flags before
183+
the registry lock; capability queries are virtual calls and must not run under
184+
that lock. They retain ADR 0006's existing meaning and are cached per strategy.
185+
No capability exempts objects from alias rejection.
186+
187+
Registration then takes `m_loggers_mx` in write mode and rechecks shutdown,
188+
duplicate IDs, object aliases against the current registry, and final index
189+
capacity. Only this locked view determines the appended indices. Construct
190+
the remaining candidates under that lock without invoking user code, then
191+
perform the non-throwing commit above. Concurrent legacy and batch writers
192+
are serialized by this same lock. Registration never takes `exec_mx`.
193+
194+
Shutdown takes the registry write lock, checks whether shutdown already won,
195+
retains the already-published immutable snapshot by shared-pointer copy
196+
(without allocating a vector), and sets `m_shutdown` while still locked.
197+
The transition to shutdown is its linearization point. Release the registry
198+
lock before taking any strategy `exec_mx`, invoking backend `shutdown()`, or
199+
shutting down the shared executor. Shutdown holds at most one strategy mutex
200+
at a time; it never reacquires the registry lock while holding that mutex.
201+
Repeated shutdown calls remain no-ops under the existing contract. This
202+
specifies the registration/shutdown paths, not new general callback reentrancy
203+
guarantees for other lifecycle/control APIs.
204+
205+
If registration publishes first, the shutdown snapshot contains every member
206+
of the committed batch. If shutdown sets the flag first, registration fails
207+
without publication or result replacement. Early atomic `m_shutdown` checks
208+
are optimizations, not substitutes for these locked checks. In-flight
209+
dispatch may retain an older snapshot, as in ADR 0003. Serialized dispatch
210+
continues to use `exec_mx`; opted-in concurrent pairs retain ADR 0006's
211+
requirements for safe concurrent lifecycle calls. Do not change those
212+
contracts or promise synchronous cancellation of in-flight calls.
213+
214+
### Atomicity and side effects
215+
216+
Atomicity covers caller-visible registry publication only. The prepared set is
217+
already materialized, so registration must not invoke factories, resolve
218+
bindings, parse input, or start a backend-specific lifecycle outside the
219+
normal logger construction contract. Factory side effects are not transactional.
220+
No implementation of the registration or shutdown changes is part of this PR.
221+
222+
## Consequences
223+
224+
- Configuration batches become visible to dispatch all at once.
225+
- Existing applications retain the unique-pointer `add_logger()` API.
226+
- Shared ownership preserves lifetime, while alias rejection prevents multiple
227+
strategy locks and shutdown paths from independently controlling one object.
228+
- The internal `LoggerStrategy` owner type changes, so implementation work must
229+
cover shutdown, snapshots, `wait()`, clear/read APIs, targeted indices, and
230+
concurrent dispatch on both C++11 and C++17.
231+
- Candidate construction also repairs legacy `add_logger()` exception safety;
232+
it adds only cold-path work, not a dispatch object-lock registry.
233+
- Registration does not provide replacement, rollback of external backend
234+
effects, file watching, or hot reload.
235+
- Configuration IDs require a small registry-side metadata map; they are not
236+
retrofitted onto legacy unnamed registrations.
237+
238+
## Regression matrix for implementation
239+
240+
| Case | Required result |
241+
| --- | --- |
242+
| Two-entry batch succeeds | One snapshot publication; both IDs map to consecutive runtime indices after existing strategies. |
243+
| Invalid second entry or duplicate ID | No new strategy or ID is visible; existing registry and caller output remain unchanged. |
244+
| Shared backend pointer under two different IDs | Reject the whole batch, with concurrent capability either enabled or disabled. |
245+
| Shared formatter pointer under two different IDs | Reject the whole batch; no log/format invocation or object state change during validation. |
246+
| Runtime object reused in a later batch | Reject even with a fresh ID; include aliasing against legacy entries and different interface subobject addresses. |
247+
| Distinct objects sharing one control block | Do not falsely reject solely because shared ownership has the same control block. |
248+
| Combined backend/formatter object in one strategy | Accept only with one shared ownership control block; reject independent control blocks for the same complete object without publication. |
249+
| Manually constructed prepared set | Reject unsupported schema, empty/duplicate IDs, null objects, invalid level/options, and unknown option IDs without publication. |
250+
| Snapshot allocation failure in batch registration | Mutable registry, ID map, dispatch snapshot, prepared input, and old result remain unchanged. |
251+
| Returned ID/index result allocation failure | No publication or partial mapping; old caller result remains unchanged. |
252+
| Legacy `add_logger()` snapshot allocation failure | No mutable registry/snapshot divergence; previous entries remain usable. |
253+
| Maximum valid index and overflow | Private count seam accepts final count `INT_MAX`/last index `INT_MAX - 1` and rejects the next append without narrowing or arithmetic overflow. |
254+
| Repeated batch | Duplicate configured IDs fail; no implicit replacement or idempotent success. |
255+
| Legacy `add_logger()` before and after a batch | Existing API remains valid; unnamed indices remain stable and configured ID mapping remains unambiguous. |
256+
| Externally retained or destroyed prepared set | Registry retains the objects; external owners obey invocation/mutation/shutdown restrictions and do not receive a second shutdown authority. |
257+
| `single_mode` option and enabled state | Targeted/general routing and default enabled state match ordinary strategy behavior. |
258+
| Concurrent dispatch during registration | Each dispatch sees either the old or complete new snapshot, never a partial batch. |
259+
| Registration versus shutdown | Deterministic barriers exercise both lock orders: either all entries are in the shutdown snapshot or registration fails unchanged. No sleeps or production-singleton restart. |
260+
| Shutdown callback queries `logger_count()` while a registration competes | No registry mutex is held during backend shutdown; registration never waits on `exec_mx`. |
261+
| Valid empty batch | Empty result, no publication; invalid schema/options or prior shutdown still fail. |
262+
| Factory/formatter failure before registration | No registration call or live mutation occurs. |
263+
| C++11/C++17 and feature-disabled builds | Public `add_logger()` remains source-compatible; registration uses no newer language features or optional parser dependency. |
264+
265+
Use focused allocation-failure seams for snapshot and result construction,
266+
and controlled barriers for the shutdown race. Run singleton shutdown cases
267+
in process-isolated regression executables or through a suitable private test
268+
seam. Do not add a production singleton reset/restart API. Checks must remain
269+
active with and without `NDEBUG`.
270+
271+
## Alternatives considered
272+
273+
### Move prepared pointers into `unique_ptr`
274+
275+
Rejected. It would make `ConfigurationPreparedSet` move-only, break the
276+
existing factory/shared-ownership contract, and make failed publication harder
277+
to preserve safely.
278+
279+
### Convert `shared_ptr` through `get()`
280+
281+
Rejected. Constructing a `unique_ptr` from that raw pointer would either cause
282+
double deletion or require a non-owning deleter, leaving lifetime dependent on
283+
the prepared set.
284+
285+
### Register each entry with the existing `add_logger()`
286+
287+
Rejected for a configuration batch. It exposes partial state and cannot return
288+
one atomic publication point or an unambiguous batch ID/index mapping.
289+
290+
### Share one object across strategies with a global lock registry
291+
292+
Rejected for v1. It would add object-level synchronization and lifecycle
293+
coordination across strategies and complicate the concurrent-dispatch path.
294+
Rejecting aliases is a smaller, explicit cold-path restriction.
295+
296+
### Replace the registry wholesale on every configuration load
297+
298+
Deferred. Replacement needs explicit semantics for in-flight records,
299+
shutdown, ID collisions, and rollback. It is not implicit hot reload.
300+
301+
## References
302+
303+
- [ADR 0009: Versioned configuration loading contract](0009-configuration-loading-contract.md)
304+
- [ADR 0003: Immutable logger registry snapshots](0003-immutable-registry-snapshots.md)
305+
- [ADR 0006: Explicit capability for concurrent dispatch](0006-concurrent-dispatch-capability.md)
306+
- [Logger registry implementation](../../include/logit_cpp/logit/Logger.hpp)
307+
- [Prepared runtime types](../../include/logit_cpp/logit/configuration_runtime.hpp)

‎docs/adr/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@ explains **why the current boundary or trade-off exists**.
3535
## Proposed decisions
3636

3737
- [0009 — Versioned configuration loading contract](0009-configuration-loading-contract.md)
38+
- [0010 — Atomic registration of prepared configuration batches](0010-atomic-configuration-registration.md)

0 commit comments

Comments
 (0)