refactor(console): phase 3 — thread-safe ConsoleModel ingest queue; fix data race

Introduce ConsoleModel (console_model.{h,cpp}): an ImGui-free, thread-safe line
store. Producers on any thread call ingest(), which only briefly locks a small
pending queue; the main thread calls drain() once per frame to move pending
lines into the visible deque and enforce the line cap, reporting how many were
added and evicted from the front.

This fixes the real data race. Previously a single lines_mutex_ guarded both the
line container AND the UI-only interaction state (selection, scroll, auto-scroll
counters), and it was held across the whole render pass — yet render() touched
auto_scroll_ / new_lines_since_scroll_ outside that lock, racing the background
RPC-trace and app-logger producers that call addLine() on worker threads.

Now:
- addLine() only ingests (lock-free w.r.t. the model); safe from any thread.
- render() drains once per frame, then does the cap/selection/scroll bookkeeping
  on the main thread (new drainModel()).
- The visible deque + all selection/scroll fields are main-thread-only, so every
  lines_mutex_ lock is gone — including the one wrapping the entire renderOutput.

Adds testConsoleModel() covering ingest/drain ordering, the line-cap eviction
counts, view-only clear (queued lines survive), and an 8-thread concurrent
ingest/drain stress with no lost lines. Full-node + lite build clean; ctest
green; source hygiene clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-01 18:35:25 -05:00
parent 33735b1d52
commit 779c9682d4
6 changed files with 274 additions and 65 deletions

View File

@@ -0,0 +1,45 @@
// DragonX Wallet - ImGui Edition
// Copyright 2024-2026 The Hush Developers
// Released under the GPLv3
#include "console_model.h"
#include <utility>
namespace dragonx {
namespace ui {
void ConsoleModel::ingest(const std::string& text, ConsoleChannel channel)
{
std::lock_guard<std::mutex> lock(ingest_mutex_);
pending_.push_back({text, channel});
}
ConsoleModel::DrainResult ConsoleModel::drain()
{
std::vector<ConsoleModelLine> incoming;
{
std::lock_guard<std::mutex> lock(ingest_mutex_);
if (pending_.empty()) return {};
incoming.swap(pending_);
}
DrainResult result;
result.added = incoming.size();
for (auto& line : incoming)
lines_.push_back(std::move(line));
while (lines_.size() > max_lines_) {
lines_.pop_front();
++result.popped;
}
return result;
}
void ConsoleModel::clear()
{
lines_.clear();
}
} // namespace ui
} // namespace dragonx