Unified raw-only four-flow source
Path: rev10-a88/btc_1m_kline_sub_probe_r10_restore_all_rawonly.cpp
112,604 B · SHA-256 f51f299d327e00d78d043726d7ee3197c2477a0a2fddd32c01ca00e52cb2f47b
// ============================================================================
// btc_1m_kline_sub_probe_r9.cpp (Rev-9: Full A25-66464 6-Gate Hardened Probe)
// Resolves ALL 6 blockers from A25's Rev-2 audit (seq=66464):
// [1] Strict Fail-Closed Scope Filter on ALL Push Paths:
// - Drops ALL push frames when `g_mode == MODE_PASSIVE_ONLY`, `!g_config_valid`,
// or `sid` is NOT in the validated allowlist (`R9_SCOPE_FILTER_TEST = PASS`).
// [2] Native C++17 Decoders for ALL 4 Required Streams (Zero external FTA4 dependency):
// - bit=3 (SBIT_ORDER_BOOK): OrderBook + OrderBookItem (bids/asks/counts/sums/imbalance/exch_ms)
// - bit=5 (SBIT_DEAL_STATISTICS): DealStatistics (vol_total/bought/sold/delta/turnover)
// - bit=35 (SBIT_TICK): Tick + TickItem (tick_key gap check, dir 1/2/3, exch_ms, price, vol, CVD)
// - bit=10001 (SBIT_CUSTOM_KLINE) + 0x1811 KlineRsp (#1=result, #2=sid, #7=bars)
// [3] Per-SID & Per-Flow 1-Hour Telemetry (`kl`, `tk`, `ob`, `ds` counts, first/last mono, silence, gaps, CVD).
// [4] Per-Market 0x1843 Subscription Bounded Retry (<=2) + Automatic Re-Subscribe when FTNN sends
// native outgoing 0x1843 (triggered by 0x18a0 ReSubNotify / reconnect / chart switch).
// [5] Strict All-or-Nothing Protobuf Wire Validation:
// - Rejects truncated fields, trailing bytes (`pos != len`), illegal wire types (3/4/6/7),
// duplicate scalar tags (`seen_mask`), and missing required fields atomically (`malformed_drops`).
// [6] Standard Public Protobuf ABI Hook (`MessageLite::ParseFromArray` / `ParseFromString` +
// `_ZTVN18FTCmdStockQuoteSub9QuotePushE + 16` via `dl_iterate_phdr` RTLD_LOCAL-safe lookup) —
// eliminates unverified internal handler callback signatures.
// ============================================================================
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <atomic>
#include <chrono>
#include <cerrno>
#include <condition_variable>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <fcntl.h>
#include <functional>
#include <link.h>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
#include <unordered_map>
#include <unistd.h>
#include <vector>
// ============================================================================
// Rev-10 (A36 / SLOT A364619) -- response to @A25 review seq=66473
// fix#1 subtraction-only bounds guard (pb_has_bytes) everywhere; no `pos+len`
// fix#2 QuotePush envelope committed all-or-nothing (no per-bit half commit)
// fix#3 wire types locked to libCorePB.so; honest raw tick_type buckets
// fix#4 empty/0-byte/unreadable config -> disarm_to_passive_locked()
// fix#5 independent 250 ms timer thread (timeouts, reload, sustained_status)
// fix#6 own-DSO-excluding dl_iterate_phdr ABI scan + honest abi_live_mask
// ============================================================================
namespace {
enum CSChannelType : uint32_t { CS_CHANNEL_QUOTE = 1 };
enum CSProtoError : uint32_t {};
enum CSBrokerId : uint32_t {};
enum NN_SubscribeBit : uint32_t {};
enum NN_CSMktType : uint32_t {};
struct CSProtoData {
uint16_t cmd_id;
uint16_t _pad[3];
std::string payload;
};
static_assert(sizeof(CSProtoData) == 40, "CSProtoData ABI mismatch");
struct CSRequestExt {
uint16_t timeout_ms = 10000;
uint16_t _pad0[3] = {0, 0, 0};
std::string ext_head;
uint64_t* opt_seq_ptr = nullptr;
uint32_t flags = 0;
uint32_t _pad1 = 0;
};
static_assert(sizeof(CSRequestExt) == 56, "CSRequestExt ABI mismatch");
struct CSResponseExt;
class QObject;
using SendCmdCallbackStdFn = std::function<void(unsigned long, CSProtoError, const CSProtoData&, const CSResponseExt*)>;
static_assert(sizeof(SendCmdCallbackStdFn) == 32, "std::function ABI size mismatch");
enum ProbeMode : int {
MODE_PASSIVE_ONLY = 0,
MODE_2B_RAW_0x1843 = 1
};
constexpr size_t kMaxTargets = 1024;
constexpr size_t kMaxMkts = 32;
constexpr size_t kReqRingCap = 2048;
struct FlowStat {
uint64_t frames = 0;
int64_t first_mono = 0;
int64_t last_mono = 0;
int64_t max_gap_ms = 0;
uint32_t gap_15s_cnt = 0;
void on_rx(int64_t rx_mono, uint64_t add_n = 1) {
if (first_mono == 0) first_mono = rx_mono;
if (last_mono > 0 && rx_mono >= last_mono) {
int64_t g = rx_mono - last_mono;
if (g > max_gap_ms) max_gap_ms = g;
if (g > 15000) ++gap_15s_cnt;
}
last_mono = rx_mono;
frames += add_n;
}
};
struct TargetSlot {
uint64_t sid = 0;
uint32_t mkt = 0;
bool sub_ack_ok = false;
uint8_t pull_tries = 0;
bool pull_inflight = false;
bool pull_ok = false;
bool pull_failed = false;
FlowStat kl;
FlowStat tk;
FlowStat ob;
FlowStat ds;
uint64_t last_bar_ts = 0;
uint64_t tick_items = 0;
uint64_t tick_key_gaps = 0;
uint64_t last_tick_key = 0;
bool has_tick_key = false;
uint64_t tick_type_hist[8] = {0, 0, 0, 0, 0, 0, 0, 0};
uint64_t tick_type_other = 0;
double tick_vol_sum = 0.0;
};
struct MktSubSlot {
uint32_t mkt = 0;
uint8_t tries = 0;
bool inflight = false;
bool ack_ok = false;
bool failed = false;
bool needs_resub = false;
};
struct ReqContext {
unsigned long req_seq = 0;
unsigned long early_seq = 0;
uint16_t cmd_id = 0;
uint32_t mkt = 0;
uint32_t exright = 0;
size_t slot_idx = 0;
uint64_t req_sid = 0;
uint8_t attempt = 0;
bool active = false;
bool pending_bind = false;
int64_t sent_mono_ms = 0;
};
bool g_is_cef_child = false;
std::atomic<int> g_mode{MODE_PASSIVE_ONLY};
bool g_send_pull_0x1811 = true;
bool g_sub_tick_35 = true;
bool g_sub_orderbook_3 = true;
bool g_sub_bbo_4 = false;
bool g_sub_dealstat_5 = true;
uint32_t g_orderbook_prob = 0;
bool g_sub_kline_10001 = true;
uint32_t g_pull_count = 300;
uint32_t g_pull_exright = 0;
uint32_t g_sub_exright = 5;
size_t g_sub_batch = 50;
size_t g_pull_step = 4;
int64_t g_pull_gap_ms = 200;
int64_t g_sub_gap_ms = 200;
int64_t g_req_timeout_ms = 12000;
int64_t g_status_period_ms = 30000;
uint8_t g_max_retries = 2;
uint64_t g_loaded_conf_hash = 0;
std::mutex g_state_mu;
// Rev-10 fix#5: serialises timer ticks against the SendCommand hook.
std::recursive_mutex g_send_step_mu;
TargetSlot g_targets[kMaxTargets];
size_t g_target_count = 0;
MktSubSlot g_mkt_subs[kMaxMkts];
size_t g_mkt_count = 0;
bool g_config_valid = false;
ReqContext g_req_ring[kReqRingCap];
size_t g_req_ring_pos = 0;
uint64_t g_qot_tx_count = 0;
uint64_t g_err_rsp_count = 0;
uint64_t g_timeout_count = 0;
uint64_t g_resub_triggers = 0;
uint64_t g_malformed_drops = 0;
uint64_t g_offscope_drops = 0;
// Rev-10 fix#6: honest dynamic-ABI mask (0 until a FOREIGN image really resolves).
std::atomic<uint32_t> g_abi_live_mask{0u};
inline void abi_mask_set(uint32_t bit) { g_abi_live_mask.fetch_or(bit, std::memory_order_release); }
// Rev-10 fix#5 status counters (declared here: sustained_status reports them).
std::atomic<bool> g_timer_started{false};
std::atomic<uint64_t> g_timer_ticks{0};
char g_log_path[256] = "/tmp/btc_1m_kline_tap.jsonl";
std::mutex g_log_mu;
int g_log_fd = -1;
std::atomic<bool> g_in_probe_send{false};
int64_t g_boot_mono_ms = 0;
int64_t g_min_wait_ms = 40000;
std::atomic<int64_t> g_last_conf_poll_ms{0};
std::atomic<int64_t> g_last_pull_ms{0};
std::atomic<int64_t> g_last_sub_ms{0};
std::atomic<int64_t> g_last_status_ms{0};
std::mutex g_pb_parse_mu;
std::unordered_map<std::thread::id, size_t> g_pb_parse_depth;
std::thread::id g_send_hook_owner;
size_t g_send_hook_depth = 0;
std::thread::id g_probe_send_owner;
thread_local bool g_in_raw_push_dispatch = false;
struct RawPushDispatchGuard {
bool old = g_in_raw_push_dispatch;
RawPushDispatchGuard() { g_in_raw_push_dispatch = true; }
~RawPushDispatchGuard() { g_in_raw_push_dispatch = old; }
};
struct PbParseGuard {
std::thread::id owner = std::this_thread::get_id();
bool outermost = false;
PbParseGuard() {
std::lock_guard<std::mutex> lk(g_pb_parse_mu);
size_t& depth = g_pb_parse_depth[owner];
outermost = (depth == 0);
++depth;
}
~PbParseGuard() {
std::lock_guard<std::mutex> lk(g_pb_parse_mu);
auto it = g_pb_parse_depth.find(owner);
if (it != g_pb_parse_depth.end()) {
if (it->second <= 1) g_pb_parse_depth.erase(it);
else --it->second;
}
}
PbParseGuard(const PbParseGuard&) = delete;
PbParseGuard& operator=(const PbParseGuard&) = delete;
};
struct ProbeSendGuard {
std::thread::id old_owner = g_probe_send_owner;
bool old_active = g_in_probe_send.load(std::memory_order_acquire);
ProbeSendGuard() {
g_probe_send_owner = std::this_thread::get_id();
g_in_probe_send.store(true, std::memory_order_release);
}
~ProbeSendGuard() {
g_in_probe_send.store(old_active, std::memory_order_release);
g_probe_send_owner = old_owner;
}
ProbeSendGuard(const ProbeSendGuard&) = delete;
ProbeSendGuard& operator=(const ProbeSendGuard&) = delete;
};
struct SendCommandGuard {
const std::thread::id owner = std::this_thread::get_id();
SendCommandGuard() { g_send_hook_owner = owner; ++g_send_hook_depth; }
~SendCommandGuard() {
if (g_send_hook_depth > 0) --g_send_hook_depth;
if (g_send_hook_depth == 0) g_send_hook_owner = std::thread::id{};
}
SendCommandGuard(const SendCommandGuard&) = delete;
SendCommandGuard& operator=(const SendCommandGuard&) = delete;
};
struct ProbeConfig {
int mode = MODE_PASSIVE_ONLY;
std::string log_path = "/tmp/btc_1m_kline_tap.jsonl";
int64_t min_wait_ms = 40000;
bool send_pull_0x1811 = true;
bool sub_tick_35 = true;
bool sub_orderbook_3 = true;
bool sub_bbo_4 = false;
bool sub_dealstat_5 = true;
uint32_t orderbook_prob = 0;
bool sub_kline_10001 = true;
uint32_t pull_count = 300;
uint32_t pull_exright = 0;
uint32_t sub_exright = 5;
size_t sub_batch = 50;
size_t pull_step = 4;
int64_t status_period_ms = 30000;
std::vector<uint64_t> sids;
};
void apply_probe_settings_locked(const ProbeConfig& cfg) {
g_send_pull_0x1811 = cfg.send_pull_0x1811;
g_sub_tick_35 = cfg.sub_tick_35;
g_sub_orderbook_3 = cfg.sub_orderbook_3;
g_sub_bbo_4 = cfg.sub_bbo_4;
g_sub_dealstat_5 = cfg.sub_dealstat_5;
g_orderbook_prob = cfg.orderbook_prob;
g_sub_kline_10001 = cfg.sub_kline_10001;
g_pull_count = cfg.pull_count;
g_pull_exright = cfg.pull_exright;
g_sub_exright = cfg.sub_exright;
g_sub_batch = cfg.sub_batch;
g_pull_step = cfg.pull_step;
g_min_wait_ms = cfg.min_wait_ms;
g_status_period_ms = cfg.status_period_ms;
std::lock_guard<std::mutex> log_lk(g_log_mu);
if (cfg.log_path != g_log_path) {
if (g_log_fd >= 0) { ::close(g_log_fd); g_log_fd = -1; }
std::snprintf(g_log_path, sizeof(g_log_path), "%s", cfg.log_path.c_str());
}
}
int64_t now_mono_ms() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
int64_t now_epoch_ms() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
void tap_log(const char* json_line) {
if (g_is_cef_child) return;
std::lock_guard<std::mutex> lk(g_log_mu);
if (g_log_fd < 0) {
g_log_fd = ::open(g_log_path, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
}
if (g_log_fd >= 0) {
size_t n = std::strlen(json_line);
(void)::write(g_log_fd, json_line, n);
(void)::write(g_log_fd, "\n", 1);
}
}
uint64_t fnv1a_64(const char* s, size_t n) {
uint64_t h = 14695981039346656037ULL;
for (size_t i = 0; i < n; ++i) {
h ^= static_cast<unsigned char>(s[i]);
h *= 1099511628211ULL;
}
return h;
}
int find_target_idx_locked(uint64_t sid) {
if (!g_config_valid) return -1;
for (size_t i = 0; i < g_target_count; ++i) {
if (g_targets[i].sid == sid) return static_cast<int>(i);
}
return -1;
}
void pb_write_varint(std::string& out, uint64_t v) {
while (v >= 0x80) {
out.push_back(static_cast<char>((v & 0x7F) | 0x80));
v >>= 7;
}
out.push_back(static_cast<char>(v));
}
void pb_write_tag(std::string& out, uint32_t fn, uint32_t wt) {
pb_write_varint(out, (static_cast<uint64_t>(fn) << 3) | wt);
}
void pb_write_bytes(std::string& out, uint32_t fn, const std::string& b) {
pb_write_tag(out, fn, 2);
pb_write_varint(out, b.size());
out.append(b);
}
bool pb_read_varint_strict(const uint8_t* buf, size_t len, size_t& i, uint64_t& out) {
out = 0;
unsigned sh = 0;
size_t bytes_read = 0;
while (i < len && bytes_read < 10) {
uint8_t b = buf[i++];
++bytes_read;
if (bytes_read == 10 && b > 0x01) return false;
out |= static_cast<uint64_t>(b & 0x7F) << sh;
if ((b & 0x80) == 0) return true;
sh += 7;
}
return false;
}
int64_t as_i64(uint64_t u) { int64_t s; std::memcpy(&s, &u, sizeof(s)); return s; }
int32_t as_i32(uint64_t u) { return static_cast<int32_t>(static_cast<uint32_t>(u)); }
double as_f64(const uint8_t* p) { double d; std::memcpy(&d, p, 8); return d; }
// ---------------------------------------------------------------------------
// Rev-10 fix #1: subtraction-only bounds arithmetic.
// `pos+need>end` wraps for a large unsigned `need` and then silently passes;
// `need <= end - pos` can never wrap once `pos <= end` has been established.
// ---------------------------------------------------------------------------
inline bool pb_has_bytes(size_t pos, size_t end, uint64_t need) {
if (pos > end) return false;
return need <= static_cast<uint64_t>(end - pos);
}
inline bool pb_read_tag_strict(const uint8_t* b, size_t len, size_t& i, uint32_t& fn, uint32_t& wt) {
uint64_t t = 0;
if (!pb_read_varint_strict(b, len, i, t)) return false;
const uint64_t f = t >> 3;
const uint32_t w = static_cast<uint32_t>(t & 7u);
if (f == 0 || f > 0x1FFFFFFFull) return false; // illegal field number
if (w == 3u || w == 4u || w == 6u || w == 7u) return false; // groups / deprecated
fn = static_cast<uint32_t>(f);
wt = w;
return true;
}
inline bool pb_read_len_strict(const uint8_t* b, size_t len, size_t& i, size_t& out_len) {
uint64_t l = 0;
if (!pb_read_varint_strict(b, len, i, l)) return false;
if (!pb_has_bytes(i, len, l)) return false;
out_len = static_cast<size_t>(l);
return true;
}
inline bool pb_read_f64_strict(const uint8_t* b, size_t len, size_t& i, double& out) {
if (!pb_has_bytes(i, len, 8)) return false;
const double d = as_f64(b + i);
if (!std::isfinite(d)) return false;
i += 8;
out = d;
return true;
}
inline bool pb_skip_strict(const uint8_t* b, size_t len, size_t& i, uint32_t w) {
if (w == 0u) { uint64_t v = 0; return pb_read_varint_strict(b, len, i, v); }
if (w == 1u) { if (!pb_has_bytes(i, len, 8)) return false; i += 8; return true; }
if (w == 5u) { if (!pb_has_bytes(i, len, 4)) return false; i += 4; return true; }
if (w == 2u) { size_t l = 0; if (!pb_read_len_strict(b, len, i, l)) return false; i += l; return true; }
return false;
}
bool mark_scalar_seen(uint64_t& mask, uint32_t fn) {
if (fn < 64) {
uint64_t bit = 1ULL << fn;
if ((mask & bit) != 0) return false;
mask |= bit;
}
return true;
}
uint32_t fallback_csmkt_for_sid(uint64_t sid) {
if (sid >= 12000000ULL && sid < 13000000ULL) return 17u;
if (sid >= 88537463800000ULL && sid < 88537464000000ULL) return 37u;
if (sid >= 70000000ULL && sid < 71000000ULL) return 38u;
if (sid >= 71000000ULL && sid < 72000000ULL) return 6u;
if (sid >= 73000000ULL && sid < 74000000ULL) return 13u;
if (sid >= 200000ULL && sid < 300000ULL) return 2u;
if (sid >= 800000ULL && sid < 900000ULL) return 1u;
return 0u;
}
bool is_24h_csmkt(uint32_t csmkt) {
return (csmkt == 17u || csmkt == 37u || csmkt == 38u || csmkt == 11u);
}
std::string encode_1m_kline_sub_prob(bool is_24h, uint32_t exright) {
std::string kt_v2;
pb_write_tag(kt_v2, 1, 0); pb_write_varint(kt_v2, 2);
pb_write_tag(kt_v2, 2, 0); pb_write_varint(kt_v2, 1);
std::string sub_item;
pb_write_tag(sub_item, 1, 0); pb_write_varint(sub_item, exright);
pb_write_bytes(sub_item, 2, kt_v2);
if (is_24h) { pb_write_tag(sub_item, 3, 0); pb_write_varint(sub_item, 0); }
pb_write_tag(sub_item, 4, 0); pb_write_varint(sub_item, 0);
std::string sub_prob;
pb_write_bytes(sub_prob, 1, sub_item);
return sub_prob;
}
std::string encode_single_security_sub(uint64_t sid, bool want_tick, bool want_kl, bool is_24h, std::optional<CSBrokerId> broker_id) {
std::string sec_sub;
pb_write_tag(sec_sub, 1, 0); pb_write_varint(sec_sub, sid);
{ std::string b0; pb_write_tag(b0, 1, 0); pb_write_varint(b0, 0); pb_write_bytes(sec_sub, 2, b0); }
{ std::string b1; pb_write_tag(b1, 1, 0); pb_write_varint(b1, 1); pb_write_bytes(sec_sub, 2, b1); }
if (g_sub_orderbook_3) {
std::string b3; pb_write_tag(b3, 1, 0); pb_write_varint(b3, 3);
if (g_orderbook_prob > 0) { pb_write_tag(b3, 2, 0); pb_write_varint(b3, g_orderbook_prob); }
pb_write_bytes(sec_sub, 2, b3);
}
if (g_sub_bbo_4) {
std::string b4; pb_write_tag(b4, 1, 0); pb_write_varint(b4, 4);
pb_write_bytes(sec_sub, 2, b4);
}
if (g_sub_dealstat_5) {
std::string b5; pb_write_tag(b5, 1, 0); pb_write_varint(b5, 5);
pb_write_bytes(sec_sub, 2, b5);
}
if (want_tick) {
std::string b35; pb_write_tag(b35, 1, 0); pb_write_varint(b35, 35);
pb_write_tag(b35, 2, 0); pb_write_varint(b35, 1);
pb_write_bytes(sec_sub, 2, b35);
}
if (want_kl) {
std::string prob2 = encode_1m_kline_sub_prob(is_24h, g_sub_exright);
std::string bkl; pb_write_tag(bkl, 1, 0); pb_write_varint(bkl, 10001);
pb_write_bytes(bkl, 4, prob2);
pb_write_bytes(sec_sub, 2, bkl);
}
if (broker_id.has_value()) {
pb_write_tag(sec_sub, 3, 0);
pb_write_varint(sec_sub, static_cast<uint64_t>(static_cast<int64_t>(static_cast<uint32_t>(*broker_id))));
}
return sec_sub;
}
std::string encode_batch_subscribe_set_req(const std::vector<std::string>& sec_subs) {
std::string set_req;
for (const auto& s : sec_subs) pb_write_bytes(set_req, 1, s);
return set_req; // isolated full-set mode; no coexisting GUI subscription state
}
std::string encode_1m_kline_pull_req(uint64_t sid, uint32_t count, uint32_t exright, std::optional<CSBrokerId> broker_id) {
std::string kt_v2;
pb_write_tag(kt_v2, 1, 0); pb_write_varint(kt_v2, 2);
pb_write_tag(kt_v2, 2, 0); pb_write_varint(kt_v2, 1);
uint64_t now_s = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()).count()) + 120;
std::string req;
pb_write_tag(req, 1, 0); pb_write_varint(req, sid);
pb_write_tag(req, 2, 0); pb_write_varint(req, 1);
pb_write_tag(req, 3, 0); pb_write_varint(req, exright);
pb_write_tag(req, 4, 0); pb_write_varint(req, 0);
pb_write_tag(req, 5, 0); pb_write_varint(req, 3);
pb_write_tag(req, 7, 0); pb_write_varint(req, now_s);
pb_write_tag(req, 8, 0); pb_write_varint(req, count);
if (broker_id.has_value()) {
pb_write_tag(req, 11, 0);
pb_write_varint(req, static_cast<uint64_t>(static_cast<int64_t>(static_cast<uint32_t>(*broker_id))));
}
pb_write_bytes(req, 12, kt_v2);
return req;
}
void note_malformed(const char* where, uint64_t sid, size_t bytes) {
{
std::lock_guard<std::mutex> lk(g_state_mu);
++g_malformed_drops;
}
char m[224];
std::snprintf(m, sizeof(m),
"{\"ev\":\"malformed_wire_rejected\",\"where\":\"%s\",\"sec_id\":%llu,\"bytes\":%zu}",
where, static_cast<unsigned long long>(sid), bytes);
tap_log(m);
}
struct DecodedBar {
uint64_t ts = 0;
double o = 0.0, c = 0.0, h = 0.0, l = 0.0;
uint64_t vol = 0, turn = 0;
std::string hp_vol, hp_turn;
};
bool parse_kline_item_strict(const uint8_t* p, size_t len, DecodedBar& out,
bool allow_incomplete = false, bool* complete_out = nullptr) {
size_t j = 0;
uint64_t seen = 0;
bool has_ts = false, has_c = false;
if (complete_out) *complete_out = false;
out = DecodedBar{};
while (j < len) {
uint64_t itag = 0;
if (!pb_read_varint_strict(p, len, j, itag) || (itag >> 3) == 0) return false;
uint32_t ifn = static_cast<uint32_t>(itag >> 3), iwt = static_cast<uint32_t>(itag & 7);
if (!mark_scalar_seen(seen, ifn)) return false;
if (iwt == 0) {
uint64_t iv = 0;
if (!pb_read_varint_strict(p, len, j, iv)) return false;
switch (ifn) {
case 1: out.ts = iv; has_ts = (iv > 0); break;
case 3: out.c = static_cast<double>(as_i64(iv)) / 1e9; has_c = true; break;
case 4: out.o = static_cast<double>(as_i64(iv)) / 1e9; break;
case 5: out.h = static_cast<double>(as_i64(iv)) / 1e9; break;
case 6: out.l = static_cast<double>(as_i64(iv)) / 1e9; break;
case 7: out.vol = iv; break;
case 8: out.turn = iv; break;
default: break;
}
} else if (iwt == 1) {
if (!pb_has_bytes(j, len, 8)) return false;
double dv = as_f64(p + j); j += 8;
if (!std::isfinite(dv)) return false;
switch (ifn) {
case 3: out.c = dv; has_c = true; break;
case 4: out.o = dv; break;
case 5: out.h = dv; break;
case 6: out.l = dv; break;
default: break;
}
} else if (iwt == 2) {
uint64_t iln = 0;
if (!pb_read_varint_strict(p, len, j, iln) || !pb_has_bytes(j, len, iln)) return false;
if (ifn == 24) out.hp_vol.assign(reinterpret_cast<const char*>(p + j), static_cast<size_t>(iln));
else if (ifn == 25) out.hp_turn.assign(reinterpret_cast<const char*>(p + j), static_cast<size_t>(iln));
j += static_cast<size_t>(iln);
} else if (iwt == 5) {
if (!pb_has_bytes(j, len, 4)) return false;
j += 4;
} else {
return false;
}
}
const bool complete = has_ts && has_c;
if (complete_out) *complete_out = complete;
return (j == len) && has_ts && (has_c || allow_incomplete);
}
void log_decoded_bar(const char* ev, unsigned long req_seq, uint64_t sid, uint32_t mkt, uint32_t bit, const DecodedBar& b) {
char line[832];
std::snprintf(line, sizeof(line),
"{\"ev\":\"%s\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"seq\":%llu,\"sec_id\":%llu,\"mkt\":%u,\"bit\":%u,"
"\"ts\":%llu,\"o\":%.6f,\"c\":%.6f,\"h\":%.6f,\"l\":%.6f,"
"\"vol\":%llu,\"turn\":%llu,\"hp_vol\":\"%s\",\"hp_turn\":\"%s\"}",
ev, static_cast<long long>(now_epoch_ms()), static_cast<long long>(now_mono_ms()),
static_cast<unsigned long long>(req_seq), static_cast<unsigned long long>(sid),
mkt, bit, static_cast<unsigned long long>(b.ts), b.o, b.c, b.h, b.l,
static_cast<unsigned long long>(b.vol), static_cast<unsigned long long>(b.turn),
b.hp_vol.c_str(), b.hp_turn.c_str());
tap_log(line);
}
struct DecodedOrderBook {
size_t nbids = 0, nasks = 0;
double b1_p = 0.0, b1_v = 0.0, a1_p = 0.0, a1_v = 0.0;
uint64_t b1_c = 0, a1_c = 0;
double b_sum = 0.0, a_sum = 0.0, srv_ms = 0.0, ex_ms = 0.0;
};
bool validate_generic_submsg_strict(const uint8_t* p, size_t len) {
size_t i = 0;
while (i < len) {
uint64_t t = 0;
if (!pb_read_varint_strict(p, len, i, t) || (t >> 3) == 0) return false;
uint32_t w = static_cast<uint32_t>(t & 7);
if (w == 0) { uint64_t v = 0; if (!pb_read_varint_strict(p, len, i, v)) return false; }
else if (w == 1) { if (!pb_has_bytes(i, len, 8) || !std::isfinite(as_f64(p + i))) return false; i += 8; }
else if (w == 2) { uint64_t l = 0; if (!pb_read_varint_strict(p, len, i, l) || !pb_has_bytes(i, len, l)) return false; i += static_cast<size_t>(l); }
else if (w == 5) { if (!pb_has_bytes(i, len, 4)) return false; i += 4; }
else return false;
}
return (i == len);
}
bool parse_orderbook_strict(const uint8_t* p, size_t len, DecodedOrderBook& out) {
auto parse_order_info = [](const uint8_t* op, size_t oln) -> bool {
size_t k = 0; uint64_t seen = 0;
while (k < oln) {
uint64_t t = 0; if (!pb_read_varint_strict(op, oln, k, t) || (t >> 3) == 0) return false;
uint32_t f = static_cast<uint32_t>(t >> 3), w = static_cast<uint32_t>(t & 7);
if (!mark_scalar_seen(seen, f)) return false;
if (f == 1 || f == 2) {
if (w == 0) { uint64_t v = 0; if (!pb_read_varint_strict(op, oln, k, v)) return false; }
else if (w == 1) { if (!pb_has_bytes(k, oln, 8) || !std::isfinite(as_f64(op + k))) return false; k += 8; }
else return false;
} else if (!pb_skip_strict(op, oln, k, w)) return false;
}
return k == oln;
};
auto parse_item = [&](const uint8_t* ip, size_t iln, double& px, double& vl,
uint64_t& cnt, bool& raw_volume) -> bool {
size_t j = 0; uint64_t seen = 0; bool has_p = false, has_v = false;
px = 0.0; vl = 0.0; cnt = 0; raw_volume = false;
while (j < iln) {
uint64_t t = 0; if (!pb_read_varint_strict(ip, iln, j, t) || (t >> 3) == 0) return false;
uint32_t f = static_cast<uint32_t>(t >> 3), w = static_cast<uint32_t>(t & 7);
if (f != 4 && !mark_scalar_seen(seen, f)) return false;
if (f == 1 || f == 2) {
double d = 0.0;
if (w == 1) {
if (!pb_has_bytes(j, iln, 8)) return false;
d = as_f64(ip + j); j += 8;
if (!std::isfinite(d)) return false;
} else if (w == 0) {
uint64_t v = 0; if (!pb_read_varint_strict(ip, iln, j, v)) return false;
if (f == 1) d = static_cast<double>(as_i64(v)) / 1e9;
else { d = static_cast<double>(v); raw_volume = true; }
} else return false;
if (f == 1) { px = d; has_p = true; }
else { if (d < 0.0) return false; vl = d; has_v = true; }
} else if (f == 3) {
uint64_t v = 0; if (w != 0 || !pb_read_varint_strict(ip, iln, j, v)) return false;
cnt = v;
} else if (f == 4) {
uint64_t l = 0; if (w != 2 || !pb_read_varint_strict(ip, iln, j, l) || !pb_has_bytes(j, iln, l)) return false;
if (!parse_order_info(ip + j, static_cast<size_t>(l))) return false;
j += static_cast<size_t>(l);
} else if (!pb_skip_strict(ip, iln, j, w)) return false;
}
return (j == iln) && has_p && has_v;
};
size_t i = 0; uint64_t seen = 0; uint32_t volume_precision = 0;
bool any_raw_volume = false;
out = DecodedOrderBook{};
while (i < len) {
uint64_t t = 0; if (!pb_read_varint_strict(p, len, i, t) || (t >> 3) == 0) return false;
uint32_t f = static_cast<uint32_t>(t >> 3), w = static_cast<uint32_t>(t & 7);
if (f != 1 && f != 2 && f != 11 && f != 12 && !mark_scalar_seen(seen, f)) return false;
if (f == 1 || f == 2) {
uint64_t l = 0; if (w != 2 || !pb_read_varint_strict(p, len, i, l) || !pb_has_bytes(i, len, l)) return false;
size_t sl = static_cast<size_t>(l);
double px = 0.0, vl = 0.0; uint64_t cnt = 0; bool raw_volume = false;
if (!parse_item(p + i, sl, px, vl, cnt, raw_volume)) return false;
any_raw_volume = any_raw_volume || raw_volume;
if (f == 1) {
if (out.nbids == 0 || px > out.b1_p) { out.b1_p = px; out.b1_v = vl; out.b1_c = cnt; }
out.b_sum += vl; ++out.nbids;
} else {
if (out.nasks == 0 || px < out.a1_p) { out.a1_p = px; out.a1_v = vl; out.a1_c = cnt; }
out.a_sum += vl; ++out.nasks;
}
i += sl;
} else if (f == 3 || f == 4 || f == 7 || f == 8 || f == 13) {
double d = 0.0;
if (w == 1) { if (!pb_has_bytes(i, len, 8)) return false; d = as_f64(p + i); i += 8; if (!std::isfinite(d)) return false; }
else if (w == 0) { uint64_t v = 0; if (!pb_read_varint_strict(p, len, i, v)) return false; d = static_cast<double>(v); }
else return false;
if (f == 3) out.srv_ms = d;
else if (f == 4) out.ex_ms = d;
} else if (f == 5 || f == 6 || f == 9 || f == 10) {
uint64_t v = 0; if (w != 0 || !pb_read_varint_strict(p, len, i, v)) return false;
if (f == 10) volume_precision = static_cast<uint32_t>(v);
} else if (f == 11 || f == 12) {
uint64_t l = 0; if (w != 2 || !pb_read_varint_strict(p, len, i, l) || !pb_has_bytes(i, len, l)) return false;
if (!validate_generic_submsg_strict(p + i, static_cast<size_t>(l))) return false;
i += static_cast<size_t>(l);
} else if (!pb_skip_strict(p, len, i, w)) return false;
}
if (any_raw_volume) {
double scale = std::pow(10.0, -static_cast<int>(volume_precision));
out.b1_v *= scale; out.a1_v *= scale; out.b_sum *= scale; out.a_sum *= scale;
}
return (i == len) && (out.nbids > 0 || out.nasks > 0);
}
struct DecodedDealStat {
double vol_tot = 0.0, vol_sold = 0.0, vol_bought = 0.0, turn = 0.0, ratio = 0.0;
uint32_t volume_precision = 0;
bool has_vol_tot = false, has_vol_sold = false, has_vol_bought = false;
};
// Rev-10 fix #3a -- DealStatistics (libCorePB.so):
// #1..#13 : double, WIRE TYPE 1 ONLY (a varint in these slots is rejected)
// #14 : CNKCBAfterDealStatistics sub-message (wire 2)
// #15 : volume_precision uint32 (wire 0)
bool parse_dealstat_strict(const uint8_t* p, size_t len, DecodedDealStat& out) {
size_t i = 0;
uint64_t seen = 0;
out = DecodedDealStat{};
while (i < len) {
uint32_t f = 0, w = 0;
if (!pb_read_tag_strict(p, len, i, f, w)) return false;
if (!mark_scalar_seen(seen, f)) return false;
if (f >= 1u && f <= 13u) {
if (w != 1u) return false; // varint masquerading as double -> reject
double d = 0.0;
if (!pb_read_f64_strict(p, len, i, d)) return false;
switch (f) {
case 4u: out.vol_tot = d; out.has_vol_tot = true; break;
case 5u: out.vol_sold = d; out.has_vol_sold = true; break;
case 6u: out.vol_bought = d; out.has_vol_bought = true; break;
case 7u: out.turn = d; break;
case 8u: out.ratio = d; break;
default: break; // #1..#3, #9..#13 validated, deliberately unused
}
} else if (f == 14u) {
if (w != 2u) return false;
size_t l = 0;
if (!pb_read_len_strict(p, len, i, l)) return false;
if (l > 0 && !validate_generic_submsg_strict(p + i, l)) return false;
i += l;
} else if (f == 15u) {
if (w != 0u) return false;
uint64_t v = 0;
if (!pb_read_varint_strict(p, len, i, v)) return false;
out.volume_precision = static_cast<uint32_t>(v);
} else {
if (!pb_skip_strict(p, len, i, w)) return false;
}
}
return (i == len) && (out.has_vol_tot || out.has_vol_sold || out.has_vol_bought);
}
struct DecodedTickItem {
uint64_t tick_key = 0;
int32_t tick_type = 0; // honest raw #2 int32 -- NO buy/sell inference
uint64_t exch_ms = 0;
double price = 0.0;
uint64_t volume_u64 = 0;
double f7 = 0.0, f8 = 0.0, f16 = 0.0;
bool has_price = false, has_volume = false, price_varint = false;
size_t n_strings = 0;
};
// Rev-10 fix #3b -- FTCmdTick.proto (libCorePB.so, no inference added):
// Tick : #1 price_last_close double, #2 server_send_to_client_time_ms double,
// #3 repeated TickItem, #4 tick_period_type uint32, #5 volume_precision int32
// TickItem : #1 tick_key uint64, #2 type int32, #3 exchange_data_time_ms uint64,
// #4 price double (WIRE 1 ONLY), #5 volume uint64,
// #6/#10/#12/#22/#23 string, #7/#8/#16 double, #9/#11/#13/#14 varint
bool parse_tick_batch_strict(const uint8_t* p, size_t len, std::vector<DecodedTickItem>& out) {
auto parse_one = [](const uint8_t* ip, size_t iln, DecodedTickItem& it) -> bool {
size_t j = 0;
uint64_t seen = 0;
it = DecodedTickItem{};
while (j < iln) {
uint32_t f = 0, w = 0;
if (!pb_read_tag_strict(ip, iln, j, f, w)) return false;
if (!mark_scalar_seen(seen, f)) return false;
if (f == 1u || f == 2u || f == 3u || f == 5u) {
if (w != 0u) return false; // uint64/int32 slots are varints
uint64_t v = 0;
if (!pb_read_varint_strict(ip, iln, j, v)) return false;
if (f == 1u) it.tick_key = v;
else if (f == 2u) it.tick_type = as_i32(v);
else if (f == 3u) it.exch_ms = v;
else { it.volume_u64 = v; it.has_volume = true; }
} else if (f == 4u || f == 7u || f == 8u || f == 16u) {
double d = 0.0;
if (w == 1u) {
if (!pb_read_f64_strict(ip, iln, j, d)) return false;
} else if (w == 0u) {
uint64_t v = 0;
if (!pb_read_varint_strict(ip, iln, j, v)) return false;
d = (f == 4u) ? static_cast<double>(as_i64(v)) / 1e9 : static_cast<double>(v);
if (f == 4u) it.price_varint = true;
} else return false;
if (f == 4u) { it.price = d; it.has_price = true; }
else if (f == 7u) it.f7 = d;
else if (f == 8u) it.f8 = d;
else it.f16 = d;
} else if (f == 9u || f == 11u || f == 13u || f == 14u) {
if (w != 0u) return false;
uint64_t v = 0;
if (!pb_read_varint_strict(ip, iln, j, v)) return false;
} else if (f == 6u || f == 10u || f == 12u || f == 22u || f == 23u) {
if (w != 2u) return false;
size_t l = 0;
if (!pb_read_len_strict(ip, iln, j, l)) return false;
j += l;
++it.n_strings; // opaque strings: never reinterpreted as price/volume
} else {
if (!pb_skip_strict(ip, iln, j, w)) return false;
}
}
return (j == iln) && it.tick_key > 0 && it.has_price && (!it.price_varint || it.exch_ms > 0);
};
size_t i = 0;
uint64_t seen = 0;
out.clear();
while (i < len) {
uint32_t f = 0, w = 0;
if (!pb_read_tag_strict(p, len, i, f, w)) return false;
if (f != 3u && !mark_scalar_seen(seen, f)) return false;
if (f == 3u) {
if (w != 2u) return false;
size_t l = 0;
if (!pb_read_len_strict(p, len, i, l)) return false;
DecodedTickItem it;
if (!parse_one(p + i, l, it)) return false;
out.push_back(it);
i += l;
} else if (f == 1u || f == 2u) {
if (w == 1u) {
double d = 0.0;
if (!pb_read_f64_strict(p, len, i, d)) return false;
} else if (w == 0u) {
uint64_t v = 0;
if (!pb_read_varint_strict(p, len, i, v)) return false;
} else return false;
} else if (f == 4u || f == 5u) {
if (w != 0u) return false;
uint64_t v = 0;
if (!pb_read_varint_strict(p, len, i, v)) return false;
} else {
if (!pb_skip_strict(p, len, i, w)) return false;
}
}
return (i == len) && !out.empty();
}
void decode_quotepush_envelope_strict(const uint8_t* buf, size_t len) {
if (g_mode.load(std::memory_order_acquire) == MODE_PASSIVE_ONLY) {
std::lock_guard<std::mutex> lk(g_state_mu);
++g_offscope_drops;
return;
}
struct StagedSec {
uint64_t sid = 0;
std::vector<DecodedOrderBook> obs;
std::vector<DecodedDealStat> dss;
std::vector<std::vector<DecodedTickItem>> tks;
};
std::vector<StagedSec> staged;
size_t i = 0;
while (i < len) {
uint64_t t = 0;
if (!pb_read_varint_strict(buf, len, i, t) || (t >> 3) == 0) { note_malformed("quotepush_tag", 0, len); return; }
uint32_t f = static_cast<uint32_t>(t >> 3), w = static_cast<uint32_t>(t & 7);
if (w == 2 && f == 1) {
uint64_t sq_ln = 0;
if (!pb_read_varint_strict(buf, len, i, sq_ln) || !pb_has_bytes(i, len, sq_ln)) { note_malformed("secquote_len", 0, len); return; }
const uint8_t* sq = buf + i;
size_t sln = static_cast<size_t>(sq_ln);
size_t j = 0; uint64_t sq_seen = 0;
uint64_t sid = 0; bool has_sid = false;
struct BqRaw { uint32_t bit; const uint8_t* dp; size_t dl; };
std::vector<BqRaw> bqs;
while (j < sln) {
uint64_t qt = 0;
if (!pb_read_varint_strict(sq, sln, j, qt) || (qt >> 3) == 0) { note_malformed("secquote_field", sid, sln); return; }
uint32_t qf = static_cast<uint32_t>(qt >> 3), qw = static_cast<uint32_t>(qt & 7);
if (qf != 2 && !mark_scalar_seen(sq_seen, qf)) { note_malformed("secquote_dup", sid, sln); return; }
if (qw == 0) {
uint64_t qv = 0;
if (!pb_read_varint_strict(sq, sln, j, qv)) { note_malformed("secquote_varint", sid, sln); return; }
if (qf == 1) { sid = qv; has_sid = (qv > 0); }
} else if (qw == 2) {
uint64_t ql = 0;
if (!pb_read_varint_strict(sq, sln, j, ql) || !pb_has_bytes(j, sln, ql)) { note_malformed("bitquote_len", sid, sln); return; }
size_t qln = static_cast<size_t>(ql);
if (qf == 2) {
const uint8_t* bp = sq + j; size_t k = 0; uint64_t b_seen = 0;
uint32_t bit = 0; bool has_bit = false, has_data = false;
const uint8_t* dp = nullptr; size_t dl = 0;
while (k < qln) {
uint64_t bt = 0;
if (!pb_read_varint_strict(bp, qln, k, bt) || (bt >> 3) == 0) { note_malformed("bitquote_tag", sid, qln); return; }
uint32_t bf = static_cast<uint32_t>(bt >> 3), bw = static_cast<uint32_t>(bt & 7);
if (!mark_scalar_seen(b_seen, bf)) { note_malformed("bitquote_dup", sid, qln); return; }
if (bw == 0) {
uint64_t bv = 0;
if (!pb_read_varint_strict(bp, qln, k, bv)) { note_malformed("bitquote_varint", sid, qln); return; }
if (bf == 1) { bit = static_cast<uint32_t>(bv); has_bit = true; }
} else if (bw == 2) {
uint64_t bl = 0;
if (!pb_read_varint_strict(bp, qln, k, bl) || !pb_has_bytes(k, qln, bl)) { note_malformed("bitquote_data_len", sid, qln); return; }
if (bf == 2) { dp = bp + k; dl = static_cast<size_t>(bl); has_data = true; }
k += static_cast<size_t>(bl);
} else if (bw == 1) {
if (!pb_has_bytes(k, qln, 8)) { note_malformed("bitquote_f64", sid, qln); return; }
k += 8;
} else if (bw == 5) {
if (!pb_has_bytes(k, qln, 4)) { note_malformed("bitquote_f32", sid, qln); return; }
k += 4;
} else { note_malformed("bitquote_wt", sid, qln); return; }
}
if (k != qln || !has_bit || !has_data) { note_malformed("bitquote_req", sid, qln); return; }
bqs.push_back({bit, dp, dl});
}
j += qln;
} else if (qw == 1) {
if (!pb_has_bytes(j, sln, 8)) { note_malformed("secquote_f64", sid, sln); return; }
j += 8;
} else if (qw == 5) {
if (!pb_has_bytes(j, sln, 4)) { note_malformed("secquote_f32", sid, sln); return; }
j += 4;
} else { note_malformed("secquote_wt", sid, sln); return; }
}
if (j != sln || !has_sid || bqs.empty()) { note_malformed("secquote_req", sid, sln); return; }
bool allowed = false;
{
std::lock_guard<std::mutex> lk(g_state_mu);
allowed = (find_target_idx_locked(sid) >= 0);
if (!allowed) ++g_offscope_drops;
}
if (allowed) {
// Rev-10 fix #2: the whole QuotePush envelope is committed
// all-or-nothing. A parse error on ANY bit=3/5/35 item discards the
// entire envelope: zero partial state, zero partial log line.
StagedSec ss;
ss.sid = sid;
bool frame_ok = true;
const char* bad_ev = nullptr;
for (const auto& bq : bqs) {
if (bq.bit == 3u) {
DecodedOrderBook ob;
if (!parse_orderbook_strict(bq.dp, bq.dl, ob)) { bad_ev = "orderbook_bit3"; frame_ok = false; break; }
ss.obs.push_back(ob);
} else if (bq.bit == 5u) {
DecodedDealStat ds;
if (!parse_dealstat_strict(bq.dp, bq.dl, ds)) { bad_ev = "dealstat_bit5"; frame_ok = false; break; }
ss.dss.push_back(ds);
} else if (bq.bit == 35u) {
std::vector<DecodedTickItem> tkb;
if (!parse_tick_batch_strict(bq.dp, bq.dl, tkb)) { bad_ev = "tick_bit35"; frame_ok = false; break; }
ss.tks.push_back(std::move(tkb));
}
}
if (!frame_ok) {
note_malformed(bad_ev, sid, len);
return; // atomic drop of the complete frame
}
if (!ss.obs.empty() || !ss.dss.empty() || !ss.tks.empty()) {
staged.push_back(std::move(ss));
}
}
i += sln;
} else if (w == 0) {
uint64_t v = 0; if (!pb_read_varint_strict(buf, len, i, v)) { note_malformed("qp_varint", 0, len); return; }
} else if (w == 2) {
uint64_t l = 0; if (!pb_read_varint_strict(buf, len, i, l) || !pb_has_bytes(i, len, l)) { note_malformed("qp_bytes", 0, len); return; }
i += static_cast<size_t>(l);
} else if (w == 1) {
if (!pb_has_bytes(i, len, 8)) { note_malformed("qp_f64", 0, len); return; }
i += 8;
} else if (w == 5) {
if (!pb_has_bytes(i, len, 4)) { note_malformed("qp_f32", 0, len); return; }
i += 4;
} else { note_malformed("qp_wt", 0, len); return; }
}
if (i != len) { note_malformed("qp_trailing", 0, len); return; }
int64_t rx_m = now_mono_ms();
int64_t rx_w = now_epoch_ms();
for (const auto& ss : staged) {
uint32_t mkt = 0;
{
std::lock_guard<std::mutex> lk(g_state_mu);
int tidx = find_target_idx_locked(ss.sid);
if (tidx < 0) continue;
TargetSlot& t = g_targets[static_cast<size_t>(tidx)];
mkt = t.mkt;
if (!ss.obs.empty()) t.ob.on_rx(rx_m, ss.obs.size());
if (!ss.dss.empty()) t.ds.on_rx(rx_m, ss.dss.size());
if (!ss.tks.empty()) {
t.tk.on_rx(rx_m, ss.tks.size());
for (const auto& batch : ss.tks) {
for (const auto& it : batch) {
++t.tick_items;
if (t.has_tick_key && it.tick_key > t.last_tick_key + 1) ++t.tick_key_gaps;
t.last_tick_key = it.tick_key;
t.has_tick_key = true;
// Rev-10 fix #3c: raw TickItem#2 buckets, no derived CVD.
if (it.tick_type >= 0 && it.tick_type < 8) ++t.tick_type_hist[it.tick_type];
else ++t.tick_type_other;
t.tick_vol_sum += static_cast<double>(it.volume_u64);
}
}
}
}
for (const auto& ob : ss.obs) {
double tot = ob.b_sum + ob.a_sum;
double imb = tot > 0.0 ? (ob.b_sum - ob.a_sum) / tot : 0.0;
char line[480];
std::snprintf(line, sizeof(line),
"{\"ev\":\"push_orderbook_bit3\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"sec_id\":%llu,\"mkt\":%u,"
"\"nbids\":%zu,\"nasks\":%zu,\"bid1_p\":%.6f,\"bid1_v\":%.4f,\"bid1_c\":%llu,"
"\"ask1_p\":%.6f,\"ask1_v\":%.4f,\"ask1_c\":%llu,\"bid_sum\":%.4f,\"ask_sum\":%.4f,\"imb\":%.6f,\"exch_ms\":%.0f}",
static_cast<long long>(rx_w), static_cast<long long>(rx_m),
static_cast<unsigned long long>(ss.sid), mkt, ob.nbids, ob.nasks,
ob.b1_p, ob.b1_v, static_cast<unsigned long long>(ob.b1_c),
ob.a1_p, ob.a1_v, static_cast<unsigned long long>(ob.a1_c),
ob.b_sum, ob.a_sum, imb, ob.ex_ms);
tap_log(line);
}
for (const auto& ds : ss.dss) {
char line[384];
std::snprintf(line, sizeof(line),
"{\"ev\":\"push_dealstat_bit5\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"sec_id\":%llu,\"mkt\":%u,"
"\"vol_total\":%.4f,\"vol_bought\":%.4f,\"vol_sold\":%.4f,\"delta\":%.4f,\"turn\":%.2f}",
static_cast<long long>(rx_w), static_cast<long long>(rx_m),
static_cast<unsigned long long>(ss.sid), mkt,
ds.vol_tot, ds.vol_bought, ds.vol_sold, ds.vol_bought - ds.vol_sold, ds.turn);
tap_log(line);
}
for (const auto& batch : ss.tks) {
for (const auto& it : batch) {
char line[512];
std::snprintf(line, sizeof(line),
"{\"ev\":\"push_tick_bit35\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"sec_id\":%llu,\"mkt\":%u,"
"\"tick_key\":%llu,\"tick_type\":%d,\"exch_ms\":%llu,\"price\":%.6f,\"vol_u64\":%llu,"
"\"f7\":%.6f,\"f8\":%.6f,\"f16\":%.6f,\"n_str\":%zu}",
static_cast<long long>(rx_w), static_cast<long long>(rx_m),
static_cast<unsigned long long>(ss.sid), mkt,
static_cast<unsigned long long>(it.tick_key), it.tick_type,
static_cast<unsigned long long>(it.exch_ms), it.price,
static_cast<unsigned long long>(it.volume_u64),
it.f7, it.f8, it.f16, it.n_strings);
tap_log(line);
}
}
}
}
size_t reserve_req_ctx(uint16_t cmd_id, uint32_t mkt, uint32_t exright,
size_t slot_idx, uint64_t sid, uint8_t attempt) {
std::lock_guard<std::mutex> lk(g_state_mu);
size_t idx = g_req_ring_pos % kReqRingCap;
++g_req_ring_pos;
ReqContext& slot = g_req_ring[idx];
slot.req_seq = 0; slot.early_seq = 0;
slot.cmd_id = cmd_id; slot.mkt = mkt; slot.exright = exright;
slot.slot_idx = slot_idx; slot.req_sid = sid; slot.attempt = attempt;
slot.active = true; slot.pending_bind = true;
slot.sent_mono_ms = now_mono_ms();
return idx;
}
void bind_or_cancel_req_ctx(size_t idx, unsigned long seq_no) {
std::lock_guard<std::mutex> lk(g_state_mu);
ReqContext& slot = g_req_ring[idx];
if (seq_no == 0) { slot.active = false; slot.pending_bind = false; return; }
if (!slot.active && slot.early_seq == seq_no) { slot.pending_bind = false; return; }
slot.req_seq = seq_no; slot.pending_bind = false;
}
bool pop_req_ctx(unsigned long seq, uint16_t expected_cmd, ReqContext& out) {
std::lock_guard<std::mutex> lk(g_state_mu);
for (size_t i = 0; i < kReqRingCap; ++i) {
if (g_req_ring[i].active && !g_req_ring[i].pending_bind && g_req_ring[i].req_seq == seq) {
out = g_req_ring[i]; g_req_ring[i].active = false; return true;
}
}
for (size_t i = 0; i < kReqRingCap; ++i) {
if (g_req_ring[i].active && g_req_ring[i].pending_bind && g_req_ring[i].cmd_id == expected_cmd) {
out = g_req_ring[i]; out.req_seq = seq;
g_req_ring[i].active = false; g_req_ring[i].pending_bind = false; g_req_ring[i].early_seq = seq;
return true;
}
}
return false;
}
void mark_sub_retry_or_fail_locked(size_t midx, const char* reason, int32_t code) {
if (midx >= g_mkt_count) return;
MktSubSlot& ms = g_mkt_subs[midx];
ms.inflight = false;
++g_err_rsp_count;
if (ms.tries <= g_max_retries) {
char msg[240];
std::snprintf(msg, sizeof(msg),
"{\"ev\":\"sub_0x1843_retry_queued\",\"mkt\":%u,\"reason\":\"%s\",\"code\":%d,\"tries\":%u}",
ms.mkt, reason, code, static_cast<unsigned>(ms.tries));
tap_log(msg);
} else {
ms.failed = true;
char msg[240];
std::snprintf(msg, sizeof(msg),
"{\"ev\":\"sub_0x1843_failed_final\",\"mkt\":%u,\"reason\":\"%s\",\"code\":%d,\"tries\":%u}",
ms.mkt, reason, code, static_cast<unsigned>(ms.tries));
tap_log(msg);
}
}
void mark_pull_retry_or_fail_locked(size_t tidx, const char* reason, int32_t code) {
if (tidx >= g_target_count) return;
TargetSlot& t = g_targets[tidx];
t.pull_inflight = false;
++g_err_rsp_count;
if (t.pull_tries <= g_max_retries) {
char msg[256];
std::snprintf(msg, sizeof(msg),
"{\"ev\":\"pull_0x1811_retry_queued\",\"sec_id\":%llu,\"mkt\":%u,\"reason\":\"%s\",\"code\":%d,\"tries\":%u}",
static_cast<unsigned long long>(t.sid), t.mkt, reason, code, static_cast<unsigned>(t.pull_tries));
tap_log(msg);
} else {
t.pull_failed = true;
char msg[256];
std::snprintf(msg, sizeof(msg),
"{\"ev\":\"pull_0x1811_failed_final\",\"sec_id\":%llu,\"mkt\":%u,\"reason\":\"%s\",\"code\":%d,\"tries\":%u}",
static_cast<unsigned long long>(t.sid), t.mkt, reason, code, static_cast<unsigned>(t.pull_tries));
tap_log(msg);
}
}
void on_0x1843_rsp_cb(unsigned long req_seq, CSProtoError err, const CSProtoData& rsp, const CSResponseExt*) {
ReqContext ctx{};
bool has_ctx = pop_req_ctx(req_seq, 0x1843, ctx);
int64_t rtt = has_ctx ? (now_mono_ms() - ctx.sent_mono_ms) : -1;
if (!has_ctx) {
char umsg[192];
std::snprintf(umsg, sizeof(umsg),
"{\"ev\":\"unmatched_late_rsp\",\"cmd_hex\":\"0x1843\",\"seq\":%llu,\"bytes\":%zu}",
static_cast<unsigned long long>(req_seq), rsp.payload.size());
tap_log(umsg);
return;
}
const auto* b = reinterpret_cast<const uint8_t*>(rsp.payload.data());
size_t i = 0, n = rsp.payload.size(); uint64_t seen = 0;
int32_t res = -1, warn = 0, max_sub = -1;
bool got_res = false, wire_ok = true;
while (i < n) {
uint64_t tag = 0;
if (!pb_read_varint_strict(b, n, i, tag) || (tag >> 3) == 0) { wire_ok = false; break; }
uint32_t fn = static_cast<uint32_t>(tag >> 3), wt = static_cast<uint32_t>(tag & 7);
if (!mark_scalar_seen(seen, fn)) { wire_ok = false; break; }
if (wt == 0) {
uint64_t v = 0;
if (!pb_read_varint_strict(b, n, i, v)) { wire_ok = false; break; }
if (fn == 1) { res = as_i32(v); got_res = true; }
else if (fn == 2) warn = as_i32(v);
else if (fn == 3) max_sub = as_i32(v);
} else if (wt == 2) {
uint64_t ln = 0;
if (!pb_read_varint_strict(b, n, i, ln) || !pb_has_bytes(i, n, ln)) { wire_ok = false; break; }
i += static_cast<size_t>(ln);
} else if (wt == 1) { if (!pb_has_bytes(i, n, 8)) { wire_ok = false; break; } i += 8; }
else if (wt == 5) { if (!pb_has_bytes(i, n, 4)) { wire_ok = false; break; } i += 4; }
else { wire_ok = false; break; }
}
if (!wire_ok || i != n || static_cast<uint32_t>(err) != 0 || !got_res || res != 0) {
std::lock_guard<std::mutex> lk(g_state_mu);
mark_sub_retry_or_fail_locked(ctx.slot_idx, !wire_ok ? "malformed" : "err_or_result_nonzero", res);
} else {
std::lock_guard<std::mutex> lk(g_state_mu);
if (ctx.slot_idx < g_mkt_count) {
MktSubSlot& ms = g_mkt_subs[ctx.slot_idx];
ms.inflight = false;
if (ms.needs_resub) {
ms.needs_resub = false;
ms.ack_ok = false;
ms.failed = false;
ms.tries = 0;
} else {
ms.ack_ok = true;
for (size_t ti = 0; ti < g_target_count; ++ti) {
if (g_targets[ti].mkt == ctx.mkt) g_targets[ti].sub_ack_ok = true;
}
}
}
}
char msg[320];
std::snprintf(msg, sizeof(msg),
"{\"ev\":\"rsp_0x1843\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"seq\":%llu,\"mkt\":%u,\"rtt_ms\":%lld,"
"\"err\":%u,\"result\":%d,\"warn\":%d,\"max_sub_count\":%d}",
static_cast<long long>(now_epoch_ms()), static_cast<long long>(now_mono_ms()),
static_cast<unsigned long long>(req_seq), ctx.mkt, static_cast<long long>(rtt),
static_cast<unsigned>(err), res, warn, max_sub);
tap_log(msg);
}
void on_0x1811_rsp_cb(unsigned long req_seq, CSProtoError err, const CSProtoData& rsp, const CSResponseExt*) {
ReqContext ctx{};
bool has_ctx = pop_req_ctx(req_seq, 0x1811, ctx);
int64_t rtt = has_ctx ? (now_mono_ms() - ctx.sent_mono_ms) : -1;
if (!has_ctx) {
char umsg[192];
std::snprintf(umsg, sizeof(umsg),
"{\"ev\":\"unmatched_late_rsp\",\"cmd_hex\":\"0x1811\",\"seq\":%llu,\"bytes\":%zu}",
static_cast<unsigned long long>(req_seq), rsp.payload.size());
tap_log(umsg);
return;
}
if (static_cast<uint32_t>(err) != 0 || rsp.payload.empty()) {
std::lock_guard<std::mutex> lk(g_state_mu);
mark_pull_retry_or_fail_locked(ctx.slot_idx, "transport_or_empty", static_cast<int32_t>(err));
return;
}
const auto* buf = reinterpret_cast<const uint8_t*>(rsp.payload.data());
size_t i = 0, n = rsp.payload.size(); uint64_t seen = 0;
int32_t result = 0; bool has_result = false, wire_ok = true;
uint64_t rsp_sid = 0, next_time = 0;
uint32_t kline_type = 0, exright = 0;
bool has_more = false;
size_t placeholder_count = 0;
std::vector<DecodedBar> bars;
while (i < n) {
uint64_t tag = 0;
if (!pb_read_varint_strict(buf, n, i, tag) || (tag >> 3) == 0) { wire_ok = false; break; }
uint32_t fn = static_cast<uint32_t>(tag >> 3), wt = static_cast<uint32_t>(tag & 7);
if (fn != 7 && !mark_scalar_seen(seen, fn)) { wire_ok = false; break; }
if (wt == 0) {
uint64_t v = 0;
if (!pb_read_varint_strict(buf, n, i, v)) { wire_ok = false; break; }
switch (fn) {
case 1: result = as_i32(v); has_result = true; break;
case 2: rsp_sid = v; break;
case 3: kline_type = static_cast<uint32_t>(v); break;
case 4: exright = static_cast<uint32_t>(v); break;
case 8: has_more = (v != 0); break;
case 9: next_time = v; break;
default: break;
}
} else if (wt == 2) {
uint64_t ln = 0;
if (!pb_read_varint_strict(buf, n, i, ln) || !pb_has_bytes(i, n, ln)) { wire_ok = false; break; }
if (fn == 7) {
DecodedBar b;
bool complete = false;
if (parse_kline_item_strict(buf + i, static_cast<size_t>(ln), b, true, &complete)) {
if (complete) bars.push_back(std::move(b));
else ++placeholder_count; // structurally valid forming/future slot without OHLC
} else { wire_ok = false; break; }
}
i += static_cast<size_t>(ln);
} else if (wt == 1) { if (!pb_has_bytes(i, n, 8)) { wire_ok = false; break; } i += 8; }
else if (wt == 5) { if (!pb_has_bytes(i, n, 4)) { wire_ok = false; break; } i += 4; }
else { wire_ok = false; break; }
}
if (!wire_ok || i != n || !has_result || result != 0 || rsp_sid == 0 ||
(ctx.req_sid != 0 && rsp_sid != ctx.req_sid) || bars.empty()) {
const char* why = (!wire_ok || i != n) ? "malformed_wire" :
(!has_result || result != 0) ? "app_result_nonzero" :
(rsp_sid != ctx.req_sid) ? "sid_mismatch" : "empty_bars";
if (!wire_ok || i != n) note_malformed("kline_rsp_0x1811", ctx.req_sid, n);
char emsg[384];
std::snprintf(emsg, sizeof(emsg),
"{\"ev\":\"rsp_0x1811_rejected\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"seq\":%llu,"
"\"req_sid\":%llu,\"rsp_sid\":%llu,\"mkt\":%u,\"result\":%d,\"bars\":%zu,\"reason\":\"%s\"}",
static_cast<long long>(now_epoch_ms()), static_cast<long long>(now_mono_ms()),
static_cast<unsigned long long>(req_seq),
static_cast<unsigned long long>(ctx.req_sid), static_cast<unsigned long long>(rsp_sid),
ctx.mkt, result, bars.size(), why);
tap_log(emsg);
std::lock_guard<std::mutex> lk(g_state_mu);
mark_pull_retry_or_fail_locked(ctx.slot_idx, why, result);
return;
}
for (const auto& b : bars) log_decoded_bar("rsp_kline_0x1811", req_seq, rsp_sid, ctx.mkt, 0x1811u, b);
{
std::lock_guard<std::mutex> lk(g_state_mu);
if (ctx.slot_idx < g_target_count) {
g_targets[ctx.slot_idx].pull_inflight = false;
g_targets[ctx.slot_idx].pull_ok = true;
}
}
char sum[448];
std::snprintf(sum, sizeof(sum),
"{\"ev\":\"rsp_0x1811_summary\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"seq\":%llu,"
"\"req_sid\":%llu,\"rsp_sid\":%llu,\"mkt\":%u,\"ktype\":%u,\"exright\":%u,"
"\"result\":%d,\"bar_count\":%zu,\"placeholder_count\":%zu,\"first_ts\":%llu,\"last_ts\":%llu,\"has_more\":%d,\"next_time\":%llu,\"rtt_ms\":%lld}",
static_cast<long long>(now_epoch_ms()), static_cast<long long>(now_mono_ms()),
static_cast<unsigned long long>(req_seq),
static_cast<unsigned long long>(ctx.req_sid), static_cast<unsigned long long>(rsp_sid),
ctx.mkt, kline_type, exright, result, bars.size(), placeholder_count,
static_cast<unsigned long long>(bars.front().ts), static_cast<unsigned long long>(bars.back().ts),
has_more ? 1 : 0, static_cast<unsigned long long>(next_time), static_cast<long long>(rtt));
tap_log(sum);
}
void decode_0x1844_push_kline_strict(uint64_t sec_id, uint32_t bit, const std::string& raw) {
if (g_mode.load(std::memory_order_acquire) == MODE_PASSIVE_ONLY) {
std::lock_guard<std::mutex> lk(g_state_mu);
++g_offscope_drops;
return;
}
uint32_t mkt = 0;
{
std::lock_guard<std::mutex> lk(g_state_mu);
int tidx = find_target_idx_locked(sec_id);
if (tidx < 0) { ++g_offscope_drops; return; }
mkt = g_targets[static_cast<size_t>(tidx)].mkt;
}
const auto* buf = reinterpret_cast<const uint8_t*>(raw.data());
size_t i = 0, n = raw.size();
std::vector<DecodedBar> bars;
bool wire_ok = true;
while (i < n) {
uint64_t tag = 0;
if (!pb_read_varint_strict(buf, n, i, tag) || (tag >> 3) == 0) { wire_ok = false; break; }
uint32_t fn = static_cast<uint32_t>(tag >> 3), wt = static_cast<uint32_t>(tag & 7);
if (wt == 0) {
uint64_t v = 0;
if (!pb_read_varint_strict(buf, n, i, v)) { wire_ok = false; break; }
} else if (wt == 2) {
uint64_t ln = 0;
if (!pb_read_varint_strict(buf, n, i, ln) || !pb_has_bytes(i, n, ln)) { wire_ok = false; break; }
size_t sln = static_cast<size_t>(ln);
if (bit == 10001u && fn == 1) {
size_t k = i, kend = i + sln;
while (k < kend) {
uint64_t ktag = 0;
if (!pb_read_varint_strict(buf, kend, k, ktag) || (ktag >> 3) == 0) { wire_ok = false; break; }
uint32_t kfn = static_cast<uint32_t>(ktag >> 3), kwt = static_cast<uint32_t>(ktag & 7);
if (kwt == 0) {
uint64_t kv = 0; if (!pb_read_varint_strict(buf, kend, k, kv)) { wire_ok = false; break; }
} else if (kwt == 2) {
uint64_t kln = 0;
if (!pb_read_varint_strict(buf, kend, k, kln) || !pb_has_bytes(k, kend, kln)) { wire_ok = false; break; }
if (kfn == 3) {
DecodedBar b;
if (!parse_kline_item_strict(buf + k, static_cast<size_t>(kln), b)) { wire_ok = false; break; }
bars.push_back(std::move(b));
}
k += static_cast<size_t>(kln);
} else if (kwt == 1) { if (!pb_has_bytes(k, kend, 8)) { wire_ok = false; break; } k += 8; }
else if (kwt == 5) { if (!pb_has_bytes(k, kend, 4)) { wire_ok = false; break; } k += 4; }
else { wire_ok = false; break; }
}
if (!wire_ok || k != kend) { wire_ok = false; break; }
} else if (fn == 6) {
DecodedBar b;
if (!parse_kline_item_strict(buf + i, sln, b)) { wire_ok = false; break; }
bars.push_back(std::move(b));
}
i += sln;
} else if (wt == 1) { if (!pb_has_bytes(i, n, 8)) { wire_ok = false; break; } i += 8; }
else if (wt == 5) { if (!pb_has_bytes(i, n, 4)) { wire_ok = false; break; } i += 4; }
else { wire_ok = false; break; }
}
if (!wire_ok || i != n || bars.empty()) {
note_malformed("push_kline_0x1844", sec_id, n);
return;
}
int64_t rx_m = now_mono_ms();
{
std::lock_guard<std::mutex> lk(g_state_mu);
int tidx = find_target_idx_locked(sec_id);
if (tidx >= 0) {
TargetSlot& t = g_targets[static_cast<size_t>(tidx)];
t.kl.on_rx(rx_m, bars.size());
t.last_bar_ts = bars.back().ts;
}
}
for (const auto& b : bars) log_decoded_bar("push_kline_0x1844", 0UL, sec_id, mkt, bit, b);
}
void sweep_timeouts_and_emit_sustained_status() {
int64_t now_m = now_mono_ms();
int64_t now_w = now_epoch_ms();
{
std::lock_guard<std::mutex> lk(g_state_mu);
for (size_t i = 0; i < kReqRingCap; ++i) {
if (g_req_ring[i].active && !g_req_ring[i].pending_bind &&
(now_m - g_req_ring[i].sent_mono_ms) >= g_req_timeout_ms) {
ReqContext expired = g_req_ring[i];
g_req_ring[i].active = false;
++g_timeout_count;
char tmsg[256];
std::snprintf(tmsg, sizeof(tmsg),
"{\"ev\":\"req_timeout\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"seq\":%llu,\"cmd_hex\":\"0x%04x\",\"sec_id\":%llu}",
static_cast<long long>(now_w), static_cast<long long>(now_m),
static_cast<unsigned long long>(expired.req_seq), expired.cmd_id,
static_cast<unsigned long long>(expired.req_sid));
tap_log(tmsg);
if (expired.cmd_id == 0x1843) mark_sub_retry_or_fail_locked(expired.slot_idx, "timeout", -1);
else if (expired.cmd_id == 0x1811) mark_pull_retry_or_fail_locked(expired.slot_idx, "timeout", -1);
}
}
}
int64_t last_st = g_last_status_ms.load(std::memory_order_relaxed);
if (now_m - last_st >= g_status_period_ms &&
g_last_status_ms.compare_exchange_strong(last_st, now_m, std::memory_order_relaxed)) {
std::lock_guard<std::mutex> lk(g_state_mu);
for (size_t i = 0; i < g_target_count; ++i) {
const TargetSlot& t = g_targets[i];
auto sil = [&](const FlowStat& f) -> long long {
return f.last_mono > 0 ? static_cast<long long>(now_m - f.last_mono) : -1LL;
};
char ttbuf[160];
std::snprintf(ttbuf, sizeof(ttbuf), "%llu/%llu/%llu/%llu/%llu/%llu/%llu/%llu",
static_cast<unsigned long long>(t.tick_type_hist[0]),
static_cast<unsigned long long>(t.tick_type_hist[1]),
static_cast<unsigned long long>(t.tick_type_hist[2]),
static_cast<unsigned long long>(t.tick_type_hist[3]),
static_cast<unsigned long long>(t.tick_type_hist[4]),
static_cast<unsigned long long>(t.tick_type_hist[5]),
static_cast<unsigned long long>(t.tick_type_hist[6]),
static_cast<unsigned long long>(t.tick_type_hist[7]));
char smsg[1024];
std::snprintf(smsg, sizeof(smsg),
"{\"ev\":\"sustained_status\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"uptime_s\":%lld,"
"\"sec_id\":%llu,\"mkt\":%u,\"sub_ok\":%d,\"hist_ok\":%d,\"hist_fail\":%d,"
"\"kl_n\":%llu,\"kl_sil_ms\":%lld,\"kl_gap_ms\":%lld,"
"\"tk_n\":%llu,\"tk_items\":%llu,\"tk_gaps\":%llu,\"tk_sil_ms\":%lld,\"tk_gap_ms\":%lld,"
"\"ob_n\":%llu,\"ob_sil_ms\":%lld,\"ob_gap_ms\":%lld,"
"\"ds_n\":%llu,\"ds_sil_ms\":%lld,\"tt_hist\":\"%s\",\"tt_other\":%llu,\"tick_vol\":%.4f,"
"\"qot_tx\":%llu,\"err_rsp\":%llu,\"timeouts\":%llu,\"resubs\":%llu,\"malformed\":%llu,\"offscope\":%llu,"
"\"abi_mask\":%u,\"timer_ticks\":%llu,\"timer_armed\":%d}",
static_cast<long long>(now_w), static_cast<long long>(now_m),
static_cast<long long>((now_m - g_boot_mono_ms) / 1000),
static_cast<unsigned long long>(t.sid), t.mkt,
t.sub_ack_ok ? 1 : 0, t.pull_ok ? 1 : 0, t.pull_failed ? 1 : 0,
static_cast<unsigned long long>(t.kl.frames), sil(t.kl), static_cast<long long>(t.kl.max_gap_ms),
static_cast<unsigned long long>(t.tk.frames), static_cast<unsigned long long>(t.tick_items),
static_cast<unsigned long long>(t.tick_key_gaps), sil(t.tk), static_cast<long long>(t.tk.max_gap_ms),
static_cast<unsigned long long>(t.ob.frames), sil(t.ob), static_cast<long long>(t.ob.max_gap_ms),
static_cast<unsigned long long>(t.ds.frames), sil(t.ds), ttbuf,
static_cast<unsigned long long>(t.tick_type_other), t.tick_vol_sum,
static_cast<unsigned long long>(g_qot_tx_count),
static_cast<unsigned long long>(g_err_rsp_count),
static_cast<unsigned long long>(g_timeout_count),
static_cast<unsigned long long>(g_resub_triggers),
static_cast<unsigned long long>(g_malformed_drops),
static_cast<unsigned long long>(g_offscope_drops),
g_abi_live_mask.load(std::memory_order_acquire),
static_cast<unsigned long long>(g_timer_ticks.load(std::memory_order_relaxed)),
g_timer_started.load(std::memory_order_acquire) ? 1 : 0);
tap_log(smsg);
}
}
}
using RawSendCommandOpaqueFn = unsigned long (*)(
CSChannelType ch, const CSProtoData& req, const CSRequestExt* ext, void* cb_abi_ptr, QObject* owner);
using OnPushKlineFn = void (*)(unsigned long, std::optional<CSBrokerId>, NN_SubscribeBit, const std::string&);
using OnRecvPushFn = void (*)(unsigned long, CSProtoError, const CSProtoData&, const CSResponseExt*);
using ParseFromArrayFn = bool (*)(void*, const void*, int);
using ParseFromStrFn = bool (*)(void*, const std::string&);
std::atomic<RawSendCommandOpaqueFn> g_real_SendCommand{nullptr};
std::atomic<OnPushKlineFn> g_real_OnPushKline{nullptr};
std::atomic<OnRecvPushFn> g_real_OnRecvPush{nullptr};
std::atomic<ParseFromArrayFn> g_real_ParseFromArray{nullptr};
std::atomic<ParseFromStrFn> g_real_ParseFromStr{nullptr};
std::atomic<const void*> g_ztv_quotepush_vptr{nullptr};
// ---------------------------------------------------------------------------
// Rev-10 fix #6: honest dynamic ABI discovery.
// Symbols are only accepted from images that are NOT our own DSO (dlpi_addr is
// compared against our own dli_fbase), so a vtable/symbol that merely collides
// with our stub can never be mistaken for the real libQotBase / libCoreBiz one.
// abi_live_mask starts at 0 and only ever sets bits for things actually resolved.
// bit0 QuotePush vptr | bit1 ParseFromArray | bit2 ParseFromString
// bit3 SendCommand | bit4 OnPushKline
// ---------------------------------------------------------------------------
struct ImageScanQuery {
const char* sym;
const char* name_needle;
const void* self_base;
void* addr;
int images_seen;
int images_matched;
};
int scan_foreign_images_cb(struct dl_phdr_info* info, size_t, void* data) {
auto* q = static_cast<ImageScanQuery*>(data);
if (info == nullptr || info->dlpi_name == nullptr || info->dlpi_name[0] == '\0') return 0;
if (q->self_base != nullptr && reinterpret_cast<const void*>(info->dlpi_addr) == q->self_base) return 0;
++q->images_seen;
if (q->name_needle != nullptr && std::strstr(info->dlpi_name, q->name_needle) == nullptr) return 0;
++q->images_matched;
if (void* h = dlopen(info->dlpi_name, RTLD_LAZY | RTLD_NOLOAD)) {
void* p = dlsym(h, q->sym);
if (p != nullptr && p != q->self_base) { q->addr = p; dlclose(h); return 1; }
dlclose(h);
}
return 0;
}
void* resolve_foreign_symbol(const char* sym, const char* name_needle, const char* soname, void* self_fn) {
Dl_info self{};
const void* self_base = nullptr;
if (dladdr(reinterpret_cast<void*>(&resolve_foreign_symbol), &self) != 0 && self.dli_fbase != nullptr) {
self_base = self.dli_fbase;
}
ImageScanQuery q{sym, name_needle, self_base, nullptr, 0, 0};
dl_iterate_phdr(&scan_foreign_images_cb, &q);
if (q.addr != nullptr && q.addr != self_fn) return q.addr;
if (soname != nullptr && *soname != '\0') {
if (void* h = dlopen(soname, RTLD_LAZY | RTLD_NOLOAD)) {
void* p = dlsym(h, sym);
dlclose(h);
if (p != nullptr && p != self_fn) return p;
}
}
return nullptr;
}
const void* resolve_quotepush_vptr() {
const void* cur = g_ztv_quotepush_vptr.load(std::memory_order_acquire);
if (cur != nullptr) return cur;
const char* sym = "_ZTVN18FTCmdStockQuoteSub9QuotePushE";
void* ztv = resolve_foreign_symbol(sym, "Qot", "libQotBase.so", nullptr);
if (ztv == nullptr) return nullptr;
// vtable layout: [offset-to-top][typeinfo][first virtual method ...]
const void* vptr = static_cast<const char*>(ztv) + (2 * sizeof(void*));
const void* first_slot = *reinterpret_cast<const void* const*>(vptr);
if (first_slot == nullptr) return nullptr; // table not relocated yet -> stay honest
g_ztv_quotepush_vptr.store(vptr, std::memory_order_release);
abi_mask_set(1u);
return vptr;
}
void* resolve_dso_symbol_safe(const char* sym, const char* soname, void* self_fn) {
if (soname && *soname) {
if (void* h = dlopen(soname, RTLD_LAZY | RTLD_NOLOAD)) {
void* p = dlsym(h, sym);
dlclose(h);
if (p && p != self_fn) return p;
}
}
if (void* p = dlsym(RTLD_NEXT, sym)) {
if (p != self_fn) return p;
}
return nullptr;
}
template <typename Fn, typename Resolver>
Fn resolve_cached_symbol(std::atomic<Fn>& slot, Resolver&& resolver) {
Fn current = slot.load(std::memory_order_acquire);
if (current != nullptr) return current;
Fn candidate = resolver();
if (candidate == nullptr) return nullptr; // retry on a later hook if the image is not loaded yet
Fn expected = nullptr;
if (slot.compare_exchange_strong(expected, candidate,
std::memory_order_release,
std::memory_order_acquire)) return candidate;
return expected;
}
bool parse_strict_allowlist(const char* txt, std::vector<uint64_t>& out_sids, const char*& err_reason) {
out_sids.clear();
const char* p = txt;
while (*p) {
while (*p == ',' || *p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') ++p;
if (!*p) break;
if (*p == '#') { while (*p && *p != '\n') ++p; continue; }
if (*p < '0' || *p > '9') { err_reason = "invalid_sid_token"; return false; }
uint64_t v = 0;
while (*p >= '0' && *p <= '9') {
const uint64_t digit = static_cast<uint64_t>(*p - '0');
if (v > (UINT64_MAX - digit) / 10u) { err_reason = "sid_overflow"; return false; }
v = v * 10u + digit;
++p;
}
if (v == 0 || (*p != '\0' && *p != ',' && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n' && *p != '#')) {
err_reason = "invalid_sid_token"; return false;
}
if (out_sids.size() >= kMaxTargets) { err_reason = "exceeds_max_targets"; return false; }
for (uint64_t previous : out_sids) {
if (previous == v) { err_reason = "duplicate_sid"; return false; }
}
out_sids.push_back(v);
}
if (out_sids.empty()) { err_reason = "empty_allowlist"; return false; }
return true;
}
constexpr size_t kMaxConfigBytes = 32768;
bool read_bounded_fd(int fd, std::string& out, const char*& reason, const char* too_large_reason) {
out.clear();
char chunk[4096];
while (true) {
const ssize_t n = ::read(fd, chunk, sizeof(chunk));
if (n < 0) {
if (errno == EINTR) continue;
reason = "conf_read_failed";
return false;
}
if (n == 0) return true;
const size_t count = static_cast<size_t>(n);
if (count > kMaxConfigBytes - out.size()) { reason = too_large_reason; return false; }
out.append(chunk, count);
}
}
bool parse_u64_decimal(const std::string& text, uint64_t& value) {
if (text.empty()) return false;
uint64_t parsed = 0;
for (char ch : text) {
if (ch < '0' || ch > '9') return false;
const uint64_t digit = static_cast<uint64_t>(ch - '0');
if (parsed > (UINT64_MAX - digit) / 10u) return false;
parsed = parsed * 10u + digit;
}
value = parsed;
return true;
}
bool parse_bool01(const std::string& text, bool& value) {
if (text == "0") { value = false; return true; }
if (text == "1") { value = true; return true; }
return false;
}
std::string trim_ascii(const std::string& text) {
const size_t first = text.find_first_not_of(" \t\v\f");
if (first == std::string::npos) return std::string();
const size_t last = text.find_last_not_of(" \t\v\f");
return text.substr(first, last - first + 1);
}
bool read_sid_file(const std::string& path, std::vector<uint64_t>& out_sids, const char*& reason) {
if (path.empty()) { reason = "sec_ids_file_empty_path"; return false; }
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) { reason = "sec_ids_file_open_failed"; return false; }
std::string contents;
const bool read_ok = read_bounded_fd(fd, contents, reason, "sec_ids_file_too_large");
const int saved_errno = errno;
::close(fd);
errno = saved_errno;
if (!read_ok) return false;
if (contents.empty()) { reason = "sec_ids_file_empty"; return false; }
const char* parse_reason = "invalid_sid_token";
if (!parse_strict_allowlist(contents.c_str(), out_sids, parse_reason)) { reason = parse_reason; return false; }
return true;
}
void rebuild_mkt_slots_locked() {
g_mkt_count = 0;
for (size_t i = 0; i < g_target_count; ++i) {
uint32_t m = g_targets[i].mkt;
bool exists = false;
for (size_t j = 0; j < g_mkt_count; ++j) {
if (g_mkt_subs[j].mkt == m) { exists = true; break; }
}
if (!exists && g_mkt_count < kMaxMkts) {
g_mkt_subs[g_mkt_count++] = MktSubSlot{m, 0, false, false, false, false};
}
}
}
void schedule_resub_all_mkts_locked(const char* trigger) {
if (!g_config_valid || g_mkt_count == 0) return;
++g_resub_triggers;
for (size_t j = 0; j < g_mkt_count; ++j) {
if (g_mkt_subs[j].inflight) {
g_mkt_subs[j].needs_resub = true;
} else {
g_mkt_subs[j].ack_ok = false;
g_mkt_subs[j].failed = false;
g_mkt_subs[j].tries = 0;
}
}
for (size_t i = 0; i < g_target_count; ++i) g_targets[i].sub_ack_ok = false;
char msg[224];
std::snprintf(msg, sizeof(msg),
"{\"ev\":\"resub_scheduled\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"trigger\":\"%s\",\"mkts\":%zu}",
static_cast<long long>(now_epoch_ms()), static_cast<long long>(now_mono_ms()), trigger, g_mkt_count);
tap_log(msg);
}
// ---------------------------------------------------------------------------
// Rev-10 fix #4: hard disarm. Caller holds driver and state locks.
// Every path that ends up "not armed" (missing file, 0-byte file, read error,
// rejected config) funnels through here so stale armed state, the target table
// and the inflated retry ring can never survive a broken config.
// ---------------------------------------------------------------------------
void disarm_to_passive_locked(const char* reason, const char* conf, uint64_t fnv64, const char* detail) {
const size_t prev_targets = g_target_count;
const size_t prev_mkts = g_mkt_count;
size_t prev_inflight = 0;
for (size_t r = 0; r < kReqRingCap; ++r) if (g_req_ring[r].active) ++prev_inflight;
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_req_ring_pos = 0;
g_target_count = 0;
g_mkt_count = 0;
g_config_valid = false;
g_loaded_conf_hash = 0;
apply_probe_settings_locked(ProbeConfig{});
g_mode.store(MODE_PASSIVE_ONLY, std::memory_order_release);
char dj[512];
std::snprintf(dj, sizeof(dj),
"{\"ev\":\"disarmed_to_passive\",\"wall_ms\":%lld,\"mono_ms\":%lld,\"conf\":\"%s\","
"\"fnv64\":\"%016llx\",\"reason\":\"%s\",\"detail\":\"%s\",\"dropped_targets\":%zu,"
"\"dropped_mkts\":%zu,\"inflight_cleared\":%zu}",
static_cast<long long>(now_epoch_ms()), static_cast<long long>(now_mono_ms()),
conf != nullptr ? conf : "", static_cast<unsigned long long>(fnv64),
reason != nullptr ? reason : "", detail != nullptr ? detail : "",
prev_targets, prev_mkts, prev_inflight);
tap_log(dj);
}
void load_fex_safe_config_file() {
std::lock_guard<std::recursive_mutex> step_lk(g_send_step_mu);
const char* env_cfg = std::getenv("BTC_PROBE_CONF");
const std::string cfg_path = (env_cfg && *env_cfg) ? env_cfg : "/tmp/btc_probe.conf";
auto disarm = [&](const char* reason, const char* detail, uint64_t cfg_hash) {
std::lock_guard<std::mutex> state_lk(g_state_mu);
disarm_to_passive_locked(reason, cfg_path.c_str(), cfg_hash, detail);
char msg[384];
std::snprintf(msg, sizeof(msg),
"{\"ev\":\"config_fail_closed_rejected\",\"reason\":\"%s\",\"fnv64\":\"%016llx\"}",
reason != nullptr ? reason : "config_rejected", static_cast<unsigned long long>(cfg_hash));
tap_log(msg);
};
const int fd = ::open(cfg_path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) { disarm("conf_open_failed", "open failed", 0); return; }
std::string raw;
const char* read_reason = "conf_read_failed";
const bool read_ok = read_bounded_fd(fd, raw, read_reason, "conf_too_large");
const int saved_errno = errno;
::close(fd);
errno = saved_errno;
if (!read_ok) { disarm(read_reason, "bounded config read failed", 0); return; }
if (raw.empty()) { disarm("conf_empty_zero_bytes", "config contains zero bytes", 0); return; }
if (raw.find('\0') != std::string::npos) {
const uint64_t hash = fnv1a_64(raw.data(), raw.size());
disarm("conf_embedded_nul", "binary NUL in config", hash); return;
}
const uint64_t cfg_hash = fnv1a_64(raw.data(), raw.size());
ProbeConfig staged;
bool mode_seen = false, sec_spec_seen = false, valid = true;
std::vector<std::string> seen_keys;
const char* reject_reason = "config_rejected";
auto mark_key = [&](const std::string& key) {
for (const std::string& seen : seen_keys) if (seen == key) return false;
seen_keys.push_back(key); return true;
};
auto parse_range = [&](const std::string& value, uint64_t minv, uint64_t maxv, uint64_t& out) {
return parse_u64_decimal(value, out) && out >= minv && out <= maxv;
};
size_t pos = 0;
while (pos <= raw.size() && valid) {
size_t endline = raw.find_first_of("\r\n", pos);
if (endline == std::string::npos) endline = raw.size();
std::string line = trim_ascii(raw.substr(pos, endline - pos));
pos = endline + 1;
if (line.empty() || line[0] == '#') continue;
const size_t eq = line.find('=');
if (eq == std::string::npos) { reject_reason = "line_missing_equals"; valid = false; break; }
const std::string key = trim_ascii(line.substr(0, eq));
const std::string value = trim_ascii(line.substr(eq + 1));
if (key.empty()) { reject_reason = "empty_key"; valid = false; break; }
if (!mark_key(key)) { reject_reason = "duplicate_key"; valid = false; break; }
if (key == "log") {
if (value.empty() || value.size() >= sizeof(g_log_path)) { reject_reason = "invalid_log_path"; valid = false; }
else staged.log_path = value;
} else if (key == "mode") {
mode_seen = true;
if (value == "passive") staged.mode = MODE_PASSIVE_ONLY;
else if (value == "2b_raw") staged.mode = MODE_2B_RAW_0x1843;
else { reject_reason = "unknown_mode"; valid = false; }
} else if (key == "delay_sec") {
uint64_t n = 0;
if (!parse_range(value, 0, 600, n)) { reject_reason = "invalid_delay_sec"; valid = false; }
else staged.min_wait_ms = static_cast<int64_t>(n) * 1000;
} else if (key == "sec_id" || key == "sec_ids" || key == "sec_ids_file") {
if (sec_spec_seen) { reject_reason = "duplicate_sec_spec"; valid = false; break; }
sec_spec_seen = true;
const char* sid_reason = "invalid_sid_token";
if (key == "sec_ids_file") valid = read_sid_file(value, staged.sids, sid_reason);
else valid = parse_strict_allowlist(value.c_str(), staged.sids, sid_reason);
if (!valid) reject_reason = sid_reason;
} else if (key == "pull_0x1811" || key == "sub_tick" || key == "sub_orderbook" ||
key == "sub_bbo" || key == "sub_deal_stat" || key == "sub_kline") {
bool b = false;
if (!parse_bool01(value, b)) { reject_reason = "invalid_boolean"; valid = false; }
else if (key == "pull_0x1811") staged.send_pull_0x1811 = b;
else if (key == "sub_tick") staged.sub_tick_35 = b;
else if (key == "sub_orderbook") staged.sub_orderbook_3 = b;
else if (key == "sub_bbo") staged.sub_bbo_4 = b;
else if (key == "sub_deal_stat") staged.sub_dealstat_5 = b;
else staged.sub_kline_10001 = b;
} else if (key == "pull_count") {
uint64_t n = 0;
if (!parse_range(value, 1, 1000, n)) { reject_reason = "invalid_pull_count"; valid = false; }
else staged.pull_count = static_cast<uint32_t>(n);
} else if (key == "pull_exright" || key == "sub_exright") {
uint64_t n = 0;
if (!parse_range(value, 0, UINT32_MAX, n)) { reject_reason = "invalid_exright"; valid = false; }
else if (key == "pull_exright") staged.pull_exright = static_cast<uint32_t>(n);
else staged.sub_exright = static_cast<uint32_t>(n);
} else if (key == "sub_batch") {
uint64_t n = 0;
if (!parse_range(value, 1, 200, n)) { reject_reason = "invalid_sub_batch"; valid = false; }
else staged.sub_batch = static_cast<size_t>(n);
} else if (key == "pull_step") {
uint64_t n = 0;
if (!parse_range(value, 1, 50, n)) { reject_reason = "invalid_pull_step"; valid = false; }
else staged.pull_step = static_cast<size_t>(n);
} else if (key == "status_sec") {
uint64_t n = 0;
if (!parse_range(value, 1, 600, n)) { reject_reason = "invalid_status_sec"; valid = false; }
else staged.status_period_ms = static_cast<int64_t>(n) * 1000;
} else if (key == "orderbook_prob") {
uint64_t n = 0;
if (!parse_range(value, 0, 100, n)) { reject_reason = "invalid_orderbook_prob"; valid = false; }
else staged.orderbook_prob = static_cast<uint32_t>(n);
} else { reject_reason = "unknown_key"; valid = false; }
}
if (!valid) { disarm(reject_reason, "no staged config field was committed", cfg_hash); return; }
if (!mode_seen) { disarm("missing_mode", "mode key is required", cfg_hash); return; }
if (staged.mode == MODE_PASSIVE_ONLY) {
std::lock_guard<std::mutex> state_lk(g_state_mu);
disarm_to_passive_locked("mode_passive", cfg_path.c_str(), cfg_hash, "mode=passive requested");
return;
}
if (!sec_spec_seen || staged.sids.empty()) {
disarm("missing_sec_ids", "2b_raw requires a non-empty allowlist", cfg_hash); return;
}
void* h_qot = dlopen("libQotBase.so", RTLD_LAZY | RTLD_NOLOAD);
using GetCSMktTypeFn = NN_CSMktType (*)(unsigned long);
auto fn_get_mkt = h_qot ? reinterpret_cast<GetCSMktTypeFn>(dlsym(h_qot, "_ZN10IStockUtil12GetCSMktTypeEm")) : nullptr;
std::vector<TargetSlot> targets;
targets.reserve(staged.sids.size());
uint64_t unmapped_sid = 0;
for (uint64_t sid : staged.sids) {
uint32_t m = fn_get_mkt ? static_cast<uint32_t>(fn_get_mkt(sid)) : 0u;
if (m == 0u) m = fallback_csmkt_for_sid(sid);
if (m == 0u) { unmapped_sid = sid; break; }
TargetSlot target{}; target.sid = sid; target.mkt = m; targets.push_back(target);
}
if (h_qot) dlclose(h_qot);
if (unmapped_sid != 0) { disarm("unmapped_mkt", "market type resolution failed", cfg_hash); return; }
{
std::lock_guard<std::mutex> state_lk(g_state_mu);
if (g_config_valid && g_loaded_conf_hash == cfg_hash) return;
apply_probe_settings_locked(staged);
g_target_count = targets.size();
for (size_t i = 0; i < targets.size(); ++i) g_targets[i] = targets[i];
for (size_t i = targets.size(); i < kMaxTargets; ++i) g_targets[i] = TargetSlot{};
rebuild_mkt_slots_locked();
g_loaded_conf_hash = cfg_hash;
g_config_valid = true;
g_mode.store(staged.mode, std::memory_order_release);
}
char okm[512];
std::snprintf(okm, sizeof(okm),
"{\"ev\":\"config_armed\",\"fnv64\":\"%016llx\",\"mode\":%d,\"targets\":%zu,"
"\"bits\":\"0,1%s%s%s%s%s\",\"pull_count\":%u,\"pull_exright\":%u,\"pull_0x1811\":%d}",
static_cast<unsigned long long>(cfg_hash), staged.mode, targets.size(),
staged.sub_orderbook_3 ? ",3" : "", staged.sub_bbo_4 ? ",4" : "", staged.sub_dealstat_5 ? ",5" : "",
staged.sub_tick_35 ? ",35" : "", staged.sub_kline_10001 ? ",10001" : "",
staged.pull_count, staged.pull_exright, staged.send_pull_0x1811 ? 1 : 0);
tap_log(okm);
}
__attribute__((noinline))
void run_multi_sub_and_paced_pull_step(RawSendCommandOpaqueFn real_opaque) {
if (!real_opaque) return;
void* h_qot = dlopen("libQotBase.so", RTLD_LAZY | RTLD_NOLOAD);
using GetEffBrokerFn = std::optional<CSBrokerId> (*)(unsigned long, std::optional<CSBrokerId>);
auto fn_eff_broker = h_qot ? reinterpret_cast<GetEffBrokerFn>(
dlsym(h_qot, "_ZN5quote13crypto_broker28GetEffectiveCryptoCSBrokerIDEmSt8optionalI10CSBrokerIdE")) : nullptr;
// A88 live ACK fix: FTChannelProxy requires a live QObject owner whenever a
// response callback is supplied. Rev-10 passed nullptr, which hits the
// CoreBiz owner assertion and leaves pushes working but reply/sub_ok at 0.
// INNProtoCenter::ms_pOwner is the process-lifetime quote QObject created by
// INNProtoCenter::InitAll; use its exported address without constructing or
// mutating any FTNN object.
QObject* qot_owner = nullptr;
if (h_qot) {
void* owner_symbol = dlsym(h_qot, "_ZN14INNProtoCenter9ms_pOwnerE");
if (owner_symbol) qot_owner = *reinterpret_cast<QObject**>(owner_symbol);
}
ProbeSendGuard probe_context;
int64_t now_m = now_mono_ms();
if (now_m - g_last_sub_ms.load(std::memory_order_relaxed) >= g_sub_gap_ms) {
std::vector<size_t> pending_mkts;
{
std::lock_guard<std::mutex> lk(g_state_mu);
if (g_config_valid) {
for (size_t mi = 0; mi < g_mkt_count; ++mi) {
MktSubSlot& ms = g_mkt_subs[mi];
if (!ms.ack_ok && !ms.failed && !ms.inflight) {
ms.inflight = true;
++ms.tries;
pending_mkts.push_back(mi);
}
}
}
}
if (!pending_mkts.empty()) {
g_last_sub_ms.store(now_m, std::memory_order_relaxed);
for (size_t mi : pending_mkts) {
uint32_t mkt_u = 0; uint8_t tries = 1;
std::vector<uint64_t> mkt_sids;
{
std::lock_guard<std::mutex> lk(g_state_mu);
mkt_u = g_mkt_subs[mi].mkt;
tries = g_mkt_subs[mi].tries;
for (size_t ti = 0; ti < g_target_count; ++ti) {
if (g_targets[ti].mkt == mkt_u) mkt_sids.push_back(g_targets[ti].sid);
}
}
bool is_24h = is_24h_csmkt(mkt_u);
std::vector<std::string> batch;
batch.reserve(g_sub_batch);
auto flush_batch = [&]() {
if (batch.empty()) return;
CSProtoData sub_data;
sub_data.cmd_id = 0x1843;
sub_data.payload = encode_batch_subscribe_set_req(batch);
CSRequestExt ext;
ext.timeout_ms = 10000;
const char hdr[2] = {static_cast<char>(mkt_u & 0xFFu), static_cast<char>((mkt_u >> 8) & 0xFFu)};
ext.ext_head.assign(hdr, 2);
uint64_t pre_seq = 0; ext.opt_seq_ptr = &pre_seq;
size_t cidx = reserve_req_ctx(0x1843, mkt_u, g_sub_exright, mi, 0, tries);
SendCmdCallbackStdFn rsp_cb(&on_0x1843_rsp_cb);
unsigned long sub_seq = real_opaque(CS_CHANNEL_QUOTE, sub_data, &ext, &rsp_cb, qot_owner);
bind_or_cancel_req_ctx(cidx, sub_seq);
if (sub_seq == 0) {
std::lock_guard<std::mutex> lk(g_state_mu);
mark_sub_retry_or_fail_locked(mi, "send_returned_zero", 0);
} else {
char line[288];
std::snprintf(line, sizeof(line),
"{\"ev\":\"sent_batch_0x1843\",\"seq\":%llu,\"mkt\":%u,\"count\":%zu,\"bytes\":%zu,\"attempt\":%u}",
static_cast<unsigned long long>(sub_seq), mkt_u, batch.size(), sub_data.payload.size(),
static_cast<unsigned>(tries));
tap_log(line);
}
batch.clear();
};
for (uint64_t sid : mkt_sids) {
std::optional<CSBrokerId> broker_opt = std::nullopt;
if (mkt_u == 17u && fn_eff_broker) broker_opt = fn_eff_broker(sid, std::nullopt);
batch.push_back(encode_single_security_sub(sid, g_sub_tick_35, g_sub_kline_10001, is_24h, broker_opt));
if (batch.size() >= g_sub_batch) flush_batch();
}
flush_batch();
}
}
}
if (g_send_pull_0x1811 && now_m - g_last_pull_ms.load(std::memory_order_relaxed) >= g_pull_gap_ms) {
std::vector<size_t> pick;
{
std::lock_guard<std::mutex> lk(g_state_mu);
if (g_config_valid) {
for (size_t i = 0; i < g_target_count && pick.size() < g_pull_step; ++i) {
TargetSlot& t = g_targets[i];
if (!t.pull_ok && !t.pull_failed && !t.pull_inflight) {
t.pull_inflight = true;
++t.pull_tries;
pick.push_back(i);
}
}
}
}
if (!pick.empty()) {
g_last_pull_ms.store(now_m, std::memory_order_relaxed);
for (size_t tidx : pick) {
uint64_t sid = 0; uint32_t mkt_u = 0; uint8_t tries = 1;
{
std::lock_guard<std::mutex> lk(g_state_mu);
sid = g_targets[tidx].sid; mkt_u = g_targets[tidx].mkt; tries = g_targets[tidx].pull_tries;
}
std::optional<CSBrokerId> broker_opt = std::nullopt;
if (mkt_u == 17u && fn_eff_broker) broker_opt = fn_eff_broker(sid, std::nullopt);
CSProtoData req_data;
req_data.cmd_id = 0x1811;
req_data.payload = encode_1m_kline_pull_req(sid, g_pull_count, g_pull_exright, broker_opt);
CSRequestExt pull_ext;
pull_ext.timeout_ms = 10000;
const char phdr[2] = {static_cast<char>(mkt_u & 0xFFu), static_cast<char>((mkt_u >> 8) & 0xFFu)};
pull_ext.ext_head.assign(phdr, 2);
uint64_t opt_seq = 0; pull_ext.opt_seq_ptr = &opt_seq;
size_t cidx = reserve_req_ctx(0x1811, mkt_u, g_pull_exright, tidx, sid, tries);
SendCmdCallbackStdFn pull_cb(&on_0x1811_rsp_cb);
unsigned long seq_no = real_opaque(CS_CHANNEL_QUOTE, req_data, &pull_ext, &pull_cb, qot_owner);
bind_or_cancel_req_ctx(cidx, seq_no);
if (seq_no == 0) {
std::lock_guard<std::mutex> lk(g_state_mu);
mark_pull_retry_or_fail_locked(tidx, "send_returned_zero", 0);
} else {
char msg[288];
std::snprintf(msg, sizeof(msg),
"{\"ev\":\"sent_pull_0x1811\",\"seq\":%llu,\"sec_id\":%llu,\"mkt\":%u,\"count\":%u,\"attempt\":%u}",
static_cast<unsigned long long>(seq_no), static_cast<unsigned long long>(sid),
mkt_u, g_pull_count, static_cast<unsigned>(tries));
tap_log(msg);
}
}
}
}
if (h_qot) dlclose(h_qot);
}
// ---------------------------------------------------------------------------
// Rev-10 fix #5: independent 250 ms driver.
// Timeout sweeps, sustained_status emission, hot config reload and paced
// sub/pull steps no longer depend on some later SendCommand / push arriving.
// The timer and SendCommand hook share the recursive driver lock. The hook takes
// it before calling the real function; thread-local recursion guards forward
// nested hook calls without double-driving the state machine.
// ---------------------------------------------------------------------------
std::mutex g_timer_mu;
std::condition_variable g_timer_cv;
std::mutex g_timer_lifecycle_mu;
std::thread g_timer_thread;
std::atomic<bool> g_timer_stop{false};
std::atomic<uint64_t> g_timer_errors{0};
constexpr int64_t kTimerPeriodMs = 250;
constexpr int64_t kConfPollMs = 5000;
void timer_tick_body() {
std::lock_guard<std::recursive_mutex> step_lk(g_send_step_mu);
if (g_is_cef_child) return;
const int64_t now_m = now_mono_ms();
sweep_timeouts_and_emit_sustained_status();
const int64_t last_poll = g_last_conf_poll_ms.load(std::memory_order_relaxed);
if (now_m - last_poll >= kConfPollMs) {
g_last_conf_poll_ms.store(now_m, std::memory_order_relaxed);
load_fex_safe_config_file(); // hot reload; empty/failed -> disarm
}
const RawSendCommandOpaqueFn real = g_real_SendCommand.load(std::memory_order_acquire);
if (g_mode.load(std::memory_order_acquire) == MODE_2B_RAW_0x1843 && real != nullptr &&
(now_m - g_boot_mono_ms) >= g_min_wait_ms &&
!g_in_probe_send.load(std::memory_order_acquire)) run_multi_sub_and_paced_pull_step(real);
g_timer_ticks.fetch_add(1, std::memory_order_relaxed);
}
void timer_thread_main() {
std::unique_lock<std::mutex> lk(g_timer_mu);
while (!g_timer_stop.load(std::memory_order_acquire)) {
g_timer_cv.wait_for(lk, std::chrono::milliseconds(kTimerPeriodMs), [] {
return g_timer_stop.load(std::memory_order_acquire);
});
if (g_timer_stop.load(std::memory_order_acquire)) break;
lk.unlock();
try { timer_tick_body(); }
catch (...) { g_timer_errors.fetch_add(1, std::memory_order_relaxed); }
lk.lock();
}
g_timer_started.store(false, std::memory_order_release);
}
void ensure_timer_thread_started() {
std::lock_guard<std::mutex> lifecycle_lk(g_timer_lifecycle_mu);
if (g_timer_thread.joinable()) {
if (g_timer_started.load(std::memory_order_acquire)) return;
if (g_timer_thread.get_id() == std::this_thread::get_id()) return;
g_timer_thread.join();
}
g_timer_stop.store(false, std::memory_order_release);
try {
g_timer_thread = std::thread(&timer_thread_main);
g_timer_started.store(true, std::memory_order_release);
char tm[192];
std::snprintf(tm, sizeof(tm),
"{\"ev\":\"timer_thread_started\",\"period_ms\":%lld,\"conf_poll_ms\":%lld}",
static_cast<long long>(kTimerPeriodMs), static_cast<long long>(kConfPollMs));
tap_log(tm);
} catch (...) {
g_timer_started.store(false, std::memory_order_release);
g_timer_errors.fetch_add(1, std::memory_order_relaxed);
}
}
void stop_timer_thread() {
std::unique_lock<std::mutex> lifecycle_lk(g_timer_lifecycle_mu);
g_timer_stop.store(true, std::memory_order_release);
g_timer_cv.notify_all();
if (g_timer_thread.joinable()) {
if (g_timer_thread.get_id() == std::this_thread::get_id()) return;
g_timer_thread.join();
}
g_timer_started.store(false, std::memory_order_release);
}
#ifndef A36_R10_UNIT_TEST
void shutdown_probe_r10() {
stop_timer_thread();
char dm[192];
std::snprintf(dm, sizeof(dm),
"{\"ev\":\"probe_unloaded\",\"ver\":\"r10-a36-66473\",\"timer_ticks\":%llu,\"timer_errors\":%llu}",
static_cast<unsigned long long>(g_timer_ticks.load(std::memory_order_relaxed)),
static_cast<unsigned long long>(g_timer_errors.load(std::memory_order_relaxed)));
tap_log(dm);
}
#endif
bool detect_cef_child_process() {
int fd = ::open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
char buf[4096]; ssize_t n = ::read(fd, buf, sizeof(buf) - 1); ::close(fd);
if (n <= 0) return false;
buf[n] = '\0';
ssize_t i = 0; int arg_idx = 0;
while (i < n) {
const char* arg = buf + i; size_t alen = std::strlen(arg);
if ((arg_idx > 0 && std::strncmp(arg, "--type=", 7) == 0) ||
std::strstr(arg, "WebRender") != nullptr || std::strstr(arg, "Crash") != nullptr) return true;
i += static_cast<ssize_t>(alen) + 1; ++arg_idx;
}
return false;
}
void strip_self_from_ld_preload_for_children() {
const char* keep = std::getenv("BTC_KEEP_CHILD_PRELOAD");
if (keep && std::strcmp(keep, "1") == 0) return;
const char* cur = std::getenv("LD_PRELOAD");
if (!cur || !*cur) return;
Dl_info info{};
if (!dladdr(reinterpret_cast<void*>(&strip_self_from_ld_preload_for_children), &info) || !info.dli_fname) return;
std::string self_base(info.dli_fname);
if (auto pos = self_base.find_last_of('/'); pos != std::string::npos) self_base = self_base.substr(pos + 1);
std::string preload(cur), kept;
size_t start = 0;
while (start < preload.size()) {
size_t sep = preload.find_first_of(": ", start);
std::string tok = preload.substr(start, sep == std::string::npos ? std::string::npos : sep - start);
if (!tok.empty() && tok.find(self_base) == std::string::npos) {
if (!kept.empty()) kept.push_back(':');
kept.append(tok);
}
if (sep == std::string::npos) break;
start = sep + 1;
}
if (kept.empty()) ::unsetenv("LD_PRELOAD");
else ::setenv("LD_PRELOAD", kept.c_str(), 1);
::unsetenv("FEX_ENV");
}
#ifndef A36_R10_UNIT_TEST
// A36_R10_UNIT_TEST only suppresses auto-start so the offline ASan harness can
// drive the state machine deterministically; shipped builds never define it.
void init_btc_1m_probe_r10() {
if (detect_cef_child_process()) { g_is_cef_child = true; return; }
strip_self_from_ld_preload_for_children();
g_boot_mono_ms = now_mono_ms();
g_last_conf_poll_ms.store(g_boot_mono_ms, std::memory_order_relaxed);
g_last_status_ms.store(g_boot_mono_ms, std::memory_order_relaxed);
load_fex_safe_config_file();
ensure_timer_thread_started(); // Rev-10 fix#5: driver runs without any SendCommand
char boot_msg[448];
std::snprintf(boot_msg, sizeof(boot_msg),
"{\"ev\":\"probe_loaded\",\"ver\":\"r10-a36-66473\",\"mode\":%d,\"targets\":%zu,"
"\"abi_mask\":%u,\"timer_period_ms\":%lld,"
"\"guards\":\"has_bytes+atomic_envelope+wire_lock+disarm+timer+foreign_abi\"}",
g_mode.load(), g_target_count,
g_abi_live_mask.load(std::memory_order_acquire),
static_cast<long long>(kTimerPeriodMs));
tap_log(boot_msg);
}
// Do not use GCC's constructor attribute here: it can run before this
// translation unit's C++ dynamic initializers and start a timer before the
// global std::thread/condition_variable members have been constructed.
// This lifecycle object is declared after those globals, so its constructor
// initializes the probe last and its destructor shuts it down first.
struct ProbeLifecycle {
ProbeLifecycle() { init_btc_1m_probe_r10(); }
~ProbeLifecycle() { shutdown_probe_r10(); }
};
ProbeLifecycle g_probe_lifecycle;
#endif // A36_R10_UNIT_TEST
} // namespace
extern "C" __attribute__((visibility("default")))
unsigned long _ZN15IFTChannelProxy11SendCommandE13CSChannelTypeRK11CSProtoDataPK12CSRequestExtSt8functionIFvm12CSProtoErrorS3_PK13CSResponseExtEEP7QObject(
CSChannelType ch, const CSProtoData& req, const CSRequestExt* ext, void* cb_abi_ptr, QObject* owner
) {
void* self_fn = reinterpret_cast<void*>(
&_ZN15IFTChannelProxy11SendCommandE13CSChannelTypeRK11CSProtoDataPK12CSRequestExtSt8functionIFvm12CSProtoErrorS3_PK13CSResponseExtEEP7QObject);
RawSendCommandOpaqueFn real = resolve_cached_symbol(g_real_SendCommand, [&]() {
return reinterpret_cast<RawSendCommandOpaqueFn>(resolve_dso_symbol_safe(
"_ZN15IFTChannelProxy11SendCommandE13CSChannelTypeRK11CSProtoDataPK12CSRequestExtSt8functionIFvm12CSProtoErrorS3_PK13CSResponseExtEEP7QObject",
"libCoreBiz.so", self_fn));
});
if (real != nullptr) abi_mask_set(8u);
if (g_is_cef_child) return real ? real(ch, req, ext, cb_abi_ptr, owner) : 0UL;
std::lock_guard<std::recursive_mutex> step_lk(g_send_step_mu);
const std::thread::id caller = std::this_thread::get_id();
if ((g_send_hook_depth != 0 && g_send_hook_owner == caller) ||
(g_in_probe_send.load(std::memory_order_acquire) && g_probe_send_owner == caller))
return real ? real(ch, req, ext, cb_abi_ptr, owner) : 0UL;
SendCommandGuard hook_context;
const unsigned long ret = real ? real(ch, req, ext, cb_abi_ptr, owner) : 0UL;
if (ch == CS_CHANNEL_QUOTE && req.cmd_id >= 0x1800 && req.cmd_id <= 0x18FF) {
{
std::lock_guard<std::mutex> lk(g_state_mu);
++g_qot_tx_count;
if (req.cmd_id == 0x1843 && g_mode.load(std::memory_order_relaxed) != MODE_PASSIVE_ONLY)
schedule_resub_all_mkts_locked("native_0x1843_tx");
}
const int64_t now_m = now_mono_ms();
if (now_m - g_last_conf_poll_ms.load(std::memory_order_relaxed) >= kConfPollMs) {
g_last_conf_poll_ms.store(now_m, std::memory_order_relaxed);
load_fex_safe_config_file();
}
sweep_timeouts_and_emit_sustained_status();
if (g_mode.load(std::memory_order_acquire) != MODE_PASSIVE_ONLY &&
(now_m - g_boot_mono_ms) >= g_min_wait_ms)
run_multi_sub_and_paced_pull_step(g_real_SendCommand.load(std::memory_order_acquire));
}
return ret;
}
extern "C" __attribute__((visibility("default")))
void _ZN14INNProtoCenter10OnRecvPushEm12CSProtoErrorRK11CSProtoDataPK13CSResponseExt(
unsigned long req_seq, CSProtoError err, const CSProtoData& data, const CSResponseExt* ext
) {
void* self_fn = reinterpret_cast<void*>(
&_ZN14INNProtoCenter10OnRecvPushEm12CSProtoErrorRK11CSProtoDataPK13CSResponseExt);
OnRecvPushFn real = resolve_cached_symbol(g_real_OnRecvPush, [&]() {
return reinterpret_cast<OnRecvPushFn>(resolve_dso_symbol_safe(
"_ZN14INNProtoCenter10OnRecvPushEm12CSProtoErrorRK11CSProtoDataPK13CSResponseExt",
"libQotBase.so", self_fn));
});
if (real != nullptr) abi_mask_set(32u);
RawPushDispatchGuard raw_scope;
if (!g_is_cef_child && data.cmd_id == 0x1844 &&
g_mode.load(std::memory_order_acquire) != MODE_PASSIVE_ONLY) {
std::lock_guard<std::recursive_mutex> step_lk(g_send_step_mu);
decode_quotepush_envelope_strict(
reinterpret_cast<const uint8_t*>(data.payload.data()), data.payload.size());
sweep_timeouts_and_emit_sustained_status();
}
if (real) real(req_seq, err, data, ext);
}
extern "C" __attribute__((visibility("default")))
void _ZN14INNProtoCenter11OnPushKlineEmSt8optionalI10CSBrokerIdE15NN_SubscribeBitRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE(
unsigned long sec_id, std::optional<CSBrokerId> broker_id, NN_SubscribeBit bit, const std::string& data
) {
void* self_fn = reinterpret_cast<void*>(
&_ZN14INNProtoCenter11OnPushKlineEmSt8optionalI10CSBrokerIdE15NN_SubscribeBitRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE);
OnPushKlineFn real = resolve_cached_symbol(g_real_OnPushKline, [&]() {
return reinterpret_cast<OnPushKlineFn>(resolve_dso_symbol_safe(
"_ZN14INNProtoCenter11OnPushKlineEmSt8optionalI10CSBrokerIdE15NN_SubscribeBitRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE",
"libQotBase.so", self_fn));
});
if (real != nullptr) abi_mask_set(16u);
if (!g_is_cef_child) {
std::lock_guard<std::recursive_mutex> step_lk(g_send_step_mu);
decode_0x1844_push_kline_strict(sec_id, static_cast<uint32_t>(bit), data);
sweep_timeouts_and_emit_sustained_status();
}
if (real) real(sec_id, broker_id, bit, data);
}
extern "C" __attribute__((visibility("default")))
bool _ZN6google8protobuf11MessageLite14ParseFromArrayEPKvi(void* msg_this, const void* data, int size) {
void* self_fn = reinterpret_cast<void*>(&_ZN6google8protobuf11MessageLite14ParseFromArrayEPKvi);
ParseFromArrayFn real = resolve_cached_symbol(g_real_ParseFromArray, [&]() {
return reinterpret_cast<ParseFromArrayFn>(resolve_dso_symbol_safe(
"_ZN6google8protobuf11MessageLite14ParseFromArrayEPKvi", nullptr, self_fn));
});
if (real != nullptr) abi_mask_set(2u);
PbParseGuard parse_scope;
const bool ok = real ? real(msg_this, data, size) : false;
if (false && ok && parse_scope.outermost && !g_in_raw_push_dispatch && !g_is_cef_child && msg_this && data && size > 0 && size <= (16 << 20) &&
g_mode.load(std::memory_order_acquire) != MODE_PASSIVE_ONLY) {
std::lock_guard<std::recursive_mutex> step_lk(g_send_step_mu);
const void* qp_vptr = resolve_quotepush_vptr();
const void* obj_vptr = *reinterpret_cast<const void* const*>(msg_this);
if (qp_vptr && obj_vptr == qp_vptr) {
decode_quotepush_envelope_strict(static_cast<const uint8_t*>(data), static_cast<size_t>(size));
sweep_timeouts_and_emit_sustained_status();
}
}
return ok;
}
extern "C" __attribute__((visibility("default")))
bool _ZN6google8protobuf11MessageLite15ParseFromStringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE(
void* msg_this, const std::string& data
) {
void* self_fn = reinterpret_cast<void*>(
&_ZN6google8protobuf11MessageLite15ParseFromStringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE);
ParseFromStrFn real = resolve_cached_symbol(g_real_ParseFromStr, [&]() {
return reinterpret_cast<ParseFromStrFn>(resolve_dso_symbol_safe(
"_ZN6google8protobuf11MessageLite15ParseFromStringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE",
nullptr, self_fn));
});
if (real != nullptr) abi_mask_set(4u);
PbParseGuard parse_scope;
const bool ok = real ? real(msg_this, data) : false;
if (false && ok && parse_scope.outermost && !g_in_raw_push_dispatch && !g_is_cef_child && msg_this && !data.empty() && data.size() <= (16u << 20) &&
g_mode.load(std::memory_order_acquire) != MODE_PASSIVE_ONLY) {
std::lock_guard<std::recursive_mutex> step_lk(g_send_step_mu);
const void* qp_vptr = resolve_quotepush_vptr();
const void* obj_vptr = *reinterpret_cast<const void* const*>(msg_this);
if (qp_vptr && obj_vptr == qp_vptr) {
decode_quotepush_envelope_strict(reinterpret_cast<const uint8_t*>(data.data()), data.size());
sweep_timeouts_and_emit_sustained_status();
}
}
return ok;
}