Files
Library/docs/roadmap/modules/Log.md

174 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Log — bounded delivery and process-wide facade
Status: plan; all feature tasks are PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
Implements R-005/R-009/R-012/R-014 under [C-03–C-05 and C-11](../ARCHITECTURE.md).
## Existing behavior and gaps
The names are deliberately distinct: `Void::Log` is the emission facade in
[Log.hpp](../../../include/Void/Log/Log.hpp); `Void::Logging` owns `Logger`, `Entry`,
formatters and sinks. [LogState/State.cpp](../../../src/LogState/State.cpp) defines the
single facade state through a separate compiled target. Preserve this across host/plugin
shared-library boundaries; replacing it with inline per-module statics changes behavior.
Disabled facade calls gate formatting, and per-module levels override the global level.
However, `Detail::emit` currently invokes the sink while holding `State::mutex` shared.
Reentrant `set_sink` or level changes therefore need a defined safe design.
[Logger.cpp](../../../src/Log/Logger.cpp) supports Immediate, Buffered and Async modes.
The async policies are Block, DropNewest and DropOldest. DropOldest currently enqueues
without reserving capacity and trims later. The worker drains into an unconstrained batch
and returns queue permits before delivery; queue capacity is not a bound on total retained
entries. Existing derived sinks flush while still alive, whereas the base destructor
stops/joins without invoking virtual delivery. Do not weaken that lifetime obligation.
[Sinks.hpp](../../../include/Void/Log/Sinks.hpp) has callback, null and fan-out sinks;
fan-out configuration is assembled before concurrent use. File/rotation/history sinks and
pattern/JSON-lines/logfmt formatters are existing capabilities. [FieldScope](../../../include/Void/Log/Field.hpp)
and [Field.cpp](../../../src/Log/Field.cpp) maintain thread-local fields;
[Entry](../../../include/Void/Log/Entry.hpp) owns snapshots for delivery.
[module.cmake](../../../src/Log/module.cmake) currently declares Functional/Configuration
and optional Stacktrace. LogState remains the lightweight compatibility bridge; foundation
independence is governed by C-01, not by linking the full sink framework everywhere.
Evidence includes [facade tests](../../../tests/standalone/Log/Log.cpp),
[async tests](../../../tests/standalone/Log/AsyncLogger.cpp), and
[scope snapshots](../../../tests/standalone/Log/LogScopeSnapshot.cpp). Existing passing
queue tests are not proof of a byte budget, reentrant callbacks or throwing-sink safety.
## Delivery architecture and NEW interfaces
Keep native delivery and formatting; external logging systems integrate via adapters,
not a mandatory backend. Use a mutex-protected bounded ring initially: it makes eviction,
permit accounting and flush boundaries auditable. A different concurrent queue is a later
measured optimization with identical semantics. No dependency on Runtime or an exporter.
NEW illustrative additions in `Void::Logging`:
```cpp
struct DeliveryLimits {
std::size_t entries = 4096;
std::size_t owned_bytes = 8 * 1024 * 1024;
std::size_t max_entry_bytes = 64 * 1024;
std::size_t batch_entries = 128;
};
enum class SubmitState { Accepted, Filtered, Dropped, Closed };
using Ticket = std::uint64_t;
struct SubmitReceipt { SubmitState state; std::optional<Ticket> ticket; };
struct FlushReport { std::uint64_t delivered, dropped, failed; };
Result<SubmitReceipt> try_submit(Entry); // NEW Logger method
Result<FlushReport> flush_through(Ticket, FlushOptions);
Result<FlushReport> close(CloseOptions);
```
`Ticket`, `FlushOptions`, `CloseOptions` and admission receipts are NEW Log-owned types;
they refer to Async's stop/deadline options rather than invent another cancellation type.
Existing void-returning methods remain compatibility adapters until the major migration.
NEW configurations default to DropNewest; existing constructors keep their documented
Block default until explicitly migrated. Ticket assignment occurs only for admitted
entries, under admission order, after fallible preparation succeeds.
Non-admitted submissions have no ticket; sequence exhaustion closes admission rather than
wrapping a watermark and reporting premature flush completion.
Reserve bytes and entries before making internal owned copies. Total accounting includes
queued entries, producers preparing admitted entries, dequeued batches, sink formatting
scratch and fan-out copies. A public caller's pre-existing Entry is outside the logger
budget; any retained copy is inside. Format into capped storage; reject oversize by default
instead of allocating an unlimited intermediate string. Truncation is an explicit policy
and marks the record. Allocator overhead is charged conservatively, not just message size.
Add defaults of 32 fields, 16 scope elements, 256-byte keys and 2 KiB field values.
The worker claims at most 128 entries/256 KiB per batch and retains their permits until
delivery or terminal loss. DropNewest rejects immediately. DropOldest evicts only a queued,
not-yet-dispatched entry under the admission lock; if all capacity is in flight, drop the
new arrival. Block is opt-in, cancellable in the new API, and forbidden on the delivery
worker or an executor needed to release capacity. Admission order defines per-logger
ordering; no timestamp-based total order across independent loggers is promised.
Fan-out is bounded to eight children by default, checks cycles on configuration, and owns
child handles. A child has a distinct budget; total memory is the sum of parent and child
budgets, visible in configuration. Share immutable records where possible, charging the
shared payload once to a retained owner and charging each envelope separately. A slow
child must not create an unbounded staging queue in the parent.
## Reentrancy, flush and shutdown
Facade configuration becomes an immutable sink-registration object retained by emitters.
Acquire/snapshot the registration under the configuration lock, then release that lock
before formatting/callback invocation and before destroying the old callback. Replacement
affects subsequent admissions; already-admitted calls may still use the old registration.
NEW `detach_and_drain` waits for those calls to exit and is not callable synchronously
from that registration's callback. `set_sink` alone is not an unsubscribe-and-join promise.
Callbacks that capture plugin code retain its generation through the last callback.
A per-thread/per-logger dispatch guard suppresses recursive dispatch into the same sink,
increments `reentrant_dropped`, and uses a bounded emergency diagnostic path only if
explicitly installed. Logging to a different sink remains allowed within a maximum nesting
depth of eight. No retry/error reporting calls back into a failing sink. User callbacks,
formatter code and virtual sink methods run outside queue/configuration locks. A callback
may request asynchronous close, but self-join or blocking flush returns WouldDeadlock.
Flush takes a ticket watermark, so later producers cannot extend it forever. Every admitted
ticket becomes delivered, evicted or failed; the completion watermark advances only through
a contiguous terminal prefix, even if immediate mode completes out of order. The report
includes all losses through that watermark. A sink's buffer flush is distinct from durable
file sync: a NEW `FlushDurability::SyncFiles` option syncs supported file sinks or returns
UnsupportedCapability. Callback sinks cannot claim disk durability on the callback's behalf.
Catch sink exceptions at delivery boundaries, mark affected tickets failed, record a bounded
error summary, and continue or quarantine that sink according to a selected configuration.
Default is quarantine after the first delivery failure, with explicit operator reset;
never silently retry a possibly written record. Mode/formatter changes use an admission
barrier and drain the old generation before publishing the new one. Configuration validation
cannot invoke arbitrary callbacks while locked.
`close` rejects new work, drains or explicitly drops queued work, then joins delivery and
releases sink ownership. A deadline may stop waiting but cannot destroy a callback still
executing; an owning close handle retains resources until completion (C-03). Legacy derived
destructors still need their flush contract; NEW composition owns sink state independently
of a partially destructed polymorphic logger. No forceful callback interruption is promised.
## Capability backlog and implementation order
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| M-LOG-01 | P0; current tests | Add regressions for callback reconfiguration, slow sink and total queued+in-flight accounting; preserve existing disabled/field/mode behavior. | astra_implementer |
| M-LOG-02 | P1; M-LOG-01, C-11 | Snapshot facade registrations, drain handles, reentrancy guard and shared-library test; host sink receives plugin events and can replace itself without deadlock. | astra_implementer |
| M-LOG-03 | P2; M-LOG-02, Memory budgeting | Bounded ring, byte admission, batch limits, all saturation policies and contiguous ticket completion; limits hold while sink stalls and producers race. | astra_implementer |
| M-LOG-04 | P2; M-LOG-03, Async operation options | Result-based flush/close, failure quarantine, reconfiguration barriers; no self-join, stuck watermark or callback after owner release. | astra_implementer |
| M-LOG-05 | P2; M-LOG-04 | Finish sink workflows: file failure reporting, retention quota, rotation/reopen, formatter escaping/redaction and configuration validation; disk-full preserves loss accounting. | sol_implementer |
| M-LOG-06 | P3; M-LOG-04, Observability hook/context contract | Optional context bridge, metrics and managed shutdown adapter; no Log↔Observability or Async↔Log cycle. | sol_implementer |
| M-LOG-07 | P3; M-LOG-05/06, shared performance harness | Profile disabled, immediate, async, structured and saturated paths; publish measured latency/memory/build costs and rejected counts. | sol_implementer |
P4 consumers reuse these contracts through [distributed platforms](../platforms/DistributedApplications.md);
logging does not become a durable consensus log. For file rotation default NEW retention is
five 16 MiB files per sink, with a 1 MiB capped formatting scratch budget. Opening/reopening
files is fallible, directory creation is explicit, and partial writes are errors with
possible partial external output. Audit records needing durable transactional semantics
belong in Storage, not a loss-tolerant logger.
## Validation and compatibility
CURRENT interfaces: the existing `VoidTests` supports `--filter`; a TEMPLATE for the verified
names is `<existing-build>/tests/VoidTests --filter '^(no_sink_is_silent|disabled_calls_do_not_format|async_.*)$'`.
Use the configured build in [validation](../VALIDATION.md); this documentation task does not
execute it. PROPOSED tests require M-LOG-01–06: deterministic blocked callbacks, callback
replacement/destruction, thrown formatter/sink, concurrent flush, drop-oldest pressure,
permit rollback on allocation failure, copied context after producer exit, and shutdown
with an admitted callback. Stress and TSan supplement deterministic ownership checks.
Measure p50/p95/p99 admission and flush separately, throughput, allocations, RSS/CPU and
build cost under [performance](../PERFORMANCE.md)'s warmup/repetition/confidence rules.
Report drops and reentrant suppression alongside useful delivery; an apparent improvement
caused by losing work is not an optimization result.
[Migration](../MIGRATION.md): preserve namespaces and LogState symbol linkage; add explicit
registration and close handles before replacing legacy signatures. Example transition:
`logger.info(text); logger.flush();` becomes checked admission plus `flush_through(ticket)`
when delivery evidence matters. Frozen C/plugin contracts must use their own versioned
bridges, not embed C++ Entry layout. Keep old sinks behind adapters during the major release;
roll back a new queue/backend only if ordering, resource and flush tests remain satisfied.
Coverage: cited files were checked in the repository graph and read directly; partial parses
in Logger/Sinks/Field were inspected, so graph absence is not used as evidence. New tests,
resource guarantees and performance claims remain unverified planned work.