Verify radio mesh deduplication independently of arrival order

This commit is contained in:
evgeny committed 2026-10-26 15:08:08 +01:00
1 parent 54a7a6bc19
commit 444deeb366
1 file changed
+123 -44
+123 -44
View File
@@ -7,12 +7,11 @@
//
// Сценарий:
// 1. A,B,D,C radio_on → флаг TOPO_FLAG_RADIO распространяется по BGP.
// 2. A: radio_talk_begin + N кадров + radio_talk_end.
// Кадр идёт к C двумя путями (A→B→C и A→D→C) — дубль гасится кэшем
// (src,stream,seq) в radio_recv.
// 3. Проверка: B, D, C получают ровно N кадров (без дублей), порядок seq
// и FIN корректны; у C счётчик дропнутых дублей > 0 (путь дедупликации
// реально отработал).
// 2. A: N кадров + FIN; B/D/C получают ровно N кадров по порядку и один FIN.
// Дедупликация (src,stream,seq) может сработать на B, D или C.
// 3. Unix: повторяем burst с удержанием прямого A→B, затем A→D до прихода
// обходной копии через C. Настоящие ETCP и radio_recv проверяют оба порядка.
// Сценарий завершается после обработки всех отправленных RADIO-пакетов.
#include "chat_core.h"
#include "chat_sync.h"
@@ -72,7 +71,8 @@ struct mesh_ctx {
int result; /* 0=running, 1=ok, 2=fail */
int ticks;
void* timer;
uint32_t stop_dup_c; /* Снимок исходного критерия до необязательного диагностического хвоста. */
int scenario; /* 0 = обычная доставка; Unix: 1/2 = обходная копия сначала на B/D. */
uint32_t dup_start[4]; /* Счётчики до burst: предыдущий сценарий не даёт ложный PASS. */
};
/* приёмник кадров (per-узел): проверка порядка seq и FIN */
@@ -100,9 +100,12 @@ static int mesh_node_index(uint64_t id) {
}
#ifdef UTUN_TEST_MESH_OBSERVE
/* Наблюдаем raw ETCP до дедупликации, не меняя данные/результат или владение entry. */
/* Наблюдение raw ETCP и отменяемое удержание прямой копии до обходной доставки. */
static etcp_recv_fn g_radio_recv;
static unsigned int g_wire_tx[4][4], g_wire_rx[4][4];
static struct { struct ETCP_CONN* conn; struct ll_entry* entry; } g_held[N_FRAMES + 1];
static unsigned int g_held_count;
static int g_hold_node = -1, g_released;
extern int __real_etcp_bind(struct UTUN_INSTANCE* inst, uint8_t id, etcp_recv_fn callback);
extern int __real_etcp_send(struct ETCP_CONN* conn, struct ll_entry* entry);
@@ -116,7 +119,7 @@ static void mesh_wire(const char* direction, struct ETCP_CONN* conn, struct ll_e
if (self >= 0 && peer >= 0) {
if (!strcmp(direction, "TX")) ++g_wire_tx[self][peer]; else ++g_wire_rx[self][peer];
}
DEBUG_INFO(DEBUG_CATEGORY_DEBUG,
DEBUG_TRACE(DEBUG_CATEGORY_DEBUG,
"mesh wire %s self=%s peer=%s group=%016llx src=%016llx stream=%u seq=%u fin=%d hops=%u",
direction, self < 0 ? "?" : g_names[self], peer < 0 ? "?" : g_names[peer],
(unsigned long long)group, (unsigned long long)src, stream, seq, !!(p[RADIO_OFF_FLAGS] & RADIO_FLAG_FIN),
@@ -124,8 +127,26 @@ static void mesh_wire(const char* direction, struct ETCP_CONN* conn, struct ll_e
}
static void mesh_radio_recv(struct ETCP_CONN* conn, struct ll_entry* entry) {
int self = mesh_node_index(conn->instance->node_id), peer = mesh_node_index(conn->peer_node_id);
mesh_wire("RX", conn, entry);
g_radio_recv(conn, entry);
if (self == g_hold_node && peer == IDX_C && g_rx[self].frames == N_FRAMES && g_rx[self].fin_seen && !g_released) {
if (g_held_count != N_FRAMES + 1) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh gate: incomplete held burst node=%s held=%u", g_names[self], g_held_count);
abort();
}
DEBUG_INFO(DEBUG_CATEGORY_DEBUG, "mesh gate: release A->%s after C->%s delivered %d frames and FIN; held=%u",
g_names[self], g_names[self], N_FRAMES, g_held_count);
g_released = 1;
for (unsigned int i = 0; i < g_held_count; ++i) {
if (__real_etcp_send(g_held[i].conn, g_held[i].entry) != 0) {
queue_dgram_free(g_held[i].entry); queue_entry_free(g_held[i].entry);
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh gate: real ETCP send failed node=%s frame=%u", g_names[self], i);
abort();
}
}
g_held_count = 0;
}
}
int __wrap_etcp_bind(struct UTUN_INSTANCE* inst, uint8_t id, etcp_recv_fn callback) {
@@ -141,13 +162,22 @@ int __wrap_etcp_bind(struct UTUN_INSTANCE* inst, uint8_t id, etcp_recv_fn callba
int __wrap_etcp_send(struct ETCP_CONN* conn, struct ll_entry* entry) {
mesh_wire("TX", conn, entry);
if (conn && entry && entry->len >= 1 + RADIO_HDR_SIZE && entry->dgram[0] == ETCP_ID_RADIO
&& conn->instance->node_id == g_sh.nid[IDX_A] && mesh_node_index(conn->peer_node_id) == g_hold_node && !g_released) {
if (g_held_count == N_FRAMES + 1) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh gate: held burst overflow node=%s", g_names[g_hold_node]); abort();
}
g_held[g_held_count].conn = conn; g_held[g_held_count++].entry = entry;
return 0; /* Владение принимает gate; передаёт реальному ETCP только после обходной доставки. */
}
return __real_etcp_send(conn, entry);
}
#endif
static void mesh_snapshot(struct mesh_ctx* t, const char* reason) {
uint64_t gid = strtoull(CH_ID, NULL, 10);
DEBUG_INFO(DEBUG_CATEGORY_DEBUG, "mesh snapshot reason=%s phase=%d tick=%d tb=%llu", reason, t->phase, t->ticks,
DEBUG_INFO(DEBUG_CATEGORY_DEBUG, "mesh snapshot reason=%s scenario=%d phase=%d tick=%d tb=%llu",
reason, t->scenario, t->phase, t->ticks,
(unsigned long long)get_time_tb());
for (int i = 0; i < 4; ++i) {
DEBUG_INFO(DEBUG_CATEGORY_DEBUG, "mesh node=%s id=%016llx frames=%d fin=%d seq_ok=%d next_seq=%u dup=%u",
@@ -161,12 +191,6 @@ static void mesh_snapshot(struct mesh_ctx* t, const char* reason) {
}
}
static void mesh_tail_stop(void* arg) {
struct mesh_ctx* t = arg;
mesh_snapshot(t, "after_diagnostic_tail");
uasync_stop(t->ua);
}
static int G_PASSED = 0, G_FAILED = 0, G_TOTAL = 0;
#define TEST(n) do { G_TOTAL++; printf(" %-58s", n); fflush(stdout); } while(0)
#define OK() do { G_PASSED++; printf("OK\n"); } while(0)
@@ -314,13 +338,23 @@ static int all_radio(struct mesh_ctx* t) {
static void rx_frame_cb(struct UTUN_INSTANCE* inst, uint64_t group_id,
uint64_t src, uint16_t stream, uint16_t seq,
uint8_t fin, const uint8_t* opus, int len, void* arg) {
(void)inst; (void)group_id; (void)src; (void)opus; (void)len;
(void)group_id; (void)opus; (void)len;
struct rx_evt* rx = (struct rx_evt*)arg;
if (src != g_sh.nid[IDX_A] || (rx->active && stream != rx->stream)) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh RX: wrong source/stream self=%016llx src=%016llx stream=%u expected=%u",
(unsigned long long)inst->node_id, (unsigned long long)src, stream, rx->stream);
rx->seq_ok = 0; return;
}
if (fin) {
if (rx->active && stream == rx->stream) rx->fin_seen = 1;
if (!rx->active || rx->fin_seen || rx->frames != N_FRAMES || seq != N_FRAMES) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh RX: invalid FIN self=%016llx stream=%u seq=%u frames=%d previous_fin=%d",
(unsigned long long)inst->node_id, stream, seq, rx->frames, rx->fin_seen);
rx->seq_ok = 0;
}
rx->fin_seen = 1;
return;
}
if (!rx->active || stream != rx->stream) {
if (!rx->active) {
rx->active = 1;
rx->stream = stream;
rx->expect_seq = 0;
@@ -328,7 +362,11 @@ static void rx_frame_cb(struct UTUN_INSTANCE* inst, uint64_t group_id,
rx->fin_seen = 0;
rx->seq_ok = 1;
}
if (seq != rx->expect_seq) rx->seq_ok = 0;
if (seq != rx->expect_seq || rx->fin_seen) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh RX: wrong data order self=%016llx seq=%u expected=%u fin=%d",
(unsigned long long)inst->node_id, seq, rx->expect_seq, rx->fin_seen);
rx->seq_ok = 0;
}
rx->expect_seq = (uint16_t)(seq + 1);
rx->frames++;
}
@@ -411,6 +449,37 @@ static void do_talk(struct UTUN_INSTANCE* A) {
/* ── master state-machine ── */
/* 1 = полная доставка и дедупликация; 0 = ждём сеть; -1 = проверяемое нарушение. */
static int mesh_burst_result(struct mesh_ctx* t) {
uint64_t gid = strtoull(CH_ID, NULL, 10);
uint32_t dup[4];
for (int i = 0; i < 4; ++i) {
dup[i] = radio_dup_dropped(t->inst[i], gid) - t->dup_start[i];
if ((g_rx[i].active && !g_rx[i].seq_ok) || g_rx[i].frames > N_FRAMES || (i == IDX_A && g_rx[i].active)) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh: invalid delivery scenario=%d node=%s frames=%d seq_ok=%d",
t->scenario, g_names[i], g_rx[i].frames, g_rx[i].seq_ok);
return -1;
}
}
for (int i = 1; i < 4; ++i)
if (g_rx[i].frames != N_FRAMES || !g_rx[i].fin_seen || !g_rx[i].seq_ok) return 0;
#ifdef UTUN_TEST_MESH_OBSERVE
if (g_held_count) return 0;
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j) if (g_wire_tx[i][j] != g_wire_rx[j][i]) return 0;
if (g_hold_node >= 0 && (!g_released || dup[g_hold_node] != N_FRAMES + 1 || dup[IDX_C]
|| g_wire_tx[g_hold_node][IDX_C] || g_wire_rx[IDX_C][g_hold_node])) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh: forced order failed hold=%s released=%d dupB=%u dupD=%u dupC=%u",
g_names[g_hold_node], g_released, dup[IDX_B], dup[IDX_D], dup[IDX_C]);
return -1;
}
#endif
if ((uint64_t)dup[IDX_B] + dup[IDX_D] + dup[IDX_C] < N_FRAMES + 1) return 0;
DEBUG_INFO(DEBUG_CATEGORY_DEBUG, "mesh scenario=%d PASS frames=5/5/5 FIN=1/1/1 dupB=%u dupD=%u dupC=%u",
t->scenario, dup[IDX_B], dup[IDX_D], dup[IDX_C]);
return 1;
}
static void mesh_tick(void* arg) {
struct mesh_ctx* t = arg;
t->timer = NULL;
@@ -449,32 +518,40 @@ static void mesh_tick(void* arg) {
break;
case P_TALK1:
memset(g_rx, 0, sizeof(g_rx));
for (int i = 0; i < 4; ++i) t->dup_start[i] = radio_dup_dropped(t->inst[i], gid);
#ifdef UTUN_TEST_MESH_OBSERVE
memset(g_wire_tx, 0, sizeof(g_wire_tx)); memset(g_wire_rx, 0, sizeof(g_wire_rx));
g_hold_node = t->scenario == 1 ? IDX_B : t->scenario == 2 ? IDX_D : -1;
g_released = 0;
#endif
do_talk(A);
t->phase = P_WAIT_RX1;
break;
case P_WAIT_RX1:
/* B и D получают по N кадров; C — ровно N (дубль по второму пути гасится кэшем) */
if (g_rx[IDX_B].frames == N_FRAMES && g_rx[IDX_B].fin_seen && g_rx[IDX_B].seq_ok
&& g_rx[IDX_D].frames == N_FRAMES && g_rx[IDX_D].fin_seen && g_rx[IDX_D].seq_ok
&& g_rx[IDX_C].frames == N_FRAMES && g_rx[IDX_C].fin_seen && g_rx[IDX_C].seq_ok)
t->phase = P_DONE;
{
int result = mesh_burst_result(t);
if (result < 0) { mesh_snapshot(t, "invalid_burst"); t->result = 2; uasync_stop(t->ua); return; }
if (result > 0) {
#ifdef UTUN_TEST_MESH_OBSERVE
t->phase = ++t->scenario < 3 ? P_TALK1 : P_DONE;
#else
t->phase = P_DONE;
#endif
}
}
break;
case P_DONE:
mesh_snapshot(t, "original_stop");
t->stop_dup_c = radio_dup_dropped(C, gid);
mesh_snapshot(t, "complete");
t->result = 1;
if (getenv("UTUN_TEST_MESH_TAIL")) {
DEBUG_INFO(DEBUG_CATEGORY_DEBUG, "mesh observe tail=500ms original_ok=1 original_dupC=%u", t->stop_dup_c);
if (!uasync_set_timeout(t->ua, 5000, t, mesh_tail_stop, "mesh_diagnostic_tail")) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh: tail timer allocation failed"); abort();
}
} else uasync_stop(t->ua);
uasync_stop(t->ua);
return;
}
if (previous != t->phase) mesh_snapshot(t, "phase_change");
if (++t->ticks > MAX_TICKS) {
mesh_snapshot(t, "timeout");
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh: timeout scenario=%d phase=%d ticks=%d", t->scenario, t->phase, t->ticks);
fprintf(stderr, "test: timeout in phase %d (B_rx=%d/%d fin=%d seqok=%d D_rx=%d/%d fin=%d seqok=%d C_rx=%d/%d fin=%d seqok=%d dupC=%u)\n",
(int)t->phase,
g_rx[IDX_B].frames, N_FRAMES, g_rx[IDX_B].fin_seen, g_rx[IDX_B].seq_ok,
@@ -495,6 +572,7 @@ int main(int argc, char** argv) {
debug_config_init(); debug_set_level(DEBUG_LEVEL_ERROR);
debug_set_category_level(DEBUG_CATEGORY_DEBUG, DEBUG_LEVEL_INFO);
if (getenv("UTUN_TEST_DEBUG")) {
debug_set_category_level(DEBUG_CATEGORY_DEBUG, DEBUG_LEVEL_TRACE);
debug_set_category_level_by_name("radio", "debug");
debug_set_category_level_by_name("bgp", "info");
debug_set_category_level_by_name("member_sync", "info");
@@ -512,7 +590,8 @@ int main(int argc, char** argv) {
printf("=== test_radio_mesh ===\n"); fflush(stdout);
TEST("single-thread: diamond (4 nodes) — дубль по 2 путям гасится кэшем (C получает ровно N)"); {
TEST("diamond: complete delivery and deduplication at B/D/C"); {
size_t allocated = u_get_allocated_count();
struct UASYNC* ua = uasync_create();
if (!ua) { FAIL("uasync_create failed"); return 1; }
@@ -541,21 +620,21 @@ int main(int argc, char** argv) {
uasync_mainloop(ua);
int ok = (t.result == 1);
uint64_t gid = strtoull(CH_ID, NULL, 10);
/* Хвост собирает поздние пакеты, но не меняет исходный результат теста. */
uint32_t dup_c = ok && getenv("UTUN_TEST_MESH_TAIL") ? t.stop_dup_c : radio_dup_dropped(t.inst[IDX_C], gid);
if (ok && dup_c == 0) {
/* кадры не задвоились, но и дедупликация не сработала — топология не дала дублей */
printf("WARN: dupC=0 — diamond не породил дублей, кэш не проверен\n");
#ifdef UTUN_TEST_MESH_OBSERVE
for (unsigned int i = 0; i < g_held_count; ++i) {
DEBUG_ERROR(DEBUG_CATEGORY_DEBUG, "mesh gate: discard unsent frame=%u after failure", i);
queue_dgram_free(g_held[i].entry); queue_entry_free(g_held[i].entry);
}
g_held_count = 0;
#endif
for (int i = 0; i < 4; i++) if (t.inst[i]) utun_instance_destroy(t.inst[i]);
uasync_destroy(ua, 0);
if (ok && dup_c > 0) OK();
else if (ok) FAIL("result ok, но дедупликация не сработала (dupC=%u)", dup_c);
else FAIL("result=%d phase=%d dupC=%u", t.result, (int)t.phase, dup_c);
size_t remaining = u_get_allocated_count();
DEBUG_INFO(DEBUG_CATEGORY_DEBUG, "mesh cleanup allocations=%zu->%zu scenarios=%d", allocated, remaining, t.scenario);
if (ok && remaining == allocated) OK();
else FAIL("result=%d phase=%d scenario=%d allocations=%zu->%zu", t.result, (int)t.phase, t.scenario, allocated, remaining);
}
char cmd[512]; snprintf(cmd, sizeof(cmd), "rm -rf %s", dir); (void)!system(cmd);