yams/tests/unit/cli/p2p_status_format_catch2_test.cpp
Trevon e0d15dc680
fix(p2p): stop quarantining honest writers for concurrent-session races (#245)
* feat(p2p): log durable writer quarantines and outbound session failures

A node that durably quarantined a peer writer left no trace of why: the
three p2p quarantine sites returned an error to their session, and the
reconnect loop dropped every outbound session error without logging it,
so a mesh that stopped receiving one writer showed only a quarantined
record count. Outbound sessions are half of all sessions in a full mesh.

Each p2p quarantine site now logs the writer, the failed check and the
local and frozen counters, and a failed outbound session logs its peer
and error, matching the existing inbound failure log.

Signed-off-by: trvon <me@trevon.dev>

* fix(p2p): stop quarantining honest writers for concurrent-session races

Each pair of direct peers normally runs two sessions at once, one
initiated from each side. Both freeze a window of the peer's writer at
handshake, and whichever applies first advances the receiver's durable
prefix under the other. The second session then compared its frozen
window with that live prefix and treated the difference as forged
history: validateHistoryExtension demanded the window start right after
the live commitment ("history extension is not contiguous"), and an
empty window demanded the live counter equal the frozen frontier. Both
durably quarantined an honest writer, after which the node dropped its
documents and refused every later session with it. A 5-node mesh run
logged exactly this (local=30 frontier=32 staged=4: a window frozen at
28 arriving after another session had applied 29-30), and the mesh
never converged.

The receiver now validates a window against durable history instead of
a snapshot. Operations at or below the advanced prefix are replays that
applyDeltas leaves untouched (a different record under a known operation
id is still a fork). The rest must chain from the durable commitment
exactly to the authenticated frontier, and an empty window must match
the durable commitment at its frontier. validateHistoryExtension returns
a typed WriterHistoryViolation for writer faults (fork, forged frontier,
gap, unauthenticated record) and an Error for local or transient
failures, and only a violation quarantines; an Error aborts the session
for a retry on the next cycle.

The security property is unchanged: nothing is applied unless a hash
chain links durable history, itself verified against the writer's
authenticated commitments, to the frontier the writer authenticated in
this handshake. Overlapping replays change no state, and forks, forged
frontiers, gaps and unauthenticated records still quarantine, now also
when they overlap an advanced prefix (new tests cover each).

The pre- and post-exchange history checks get the same treatment. A
live prefix between the proven handshake prefix and the frozen frontier
is consistent, since delta exchange verifies the rest; one beyond the
frontier is compared with the durable commitment at the frontier rather
than rejected as a rollback.

The handshake also clamps the live local-writer window resolver to the
frozen snapshot, so concurrent local writes no longer fail the session
with "local writer-window resolver violated negotiated bounds".

Signed-off-by: trvon <me@trevon.dev>

* feat(p2p): report outbound sessions and durable writer quarantines

`yams p2p status` showed inbound session failures but not outbound
ones, and only a `quarantined` record count that mixes durable writer
quarantine with transient rejections (a record whose causal dependency
from a third writer has not arrived yet). An operator could not tell a
mesh that was retrying from one that had permanently cut off a writer.

Status now reports:

- outbound_sessions / outbound_failures and the last outbound failure
  with its peer, counted for both explicit connects and reconnects.
  Failed sessions in either direction are aborted and retried.
- quarantined_writers: writers durably quarantined by this node, read
  from the replication checkpoint, so it survives restarts. Each
  quarantine is also logged with its reason.

The fields travel through MemorySyncStatus, MemorySyncResponse and
protobuf fields 38-42 to the text and JSON status and to `yams daemon
status -d`, following the apply-health fields.

Signed-off-by: trvon <me@trevon.dev>

* fix(memory-sync): verify replayed writer counters against durable history

validateHistoryExtension skipped every staged operation at or below the
writer's durable prefix as a replay without looking at its record hash,
leaving fork detection to applyDeltas. applyDeltas recognizes a fork only
by an operation id it still remembers, and that memory is lost on restart
and bounded by maxTrackedIdentities. A different, internally valid record
for an already-applied counter therefore passed as a harmless replay
instead of being quarantined as the fork it is, whether the window only
replayed old counters or rode the fork along an honest extension.

Before skipping a replayed counter, compare its record hash with the
durable history entry committed at that counter (rebuilding the entry like
computeHistoryCommitmentAt when it is missing). A mismatch is a
WriterHistoryViolation, so the p2p session durably quarantines the writer;
an identical replay is still accepted as a no-op. A history entry that
cannot be read stays a local Error and only aborts the session.

Signed-off-by: trvon <me@trevon.dev>

* fix(memory-sync): log every durable writer quarantine where it happens

Durable writer quarantine was logged only by its two p2p callers. The
duplicate-operation fork path inside applyDeltas and the shared-store scan
path quarantined silently, so the documented guarantee that every durable
quarantine logs its reason and counters did not hold, and an operator saw
a quarantined_writers count with nothing in the log to explain it.

quarantineWriter now takes the reason and is the one place that logs a new
quarantine: writer, reason, source node, and the writer's local history and
version counters. It logs nothing when the writer was already quarantined,
so a repeated request is not reported twice. The p2p callers drop their own
warnings and fold their session context (frontier, staged count, prefix
match) into the reason instead. memory_sync now declares its spdlog
dependency explicitly.

Signed-off-by: trvon <me@trevon.dev>

* fix(cli): show outbound p2p sessions in daemon status

The daemon already reports outbound sessions, failures, and the last
outbound failure, and `yams p2p status` prints them, but `yams daemon
status -d` only gained the quarantined-writers row. An outbound direction
that keeps failing is aborted and retried, never quarantined, so the
detailed status was the place an operator would miss it.

The Memory Sync section now shows an Outbound sessions row (started and
failed counts, warning when any failed) for direct-backend nodes, and a
Last outbound failure row with the peer, the error, and its age.

Signed-off-by: trvon <me@trevon.dev>

---------

Signed-off-by: trvon <me@trevon.dev>
2026-10-01 12:18:47 -06:00

141 lines
6 KiB
C++

// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright 2026 YAMS Contributors
// `yams p2p status` rendering of memory-sync apply health. The formatter is pure, so a synthetic
// reply drives every branch the CLI otherwise reaches only through a live daemon.
// pi-lens-ignore: fatal error
#include <nlohmann/json.hpp>
#include <catch2/catch_test_macros.hpp>
#include <string>
#include <yams/cli/p2p_status_format.h>
#include <yams/daemon/ipc/ipc_protocol.h>
namespace {
yams::daemon::MemorySyncResponse stuckMeshNode() {
yams::daemon::MemorySyncResponse m;
m.started = true;
m.backend = "direct";
m.nodeId = "net-research";
m.corpusId = "corpus";
m.corpusEpoch = 1;
m.mode = "persistent";
m.trustMode = "mutual-tls-operator-pinned";
m.peerCount = 2;
m.records = 219;
m.successfulCycles = 1268;
m.applyCycles = 1268;
m.applyFailedCycles = 1268;
m.deferredVector = 3;
m.deferredTopology = 1;
m.oldestDeferralAgeMs = 754'000;
m.applyFailuresTopology = 1268;
m.lastApplyFailureStage = "topology";
m.lastApplyFailure = "topology edge identity does not match logical key";
m.lastApplyFailureAgeMs = 5'000;
m.publishSkippedCycles = 2;
m.publishFailedCycles = 1;
return m;
}
} // namespace
TEST_CASE("p2p status text reports apply health as key=value tokens",
"[cli][p2p][status][memory-sync]") {
const auto rendered = yams::cli::formatP2pStatus(stuckMeshNode(), false);
REQUIRE(rendered.has_value());
const auto& text = rendered.value();
const auto firstLine = text.substr(0, text.find('\n'));
// The first line stays one line of tokens, so existing scrapers keep working.
CHECK(firstLine.find("records=219") != std::string::npos);
CHECK(firstLine.find("failed_cycles=0") != std::string::npos);
CHECK(firstLine.find("apply_cycles=1268") != std::string::npos);
CHECK(firstLine.find("apply_failed_cycles=1268") != std::string::npos);
CHECK(firstLine.find(" deferred=4 ") != std::string::npos);
CHECK(firstLine.find("oldest_deferral_age_ms=754000") != std::string::npos);
CHECK(firstLine.find("publish_skipped_cycles=2") != std::string::npos);
CHECK(firstLine.find("publish_failed_cycles=1") != std::string::npos);
CHECK(text.find("\napply deferred_content=0 deferred_metadata=0 deferred_vector=3 "
"deferred_topology=1 failures_content=0 failures_metadata=0 "
"failures_vector=0 failures_topology=1268") != std::string::npos);
CHECK(text.find("\nlast apply failure (5s ago) at topology: topology edge identity") !=
std::string::npos);
CHECK(text.find("last inbound failure") == std::string::npos);
}
TEST_CASE("p2p status text omits the apply failure line on a healthy node",
"[cli][p2p][status][memory-sync]") {
yams::daemon::MemorySyncResponse m;
m.started = true;
m.applyCycles = 10;
const auto rendered = yams::cli::formatP2pStatus(m, false);
REQUIRE(rendered.has_value());
CHECK(rendered.value().find(" deferred=0 ") != std::string::npos);
CHECK(rendered.value().find("last apply failure") == std::string::npos);
}
TEST_CASE("p2p status JSON nests apply health", "[cli][p2p][status][memory-sync][json]") {
const auto rendered = yams::cli::formatP2pStatus(stuckMeshNode(), true);
REQUIRE(rendered.has_value());
const auto parsed = nlohmann::json::parse(rendered.value());
REQUIRE(parsed.contains("apply"));
const auto& apply = parsed.at("apply");
CHECK(apply.at("cycles") == 1268);
CHECK(apply.at("failed_cycles") == 1268);
CHECK(apply.at("deferred").at("total") == 4);
CHECK(apply.at("deferred").at("vector") == 3);
CHECK(apply.at("deferred").at("topology") == 1);
CHECK(apply.at("oldest_deferral_age_ms") == 754'000);
CHECK(apply.at("failures").at("topology") == 1268);
CHECK(apply.at("last_failure").at("stage") == "topology");
CHECK(apply.at("publish_skipped_cycles") == 2);
CHECK(apply.at("publish_failed_cycles") == 1);
CHECK(parsed.at("failed_cycles") == 0);
}
TEST_CASE("p2p status separates transient session failures from durable quarantines",
"[cli][p2p][status][quarantine]") {
auto m = stuckMeshNode();
m.inboundSessions = 30;
m.inboundFailures = 4;
m.lastInboundFailureStage = "delta_exchange";
m.lastInboundFailure = "p2p peer made no causal progress applying direct deltas";
m.outboundSessions = 28;
m.outboundFailures = 2;
m.lastOutboundFailure = "peer-b: authenticated peer writer prefix was not verified";
m.lastOutboundFailureAgeMs = 7'000;
m.quarantinedWriters = 1;
const auto text = yams::cli::formatP2pStatus(m, false);
REQUIRE(text.has_value());
const auto firstLine = text.value().substr(0, text.value().find('\n'));
CHECK(firstLine.find(" quarantined_writers=1") != std::string::npos);
CHECK(firstLine.find(" outbound_sessions=28") != std::string::npos);
CHECK(firstLine.find(" outbound_failures=2") != std::string::npos);
CHECK(text.value().find("\nlast outbound failure (7s ago) to peer-b: authenticated peer "
"writer prefix was not verified") != std::string::npos);
const auto json = yams::cli::formatP2pStatus(m, true);
REQUIRE(json.has_value());
const auto parsed = nlohmann::json::parse(json.value());
CHECK(parsed.at("quarantined_writers") == 1);
CHECK(parsed.at("outbound_sessions") == 28);
CHECK(parsed.at("outbound_failures") == 2);
CHECK(parsed.at("last_outbound_failure").at("age_ms") == 7'000);
m.outboundFailures = 0;
m.quarantinedWriters = 0;
const auto healthy = yams::cli::formatP2pStatus(m, false);
REQUIRE(healthy.has_value());
CHECK(healthy.value().find(" quarantined_writers=0") != std::string::npos);
CHECK(healthy.value().find("last outbound failure") == std::string::npos);
}
TEST_CASE("p2p status refuses a stopped memory sync service", "[cli][p2p][status]") {
yams::daemon::MemorySyncResponse m;
m.started = false;
CHECK_FALSE(yams::cli::formatP2pStatus(m, false).has_value());
}