// ============================================================================
// A36 / SLOT A364619 -- offline ASan+UBSan harness for Rev-10 (response to @A25
// review seq=66473).  Targeted regression tests for the five requested review fixes and parser fixtures.
//
//   g++ -std=c++17 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer
//       -Wall -Wextra -Werror -pthread -ldl -o /tmp/test_r10_a25 test_r10_a25_asan.cpp
//   ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 /tmp/test_r10_a25
// ============================================================================
#define A36_R10_UNIT_TEST 1
#include "btc_1m_kline_sub_probe_r10_a25.cpp"

#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <random>
#include <thread>
#include <vector>

// ---------------------------------------------------------------- fixtures
// Golden vector is a clean valid bit=3 OrderBook frame. Positive mixed coverage
// adds a valid protobuf bit=35 Tick payload; arbitrary filler is not mislabeled.
static const char* kHexClean =
    "0a890108d6c4ed211281010803127d0a210900000000809cd540110000000000005e40180522"
    "0b0900008058346fcd4110140a140900000000409cd540110000000000005440180312140900"
    "000000c09cd540110000000000805640180412140900000000009dd540110000000000c06240"
    "18061900f087cab6207a422100b087cab6207a42280130015002";
static const char* kHexBadWire = "0a0d08d6c4ed211206080312021801";


static const uint64_t kSidHsi = 71000662ULL;   // -> fallback csmkt 6

static int g_fail = 0;
static int g_check = 0;

#define CHECK(cond)                                                        \
    do {                                                                   \
        ++g_check;                                                         \
        if (!(cond)) {                                                     \
            std::printf("  FAIL %s:%d  %s\n", __FILE__, __LINE__, #cond);  \
            ++g_fail;                                                      \
        }                                                                  \
    } while (0)

#define CHECK_D(actual, expected)                                                     \
    do {                                                                              \
        ++g_check;                                                                    \
        const double a_ = (actual), e_ = (expected);                                  \
        if (!(std::fabs(a_ - e_) <= 1e-9 * (1.0 + std::fabs(e_)))) {                   \
            std::printf("  FAIL %s:%d  %s = %.9f, want %.9f\n", __FILE__, __LINE__,   \
                        #actual, a_, e_);                                             \
            ++g_fail;                                                                 \
        }                                                                             \
    } while (0)

#define CHECK_U(actual, expected)                                                  \
    do {                                                                           \
        ++g_check;                                                                 \
        const unsigned long long a_ = (unsigned long long)(actual);                \
        const unsigned long long e_ = (unsigned long long)(expected);              \
        if (a_ != e_) {                                                            \
            std::printf("  FAIL %s:%d  %s = %llu, want %llu\n", __FILE__, __LINE__, \
                        #actual, a_, e_);                                          \
            ++g_fail;                                                              \
        }                                                                          \
    } while (0)

// ---------------------------------------------------------------- helpers
static std::string from_hex(const char* hex) {
    std::string out;
    const size_t n = std::strlen(hex);
    for (size_t i = 0; i + 1 < n; i += 2) {
        auto nib = [](char c) -> int {
            if (c >= '0' && c <= '9') return c - '0';
            if (c >= 'a' && c <= 'f') return c - 'a' + 10;
            if (c >= 'A' && c <= 'F') return c - 'A' + 10;
            return 0;
        };
        out.push_back(static_cast<char>((nib(hex[i]) << 4) | nib(hex[i + 1])));
    }
    return out;
}

static void put_double(std::string& s, uint32_t f, double d) {
    pb_write_tag(s, f, 1);
    s.append(reinterpret_cast<const char*>(&d), sizeof(d));
}
static void put_varint(std::string& s, uint32_t f, uint64_t v) {
    pb_write_tag(s, f, 0);
    pb_write_varint(s, v);
}
static void put_bytes(std::string& s, uint32_t f, const std::string& b) {
    pb_write_bytes(s, f, b);
}

struct BitItem {
    uint32_t bit;
    std::string data;
};

static std::string make_envelope(uint64_t sid, const std::vector<BitItem>& items) {
    std::string sq;
    put_varint(sq, 1, sid);
    for (const auto& it : items) {
        std::string bq;
        put_varint(bq, 1, it.bit);
        put_bytes(bq, 2, it.data);
        put_bytes(sq, 2, bq);
    }
    std::string env;
    put_bytes(env, 1, sq);
    return env;
}

// OrderBook #1 bid / #2 ask (OrderBookItem: #1 price double, #2 volume double,
// #3 order_count uint32, #4 orders), #3/#4 doubles, #5/#6 varints.
static std::string make_orderbook(double bp, double bv, double ap, double av) {
    std::string bid, ask, ob;
    put_double(bid, 1, bp);
    put_double(bid, 2, bv);
    put_varint(bid, 3, 5);
    put_double(ask, 1, ap);
    put_double(ask, 2, av);
    put_varint(ask, 3, 4);
    put_bytes(ob, 1, bid);
    put_bytes(ob, 2, ask);
    put_double(ob, 3, 1795488000127.0);
    put_double(ob, 4, 1795488000123.0);
    put_varint(ob, 5, 1);
    put_varint(ob, 6, 1);
    put_varint(ob, 10, 2);
    return ob;
}

// DealStatistics: #4 volume, #5 volume_sold, #6 volume_bought (all double), #15
// volume_precision (uint32).
static std::string make_dealstat(double tot, double sold, double bought, uint32_t prec) {
    std::string ds;
    put_double(ds, 1, 1.0);
    put_double(ds, 4, tot);
    put_double(ds, 5, sold);
    put_double(ds, 6, bought);
    put_varint(ds, 15, prec);
    return ds;
}

// Tick (#1/#2 double, #3 repeated TickItem, #4/#5 varint) with TickItem
// #1 tick_key uint64, #2 type int32, #3 exch_ms uint64, #4 price double,
// #5 volume uint64, #22 string.
static std::string make_tick_batch(uint64_t key0, int32_t type, double px) {
    std::string item, item2, tick;
    put_varint(item, 1, key0);
    put_varint(item, 2, static_cast<uint64_t>(static_cast<uint32_t>(type)));
    put_varint(item, 3, 1795488000123ULL);
    put_double(item, 4, px);
    put_varint(item, 5, 300ULL);
    put_bytes(item, 22, std::string("opaque-hp-string"));
    put_varint(item2, 1, key0 + 1);
    put_varint(item2, 2, static_cast<uint64_t>(static_cast<uint32_t>(type)));
    put_varint(item2, 3, 1795488000124ULL);
    put_double(item2, 4, px + 1.0);
    put_varint(item2, 5, 100ULL);
    put_double(tick, 1, px);
    put_double(tick, 2, 1795488000125.0);
    put_bytes(tick, 3, item);
    put_bytes(tick, 3, item2);
    put_varint(tick, 4, 2);
    put_varint(tick, 5, 2);
    return tick;
}

static void reset_state() {
    std::lock_guard<std::mutex> lk(g_state_mu);
    for (size_t i = 0; i < kMaxTargets; ++i) g_targets[i] = TargetSlot{};
    for (size_t j = 0; j < kMaxMkts; ++j) g_mkt_subs[j] = MktSubSlot{};
    for (size_t r = 0; r < kReqRingCap; ++r) g_req_ring[r] = ReqContext{};
    g_target_count = 0;
    g_mkt_count = 0;
    g_req_ring_pos = 0;
    g_config_valid = false;
    g_mode.store(MODE_PASSIVE_ONLY, std::memory_order_release);
}

static void arm_one(uint64_t sid, uint32_t mkt, int mode = MODE_2B_RAW_0x1843) {
    std::lock_guard<std::mutex> lk(g_state_mu);
    g_targets[0] = TargetSlot{};
    g_targets[0].sid = sid;
    g_targets[0].mkt = mkt;
    g_target_count = 1;
    g_mkt_subs[0] = MktSubSlot{};
    g_mkt_subs[0].mkt = mkt;
    g_mkt_count = 1;
    g_config_valid = true;
    g_mode.store(mode, std::memory_order_release);
}

static long count_in_log(const char* needle) {
    FILE* f = std::fopen(g_log_path, "rb");
    if (!f) return 0;
    std::string all;
    char buf[4096];
    size_t n = 0;
    while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0) all.append(buf, n);
    std::fclose(f);
    long c = 0;
    size_t pos = 0;
    const std::string nd(needle);
    while ((pos = all.find(nd, pos)) != std::string::npos) { ++c; pos += nd.size(); }
    return c;
}

// ============================================================ tests
static void t01_fix1_bounds_no_unsigned_wrap() {
    std::printf("[T01] fix#1 subtraction-only bounds guard\n");
    CHECK(!pb_has_bytes(10, 10, UINT64_MAX));
    CHECK(!pb_has_bytes(10, 10, UINT64_MAX - 9));
    CHECK(pb_has_bytes(10, 10, 0));
    CHECK(!pb_has_bytes(11, 10, 0));
    CHECK(!pb_has_bytes(static_cast<size_t>(-1), 0, 0));
    CHECK(pb_has_bytes(0, 10, 10));
    CHECK(!pb_has_bytes(0, 10, 11));

    // A length prefix of UINT64_MAX must fail closed, not wrap past the buffer.
    std::string evil;
    put_varint(evil, 1, kSidHsi);          // SecurityQuote #1
    pb_write_tag(evil, 2, 2);              // SecurityQuote #2 as bytes ...
    pb_write_varint(evil, UINT64_MAX);     // ... with a UINT64_MAX length
    std::string env;
    put_bytes(env, 1, evil);

    arm_one(kSidHsi, 6);
    const uint64_t mal_before = g_malformed_drops;
    const uint64_t ob_before = g_targets[0].ob.frames;
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(env.data()), env.size());
    CHECK_U(g_malformed_drops, mal_before + 1);
    CHECK_U(g_targets[0].ob.frames, ob_before);
}

static void t02_fix1_truncated_frames_rejected() {
    std::printf("[T02] fix#1/#2 truncated frames fail closed\n");
    arm_one(kSidHsi, 6);
    std::string trunc = from_hex(kHexClean);
    trunc.pop_back();
    const uint64_t mal_before = g_malformed_drops;
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(trunc.data()), trunc.size());
    CHECK_U(g_malformed_drops, mal_before + 1);
    CHECK_U(g_targets[0].ob.frames, 0);

    // trailing garbage byte after a complete frame
    const std::string clean = from_hex(kHexClean);
    std::string trailing = clean;
    trailing.push_back(static_cast<char>(0xFF));
    const uint64_t mal2 = g_malformed_drops;
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(trailing.data()), trailing.size());
    CHECK_U(g_malformed_drops, mal2 + 1);

    // illegal group wire type (0x0B) must be rejected
    std::string grp;
    put_bytes(grp, 1, std::string("\x0B", 1));
    const uint64_t mal3 = g_malformed_drops;
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(grp.data()), grp.size());
    CHECK_U(g_malformed_drops, mal3 + 1);
}

static void t03_golden_clean_frame_decodes() {
    std::printf("[T03] @A25 golden frame (clean) decodes to bid=22130 ask=22131\n");
    reset_state();
    arm_one(kSidHsi, 6);
    const std::string clean = from_hex(kHexClean);
    const long logged_before = count_in_log("push_orderbook_bit3");
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(clean.data()), clean.size());
    CHECK_U(g_targets[0].ob.frames, 1);
    CHECK(count_in_log("push_orderbook_bit3") == logged_before + 1);
    // value-exact proof straight out of the emitted JSONL: best bid / best ask /
    // exchange timestamp of the @A25 golden vector.
    CHECK(count_in_log("\"bid1_p\":22130.000000") > 0);
    CHECK(count_in_log("\"ask1_p\":22131.000000") > 0);
    CHECK(count_in_log("\"exch_ms\":1795488000123") > 0);
}

static void t04_valid_mixed_bits_commit() {
    std::printf("[T04] valid bit=3 OrderBook + valid bit=35 Tick commit together\n");
    reset_state();
    arm_one(kSidHsi, 6);
    std::vector<BitItem> bits;
    bits.push_back(BitItem{3u, make_orderbook(22130.0, 10.0, 22131.0, 11.0)});
    bits.push_back(BitItem{35u, make_tick_batch(7000ULL, 2, 22130.5)});
    const std::string mixed = make_envelope(kSidHsi, bits);
    const uint64_t mal_before = g_malformed_drops;
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(mixed.data()), mixed.size());
    CHECK_U(g_malformed_drops, mal_before);
    CHECK_U(g_targets[0].ob.frames, 1);
    CHECK_U(g_targets[0].tk.frames, 1);
    CHECK_U(g_targets[0].tick_items, 2);
}

static void t04b_malformed_tick_fails_closed() {
    std::printf("[T04B] malformed protobuf bit=35 drops mixed envelope atomically\n");
    reset_state();
    arm_one(kSidHsi, 6);
    std::string malformed_tick = make_tick_batch(8000ULL, 2, 22130.5);
    malformed_tick.pop_back();
    std::vector<BitItem> bits;
    bits.push_back(BitItem{3u, make_orderbook(22130.0, 10.0, 22131.0, 11.0)});
    bits.push_back(BitItem{35u, malformed_tick});
    const std::string mixed = make_envelope(kSidHsi, bits);
    const uint64_t mal_before = g_malformed_drops;
    const long logged_before = count_in_log("push_orderbook_bit3");
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(mixed.data()), mixed.size());
    CHECK_U(g_malformed_drops, mal_before + 1);
    CHECK_U(g_targets[0].ob.frames, 0);
    CHECK_U(g_targets[0].tk.frames, 0);
    CHECK(count_in_log("push_orderbook_bit3") == logged_before);
}

static void t05_bad_wire_orderbook_rejected() {
    std::printf("[T05] fix#3 OrderBook #3 as varint rejected\n");
    reset_state();
    arm_one(kSidHsi, 6);
    const std::string bad = from_hex(kHexBadWire);
    const uint64_t mal_before = g_malformed_drops;
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(bad.data()), bad.size());
    CHECK_U(g_malformed_drops, mal_before + 1);
    CHECK_U(g_targets[0].ob.frames, 0);

    // direct parser call as well
    DecodedOrderBook ob;
    const std::string raw = std::string("\x19", 1) + std::string(8, '\0');
    CHECK(!parse_orderbook_strict(reinterpret_cast<const uint8_t*>(raw.data()), raw.size(), ob));
}

static void t06_fix3_dealstat_wire_lock() {
    std::printf("[T06] fix#3 DealStatistics #1..#13 must be wire-1 double\n");
    DecodedDealStat ds;

    const std::string good = make_dealstat(1000.0, 400.0, 600.0, 2u);
    CHECK(parse_dealstat_strict(reinterpret_cast<const uint8_t*>(good.data()), good.size(), ds));
    CHECK_D(ds.vol_tot, 1000.0);
    CHECK_D(ds.vol_sold, 400.0);
    CHECK_D(ds.vol_bought, 600.0);
    CHECK_U(ds.volume_precision, 2u);

    std::string varint_vol;
    put_varint(varint_vol, 4, 1000u);                 // #4 as varint -> must be refused
    CHECK(!parse_dealstat_strict(reinterpret_cast<const uint8_t*>(varint_vol.data()),
                                 varint_vol.size(), ds));

    std::string nan_vol;
    put_double(nan_vol, 4, std::nan(""));             // non-finite double -> refused
    CHECK(!parse_dealstat_strict(reinterpret_cast<const uint8_t*>(nan_vol.data()),
                                 nan_vol.size(), ds));

    std::string no_vol;
    put_double(no_vol, 1, 1.0);                       // no volume field at all -> refused
    CHECK(!parse_dealstat_strict(reinterpret_cast<const uint8_t*>(no_vol.data()),
                                 no_vol.size(), ds));

    std::string bad14;
    put_double(bad14, 4, 10.0);
    put_varint(bad14, 14, 5u);                        // #14 must be wire-2
    CHECK(!parse_dealstat_strict(reinterpret_cast<const uint8_t*>(bad14.data()),
                                 bad14.size(), ds));

    std::string bad15;
    put_double(bad15, 4, 10.0);
    put_double(bad15, 15, 3.0);                       // #15 must be wire-0
    CHECK(!parse_dealstat_strict(reinterpret_cast<const uint8_t*>(bad15.data()),
                                 bad15.size(), ds));
}

static void t07_fix3_tickitem_wire_lock_and_no_cvd_inference() {
    std::printf("[T07] fix#3 TickItem#4 wire-1 only + honest raw tick_type buckets\n");
    std::vector<DecodedTickItem> items;

    const std::string good = make_tick_batch(5000ULL, 2, 22130.5);
    CHECK(parse_tick_batch_strict(reinterpret_cast<const uint8_t*>(good.data()), good.size(), items));
    CHECK_U(items.size(), 2);
    if (items.size() == 2) {
        CHECK_U(items[0].tick_key, 5000ULL);
        CHECK(items[0].tick_type == 2);
        CHECK_D(items[0].price, 22130.5);
        CHECK_U(items[0].volume_u64, 300ULL);
        CHECK_U(items[0].n_strings, 1);
    }

    std::string bad;
    std::string item;
    put_varint(item, 1, 1ULL);
    put_varint(item, 4, 22130u);                      // #4 as varint -> refused
    put_double(bad, 1, 100.0);
    put_bytes(bad, 3, item);
    CHECK(!parse_tick_batch_strict(reinterpret_cast<const uint8_t*>(bad.data()), bad.size(), items));

    // TickItem without tick_key / without price -> refused
    std::string no_key;
    std::string it2;
    put_double(it2, 4, 1.0);
    put_double(no_key, 1, 1.0);
    put_bytes(no_key, 3, it2);
    CHECK(!parse_tick_batch_strict(reinterpret_cast<const uint8_t*>(no_key.data()),
                                   no_key.size(), items));

    // #22 arbitrary string must never be reinterpreted as a volume/price
    std::string s22;
    std::string it3;
    put_varint(it3, 1, 9ULL);
    put_double(it3, 4, 5.0);
    put_bytes(it3, 22, std::string("999.5"));
    put_double(s22, 1, 1.0);
    put_bytes(s22, 3, it3);
    CHECK(parse_tick_batch_strict(reinterpret_cast<const uint8_t*>(s22.data()), s22.size(), items));
    if (items.size() == 1) {
        CHECK_U(items[0].volume_u64, 0ULL);
        CHECK_D(items[0].price, 5.0);
    }
}

static void t08_fix3_end_to_end_buckets() {
    std::printf("[T08] fix#3 end-to-end: orderbook + dealstat + tick in one clean frame\n");
    reset_state();
    arm_one(kSidHsi, 6);
    std::vector<BitItem> bits;
    bits.push_back(BitItem{3u, make_orderbook(22130.0, 120.0, 22131.0, 90.0)});
    bits.push_back(BitItem{5u, make_dealstat(1000.0, 400.0, 600.0, 2u)});
    bits.push_back(BitItem{35u, make_tick_batch(7000ULL, 2, 22130.5)});
    const std::string env = make_envelope(kSidHsi, bits);
    const uint64_t mal_before = g_malformed_drops;
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(env.data()), env.size());
    CHECK_U(g_malformed_drops, mal_before);
    CHECK_U(g_targets[0].ob.frames, 1);
    CHECK_U(g_targets[0].ds.frames, 1);
    CHECK_U(g_targets[0].tk.frames, 1);
    CHECK_U(g_targets[0].tick_items, 2);
    CHECK_U(g_targets[0].tick_type_hist[2], 2);
    CHECK_U(g_targets[0].tick_type_other, 0);
    CHECK_D(g_targets[0].tick_vol_sum, 400.0);
    // tick_type=2 is NOT mapped to buy/sell CVD anywhere (fields no longer exist)
}

static void t09_offscope_dropped() {
    std::printf("[T09] off-scope security dropped, no state change\n");
    reset_state();
    arm_one(kSidHsi, 6);
    std::vector<BitItem> bits;
    bits.push_back(BitItem{3u, make_orderbook(10.0, 1.0, 11.0, 1.0)});
    const std::string env = make_envelope(71000999ULL, bits);   // not in target table
    const uint64_t off_before = g_offscope_drops;
    decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(env.data()), env.size());
    CHECK_U(g_offscope_drops, off_before + 1);
    CHECK_U(g_targets[0].ob.frames, 0);
}

static void write_file_at(const char* path, const char* body) {
    FILE* f = std::fopen(path, "wb");
    if (!f) return;
    if (body && *body) std::fwrite(body, 1, std::strlen(body), f);
    std::fclose(f);
}

static void t10_fix4_zero_byte_config_disarms() {
    std::printf("[T10] fix#4 0-byte config -> disarm (targets, mkts, inflight ring)\n");
    const char* path = "/tmp/r10_empty.conf";
    write_file_at(path, "");                      // 0 bytes
    setenv("BTC_PROBE_CONF", path, 1);

    reset_state();
    arm_one(kSidHsi, 6);
    const size_t ridx = reserve_req_ctx(0x1811, 6u, 0u, 0u, kSidHsi, 1u);
    CHECK_U(g_req_ring[ridx].active, 1);

    load_fex_safe_config_file();

    CHECK_U(g_mode.load(), MODE_PASSIVE_ONLY);
    CHECK_U(g_target_count, 0);
    CHECK_U(g_mkt_count, 0);
    CHECK(!g_config_valid);
    CHECK_U(g_req_ring[ridx].active, 0);           // ring cleared, no stale retry
    CHECK_U(g_loaded_conf_hash, 0);
    CHECK(count_in_log("disarmed_to_passive") > 0);
    CHECK(count_in_log("conf_empty_zero_bytes") > 0);
}

static void t11_fix4_missing_config_disarms() {
    std::printf("[T11] fix#4 missing/unreadable config -> disarm\n");
    setenv("BTC_PROBE_CONF", "/tmp/r10_does_not_exist.conf", 1);
    reset_state();
    arm_one(kSidHsi, 6);
    load_fex_safe_config_file();
    CHECK_U(g_mode.load(), MODE_PASSIVE_ONLY);
    CHECK_U(g_target_count, 0);
    CHECK(count_in_log("conf_open_failed") > 0);
}

static void t12_fix4_rejected_config_disarms() {
    std::printf("[T12] fix#4 rejected config (bad sid token) -> disarm\n");
    const char* path = "/tmp/r10_bad.conf";
    write_file_at(path, "mode=2b_raw\nsec_id=12x34\n");
    setenv("BTC_PROBE_CONF", path, 1);
    reset_state();
    arm_one(kSidHsi, 6);
    load_fex_safe_config_file();
    CHECK_U(g_mode.load(), MODE_PASSIVE_ONLY);
    CHECK_U(g_target_count, 0);
    CHECK(count_in_log("invalid_sid_token") > 0);
}

static void t13_valid_config_arms() {
    std::printf("[T13] sanity: a valid config still arms (no over-disarm)\n");
    const char* path = "/tmp/r10_good.conf";
    write_file_at(path, "mode=2b_raw\ndelay_sec=0\nsec_id=71000662\nstatus_sec=1\n");
    setenv("BTC_PROBE_CONF", path, 1);
    reset_state();
    load_fex_safe_config_file();
    CHECK_U(g_mode.load(), MODE_2B_RAW_0x1843);
    CHECK_U(g_target_count, 1);
    CHECK_U(g_targets[0].sid, kSidHsi);
    CHECK_U(g_targets[0].mkt, 6);
    CHECK(g_config_valid);
}

static void t14_config_reload_is_transactional() {
    std::printf("[T14] config reload commits one snapshot and resets omitted keys\n");
    const char* path = "/tmp/r10_atomic_reload.conf";
    setenv("BTC_PROBE_CONF", path, 1);
    reset_state();
    write_file_at(path,
        "mode=2b_raw\nsec_id=71000662\nlog=/tmp/r10_atomic_reload.jsonl\n"
        "pull_0x1811=0\npull_count=900\nsub_deal_stat=0\ndelay_sec=5\n");
    load_fex_safe_config_file();
    CHECK(g_config_valid);
    CHECK(!g_send_pull_0x1811);
    CHECK_U(g_pull_count, 900);
    CHECK(!g_sub_dealstat_5);
    CHECK_U(g_min_wait_ms, 5000);
    CHECK(std::string(g_log_path) == "/tmp/r10_atomic_reload.jsonl");

    write_file_at(path, "mode=2b_raw\nsec_id=71000662\n");
    load_fex_safe_config_file();
    CHECK(g_config_valid);
    CHECK(g_send_pull_0x1811);
    CHECK_U(g_pull_count, 300);
    CHECK(g_sub_dealstat_5);
    CHECK_U(g_min_wait_ms, 40000);
    CHECK(std::string(g_log_path) == "/tmp/btc_1m_kline_tap.jsonl");

    write_file_at(path,
        "mode=2b_raw\nsec_id=71000662\nsub_deal_stat=0\n"
        "pull_count=12\ndelay_sec=601\n");
    load_fex_safe_config_file();
    CHECK(!g_config_valid);
    CHECK_U(g_mode.load(), MODE_PASSIVE_ONLY);
    CHECK(g_send_pull_0x1811);
    CHECK_U(g_pull_count, 300);
    CHECK(g_sub_dealstat_5);
    CHECK_U(g_min_wait_ms, 40000);
    CHECK(std::string(g_log_path) == "/tmp/btc_1m_kline_tap.jsonl");
}

static void t14_fix5_timer_drives_without_sendcommand() {
    std::printf("[T15] 250 ms timer retries/timeouts with ZERO SendCommand traffic\n");
    reset_state();
    arm_one(kSidHsi, 6);
    g_last_conf_poll_ms.store(now_mono_ms(), std::memory_order_relaxed);
    g_boot_mono_ms = now_mono_ms();
    CHECK_U(g_timer_started.load(), 0);
    const uint64_t to_before = g_timeout_count;
    const uint64_t tick_before = g_timer_ticks.load();

    // stale in-flight pull request, as if a response never came back
    const size_t ridx = reserve_req_ctx(0x1811, 6u, 0u, 0u, kSidHsi, 1u);
    {
        std::lock_guard<std::mutex> lk(g_state_mu);
        g_req_ring[ridx].pending_bind = false;
        g_req_ring[ridx].req_seq = 4242UL;
        g_req_ring[ridx].sent_mono_ms = now_mono_ms() - (g_req_timeout_ms + 5000);
        g_targets[0].pull_inflight = true;
    }

    ensure_timer_thread_started();      // no SendCommand, no push: timer only
    CHECK_U(g_timer_started.load(), 1);
    std::this_thread::sleep_for(std::chrono::milliseconds(900));

    CHECK(g_timer_ticks.load() >= tick_before + 2);      // ~3-4 ticks in 900 ms
    CHECK(g_timeout_count > to_before);                  // expired request reaped
    CHECK(!g_targets[0].pull_inflight);                  // retry/fail path executed
    CHECK(count_in_log("req_timeout") > 0);
    CHECK(count_in_log("timer_thread_started") > 0);

    stop_timer_thread();
    CHECK(!g_timer_thread.joinable());
    CHECK_U(g_timer_started.load(), 0);
    const uint64_t stopped_ticks = g_timer_ticks.load();
    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    CHECK_U(g_timer_ticks.load(), stopped_ticks);

    ensure_timer_thread_started();
    std::this_thread::sleep_for(std::chrono::milliseconds(300));
    CHECK(g_timer_ticks.load() > stopped_ticks);
    stop_timer_thread();
    CHECK(!g_timer_thread.joinable());
    CHECK_U(g_timer_started.load(), 0);
}

static void t15_fix6_abi_mask_honest() {
    std::printf("[T15] fix#6 abi_live_mask starts at 0, own DSO excluded\n");
    CHECK_U(g_abi_live_mask.load(), 0);
    // resolve_quotepush_vptr must never return a pointer inside our own image
    const void* vptr = resolve_quotepush_vptr();
    Dl_info self{};
    const bool self_known = dladdr(reinterpret_cast<void*>(&resolve_quotepush_vptr), &self) != 0;
    if (vptr != nullptr && self_known && self.dli_fbase != nullptr) {
        CHECK(static_cast<const char*>(vptr) < static_cast<const char*>(self.dli_fbase) ||
              static_cast<const char*>(vptr) >= static_cast<const char*>(self.dli_fbase) + (1 << 30));
    } else {
        CHECK(vptr == nullptr);   // honest: not resolvable offline
        CHECK_U(g_abi_live_mask.load() & 1u, 0);
    }
}

static std::atomic<uint64_t> g_fake_send_calls{0};
static unsigned long fake_send_command(CSChannelType, const CSProtoData&, const CSRequestExt*, void*, QObject*) {
    g_fake_send_calls.fetch_add(1, std::memory_order_relaxed);
    return 77UL;
}

static void t16_sendcommand_locks_before_real() {
    std::printf("[T16] SendCommand hook locks before invoking real\n");
    g_is_cef_child = false;
    g_in_probe_send.store(false, std::memory_order_release);
    g_fake_send_calls.store(0, std::memory_order_relaxed);
    g_real_SendCommand.store(&fake_send_command, std::memory_order_release);
    g_last_conf_poll_ms.store(now_mono_ms(), std::memory_order_relaxed);
    g_boot_mono_ms = now_mono_ms();
    g_mode.store(MODE_PASSIVE_ONLY, std::memory_order_release);
    CSProtoData request{};
    request.cmd_id = 0x1801;
    std::unique_lock<std::recursive_mutex> held(g_send_step_mu);
    std::thread caller([&]() {
        const unsigned long result = _ZN15IFTChannelProxy11SendCommandE13CSChannelTypeRK11CSProtoDataPK12CSRequestExtSt8functionIFvm12CSProtoErrorS3_PK13CSResponseExtEEP7QObject(
            CS_CHANNEL_QUOTE, request, nullptr, nullptr, nullptr);
        CHECK_U(result, 77UL);
    });
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    CHECK_U(g_fake_send_calls.load(std::memory_order_relaxed), 0);
    held.unlock();
    caller.join();
    CHECK_U(g_fake_send_calls.load(std::memory_order_relaxed), 1);
    g_real_SendCommand.store(nullptr, std::memory_order_release);
}

static unsigned long fake_resolved_symbol(CSChannelType, const CSProtoData&, const CSRequestExt*, void*, QObject*) {
    return 99UL;
}

static void t17_lazy_symbol_publication_is_atomic() {
    std::printf("[T17] concurrent lazy symbol publication uses atomic CAS\n");
    std::atomic<RawSendCommandOpaqueFn> slot{nullptr};
    std::atomic<uint64_t> resolver_calls{0};
    std::atomic<bool> all_ok{true};
    std::vector<std::thread> workers;
    for (int i = 0; i < 12; ++i) workers.emplace_back([&]() {
        RawSendCommandOpaqueFn resolved = resolve_cached_symbol(slot, [&]() {
            resolver_calls.fetch_add(1, std::memory_order_relaxed);
            std::this_thread::yield();
            return &fake_resolved_symbol;
        });
        if (resolved != &fake_resolved_symbol || slot.load(std::memory_order_acquire) != &fake_resolved_symbol)
            all_ok.store(false, std::memory_order_relaxed);
    });
    for (auto& worker : workers) worker.join();
    CHECK(all_ok.load(std::memory_order_relaxed));
    CHECK(slot.load(std::memory_order_acquire) == &fake_resolved_symbol);
    CHECK(resolver_calls.load(std::memory_order_relaxed) >= 1);
}

static void t18_fuzz_no_oob() {
    std::printf("[T18] fuzz: 60k mutated/random frames, ASan must stay silent\n");
    reset_state();
    arm_one(kSidHsi, 6);
    const std::string seed = from_hex(kHexClean);
    std::mt19937_64 rng(0xA36ULL);
    uint64_t ok_frames = 0, dropped = 0;
    for (int it = 0; it < 60000; ++it) {
        std::string buf;
        if (it % 3 == 0) {
            buf.assign(static_cast<size_t>(rng() % 320), '\0');
        } else {
            buf = seed;
            const size_t muts = 1 + (rng() % 6);
            for (size_t m = 0; m < muts && !buf.empty(); ++m) {
                const size_t pos = static_cast<size_t>(rng() % buf.size());
                switch (rng() % 3) {
                    case 0: buf[pos] = static_cast<char>(rng() & 0xFF); break;
                    case 1: buf.resize(pos); break;
                    default: buf.insert(buf.begin() + static_cast<long>(pos), static_cast<char>(rng() & 0xFF)); break;
                }
            }
        }
        const uint64_t mal = g_malformed_drops;
        decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(buf.data()), buf.size());
        if (g_malformed_drops > mal) ++dropped; else ++ok_frames;
    }
    std::printf("      frames accepted=%llu dropped=%llu (no ASan report)\n",
                (unsigned long long)ok_frames, (unsigned long long)dropped);
    CHECK(dropped > 0);
    CHECK(ok_frames + dropped == 60000ULL);
}

int main() {
    std::snprintf(g_log_path, sizeof(g_log_path), "%s", "/tmp/r10_unit_tap.jsonl");
    std::remove(g_log_path);

    (void)&detect_cef_child_process;   // referenced only by the disabled auto-start hook
    std::printf("=== A36 Rev-10 A25 offline harness (timer, serialization, atomic config, fixtures) ===\n");
    t15_fix6_abi_mask_honest();
    t01_fix1_bounds_no_unsigned_wrap();
    t02_fix1_truncated_frames_rejected();
    t03_golden_clean_frame_decodes();
    t04_valid_mixed_bits_commit();
    t04b_malformed_tick_fails_closed();
    t05_bad_wire_orderbook_rejected();
    t06_fix3_dealstat_wire_lock();
    t07_fix3_tickitem_wire_lock_and_no_cvd_inference();
    t08_fix3_end_to_end_buckets();
    t09_offscope_dropped();
    t10_fix4_zero_byte_config_disarms();
    t11_fix4_missing_config_disarms();
    t12_fix4_rejected_config_disarms();
    t13_valid_config_arms();
    t14_config_reload_is_transactional();
    t14_fix5_timer_drives_without_sendcommand();
    t16_sendcommand_locks_before_real();
    t17_lazy_symbol_publication_is_atomic();
    t18_fuzz_no_oob();

    std::printf("=== %d checks, %d failures ===\n", g_check, g_fail);
    std::printf("%s\n", g_fail == 0 ? "R10_ASAN_UBSAN_RESULT=PASS" : "R10_ASAN_UBSAN_RESULT=FAIL");
    std::fflush(stdout);
    return g_fail == 0 ? 0 : 1;
}
