Files

125 lines
8.8 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.
# Messaging subsystem plan — NEW
Status: NEW design; all tasks PLANNED. Baseline
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
Authority: [requirements](../REQUIREMENTS.md) R-009, R-011, R-012, R-014–R-016;
[architecture](../ARCHITECTURE.md) C-02–C-05, C-08, C-11–C-13.
## Baseline and ownership
No current Messaging directory, broker or delivery guarantee is claimed. Existing
[Net WebSocketSessions](../../../include/Void/Net/Server.hpp) is a connection registry,
not durable messaging. Its graph parse gaps at 207/211/214 were read directly; source
does not imply a wire transport. Proposed roots `include/Void/Messaging`, `src/Messaging`
and `tests/standalone/Messaging` are NEW. Messaging owns delivery state, queue/group
semantics, acknowledgements and retry policy. [Storage](Storage.md) owns durable batches;
[RPC](RPC.md) owns remote envelopes; [Replication](Replication.md) optionally supplies a
replicated queue state machine. None depends back on Messaging.
Select native queue/delivery logic with a single-node durable Storage adapter first.
Transport remains optional. An in-process ephemeral channel is explicitly nondurable;
it must not use the same success label as durable publish. An external broker adapter
is a later capability gate with its own conformance matrix, not the initial backend.
## NEW API and delivery contract
```cpp
// NEW illustrative Void::Messaging shapes; Result/Task/options follow C-02/C-03.
enum class PublishDurability { memory, durable };
struct Message { MessageId id; OwnedBytes payload; Headers headers; };
struct Delivery { Message message; Receipt receipt; std::uint32_t attempt; };
class Queue {
Task<Result<PublishReceipt>> publish(Message, PublishDurability, OperationOptions);
Task<Result<Delivery>> receive(ConsumerGroup, OperationOptions);
Task<Result<void>> ack(Receipt, OperationOptions);
Task<Result<void>> nack(Receipt, RetryDelay, OperationOptions);
};
```
Durable delivery is explicitly at-least-once. Message IDs are application-visible;
receipts additionally identify queue, group and delivery generation. Ack means the queue
durably recorded processing acknowledgement, not that the external world changed exactly
once. Consumer effects followed by a crash before ack can run again. An application may
atomically write effects plus an inbox dedup record only when both share one supported
Storage batch; an email, payment or arbitrary RPC is outside that atomicity boundary.
Outbox recipes store a business mutation and outbound message in the same local batch,
then publish/retry by stable ID. They do not create cross-system transactions.
Initial durable model is FIFO work queues per consumer group with competing consumers.
Order is enqueue sequence within a queue, not completion order when concurrency >1.
Single-active-consumer mode provides ordered processing only if the application waits
for ack before the next delivery; retries block that group's head in this mode. Parallel
mode can complete out of order. Pub/sub uses named groups, each with independent offset,
retry and retention state. There is no global order across queues/groups.
Native state machine: Pending → InFlight(receipt-generation, visibility deadline) →
Acked, or Pending after nack/visibility expiry, or DeadLetter after exhaustion. Publish
durably inserts payload, sequence and initial group records before returning durable
success. Receive persists delivery generation/attempt before exposing the receipt.
Ack is a conditional atomic state change matching the current receipt. Old receipt:
stale_receipt; repeat ack of the same acknowledged receipt: successful idempotent result.
Nack/ack races serialize in writer order. An abandoned Delivery is not implicitly acked.
Visibility defaults to 30 seconds, extension explicit up to 5 minutes per delivery.
Use injected monotonic timers while running. On restart all prior InFlight records become
eligible for redelivery with a higher generation; old worker receipts cannot acknowledge
the new attempt. Retention expiry uses recorded civil instants and an injected clock;
clock-health failure pauses expiry rather than discarding potentially live messages.
Retry: five delivery attempts total, full jitter base 1 second/cap 60 seconds, injectable
randomness. DLQ insertion and source removal are one atomic batch in the same store.
If DLQ is full or unavailable, keep the message and block/drop no data; expose stuck count.
## Bounds, shutdown and operational failures
NEW defaults: message ≤768 KiB, headers ≤8 KiB/32 fields, 1,024 queues, 32 groups/queue,
64 in-flight deliveries/group, 1,024 waiting receives/module and 64 MiB transient payload
budget. Persistent quota defaults to 1 GiB, including retry/DLQ/group metadata. Durable
publish identity outcomes retain 24 hours and at most 100,000 IDs; at capacity reject new
publish, never silently evict an identity still within its contract. Older IDs outside
the retention contract can be published again, so application dedup remains necessary.
Logical retention defaults to seven days and requires an explicit policy for unread
messages: the initial policy blocks further publish at quota, rather than expiring unread
work silently. Operators may explicitly choose lossy expiry in a separately named mode.
Stop admission → wake/cancel pending receives → drain active consumers for 10 seconds →
persist remaining visibility state → join owned tasks. A callback receives an owning
message handle until it returns; no payload is reclaimed while a delivery owns it.
Observers run outside queue/storage locks with bounded labels and no payload/secret logging.
| Trigger | Required behavior | Gate |
| --- | --- | --- |
| Publish sync fails / reply lost | Error or unknown outcome; stable ID permits inspection/retry | Crash at insert/sync/reply boundaries |
| Consumer effect then process dies | Redeliver; duplicate expected | Inbox/outbox sample proves stated boundary |
| Visibility expires / old ack arrives | New generation; stale ack cannot remove newer work | Controlled timer/receipt histories |
| Poison message | Retry bound then atomic DLQ move | Attempt counter survives restart |
| DLQ or queue quota full | Stop affected admission; retained work remains durable | Disk full and retention pressure |
| Cancellation during ack | Ack may have committed; query by receipt | Lost-reply and duplicate-ack cases |
| Partition in replicated mode | Minority cannot durable-publish/ack | Quorum adapter tests |
| Unknown schema / corrupt payload | Quarantine/report; no acknowledgement as processed | Corruption and consumer-version tests |
## Task DAG and validation
| ID | Phase / dependencies | Implementation and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-MESSAGING-01 | P0; baseline | Record NEW boundary and build-independent delivery model fixtures | sol_implementer |
| S-MESSAGING-02 | P1; S-MESSAGING-01, Async/Time/Binary contracts | Typed IDs/receipts, native state model and bounded ephemeral channel; deterministic cancel/order tests | sol_implementer |
| S-MESSAGING-03 | P3; S-MESSAGING-02, Storage durable batches | Durable queues, visibility generations, retries/DLQ and recovery; crash injection preserves acknowledged state | astra_implementer |
| S-MESSAGING-04 | P3; S-MESSAGING-03, RPC/Security gates | Remote publish/receive/ack and inbox/outbox examples; no blanket exactly-once assertion | sol_implementer |
| S-MESSAGING-05 | P4; S-MESSAGING-04, Replication single-group gate | Replicated queue adapter; leader change/lost replies preserve at-least-once and ack state | astra_implementer |
| S-MESSAGING-06 | P4; S-MESSAGING-05 | Partitioned queues/group operations and operational tooling; per-queue ordering explicit, no cross-shard atomic publish | astra_implementer |
CURRENT: no Messaging executable or test target exists. PROPOSED verification adds state
model enumeration, receipt race tests, crash/restart fault injection, poison/DLQ pressure,
slow consumers and minority partitions. Use [SQLite's crash-test methodology](https://sqlite.org/atomiccommit.html#_testing_atomic_commit_behavior)
as a model for persistence faults, not a claim of SQLite compatibility. Future targets
and commands follow [VALIDATION](../VALIDATION.md) and
[BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md).
Measure publish durable latency, receive-to-ack p50/p95/p99, redelivery lag, throughput,
allocations, peak RSS/CPU, retained disk and build cost under [PERFORMANCE](../PERFORMANCE.md).
Migration versions persisted receipt/state records and drains old consumers before changing
semantics. Export retains message IDs, groups, attempts and DLQ reasons. Rollback must keep
old format readers and receipt fencing; it cannot make previously delivered effects disappear.
See [MIGRATION](../MIGRATION.md), [Scheduler](Scheduler.md) and
[DistributedApplications](../platforms/DistributedApplications.md).