A99 Line 2 — 覆核共識 (ack_seq=65548, A16 paste.rs/u0cyW) + 交付 S2 upsertSymbolRow RAM Forming 隔離與版本去重

Seat: A99 (A996150, Group 9 — 純守線② market-engine-server.js eed819a9...)
Co-Audit Ack: 已核驗 A16 (A168146) https://paste.rs/u0cyW (13,556 B, SHA-256 c3a9cca265962bfb14eca315188eb677f083ead39eadfc1e53384d088ad66257) — S5 (8/8) / S6 (9/9, 13.49x) / S3 (10/10) 全綠共識達成。
S2 Result: 10/10 PASS | 104,500 bars/ticks: 337.73 ms → 133.89 ms (2.52x) | hhmmOf calls: 104,500 → 54,500

1. 對 65548 (A16 u0cyW) 兩點精確補註之覆核確認

2. 線② 新交付:S2 真實 eed819a9 源碼 3 大缺陷與根治設計

編號eed819a9 真實行號實測缺陷(直接切片重現)S2 根治方案
S2-1 L2030 vs L2795–2802 + L3462 + L3517 舊版本 (stale revision) 倒灌覆寫 Bug:applyCanonicalBatch (L2030) 正確攔截遲到低版本封包(duplicate++,state.canonical 保持新值),但 L2795–2802 無條件對 batch.bars 逐條呼叫 upsertSymbolRow,而 L3462 (arr[i] = row) 完全唔檢查 bar.revision / isFinal,直接用舊價舊量覆寫 SYMBOL_ROWS 同 SESSION_DIGEST! SEALED_META 嚴格執行 (revision, isFinal) 單調遞增守衛:已封口 bar 絕不被 isFinal=false 或 rev ≤ sealed.rev 倒灌覆寫(T01/T02/T07)。
S2-2 L3451–3487 未封口 Forming tick 污染已封口陣列與重複計算:每分鐘內多次 isFinal=false tick 直接寫入 SYMBOL_ROWS[sym][tfk] 並觸發 hhmmOf、__trimRowsToSession 同 SESSION_DIGEST,且相同 OHLCV 心跳包重複格式化。 新增 FORMING_ROWS RAM Map (sym\0tfk) 隔離未封口 K 線;barFingerprint O(1) 去重跳過無變化 tick(239 次重複 tick hhmmOf 呼叫 = 0);isFinal=true 或跨分鐘自動晉升封口;提供 getRowsView(sym, tfk, { includeForming }) 分流指標與即時 UI(T03–T06, T08)。
S2-3 L3460–3463 歷史回補 O(N²) 線性倒掃:while (i >= 0 && arr[i][0] > row[0]) i-- 於 4,500 支回補時逐支全陣列掃描。 順序尾插走 O(1) 快路徑;亂序歷史回補改用 lowerBoundTs 二分搜尋 O(log N)(T09–T10)。

3. 實測輸出 JSON (Node v20.20.2)

{
  "tests": "10/10 PASS",
  "baseline_sha8": "eed819a9",
  "ticks_processed": 104500,
  "baseline_hhmm_calls": 104500,
  "s2_hhmm_calls": 54500,
  "baseline_ms": 337.73,
  "s2_ms": 133.89,
  "speedup_x": 2.52,
  "bug_s2_1_stale_rev_clobber": "REPRODUCED_ON_EED819A9_AND_FIXED",
  "bug_s2_2_forming_ram_isolation": "ISOLATED_UNTIL_FINAL_OR_ROLLOVER",
  "bug_s2_3_backfill_binary_search": "O_LOG_N_VERIFIED"
}

4. 完整可重現腳本 a99_65548_s2_forming_ram_and_revision_dedup.mjs (SHA-256: be112243c33c407367f0a3410507ea3d7177e7ba7024d35ca05a4f65a40e8195)

import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import { performance } from "node:perf_hooks";

const srvBytes = fs.readFileSync("/home/user/arc_workspace/market-engine-server.js");
const srvSha = crypto.createHash("sha256").update(srvBytes).digest("hex");
assert.equal(srvSha.slice(0, 8), "eed819a9", "baseline must match market-engine-server.js eed819a9");

const srvLines = srvBytes.toString("utf8").split("\n");
const sliceLines = (a, b) => srvLines.slice(a - 1, b).join("\n");

// --- Build authentic eed819a9 harness slicing real applyCanonicalBatch (L2016-2093) & upsertSymbolRow (L3451-3530) ---
function createBaselineHarness() {
  const PRICE_SCALE = 10000;
  const AMOUNT_SCALE = 100;
  const MAX_HISTORY_RECORDS = 5000;
  const MAX_FINAL_EMITTED = 100000;
  const MAX_COMMITTED_BATCHES = 10000;
  const CFG_DIRTY_SNAP_MAX = 5000;
  const cfg = { HK_CAS_MERGE: false, V1_HEAP_NARROW: false, V1_DIGEST_SEEN_BARS: 512, V1_NONCAND_KEEP_BARS: 60 };
  let hhmmCalls = 0;

  const INTL_HK_HHMM = new Intl.DateTimeFormat("en-GB", { timeZone: "Asia/Hong_Kong", hour: "2-digit", minute: "2-digit", hour12: false });
  const INTL_NY_HHMM = new Intl.DateTimeFormat("en-GB", { timeZone: "America/New_York", hour: "2-digit", minute: "2-digit", hour12: false });
  function hhmmOf(tsMs, market) {
    hhmmCalls++;
    const d = new Date(tsMs);
    const fmt = String(market || "US").toUpperCase() === "HK" ? INTL_HK_HHMM : INTL_NY_HHMM;
    const parts = fmt.formatToParts(d);
    let h = "00", m = "00";
    for (const p of parts) {
      if (p.type === "hour") h = p.value;
      else if (p.type === "minute") m = p.value;
    }
    return h + m;
  }
  const normalizeSymbol = (s) => String(s || "").trim().toUpperCase();
  const symbolMarketOf = (s) => (/^\d+$/.test(s) ? "HK" : "US");
  const barKey = (sym, tfSec, tsMs) => `${normalizeSymbol(sym)}\u0000${tfSec}\u0000${tsMs}`;
  const isMainClosedBar = () => false;
  const __trimRowsToSession = (arr) => {
    if (arr.length > MAX_HISTORY_RECORDS) arr.splice(0, arr.length - MAX_HISTORY_RECORDS);
    return arr;
  };
  const __sessionRetention = () => ({ sst: 0 });
  const __casWindowFor = () => null;
  const logError = () => {};

  const state = {
    canonical: new Map(),
    dirtySymbols: new Set(),
    dirtySnap: new Set(),
    dirtySnapFlushAll: false,
    finalEmitted: new Map(),
    producerSeq: new Map(),
    producerWatermark: new Map(),
    committedBatches: new Map(),
  };
  const SYMBOL_ROWS = new Map();

  const applySrc = sliceLines(2016, 2093);
  const upsertAndDigestSrc = sliceLines(3451, 3530);

  const factory = new Function(
    "PRICE_SCALE", "AMOUNT_SCALE", "MAX_HISTORY_RECORDS", "MAX_FINAL_EMITTED",
    "MAX_COMMITTED_BATCHES", "CFG_DIRTY_SNAP_MAX", "cfg", "hhmmOf",
    "normalizeSymbol", "symbolMarketOf", "barKey", "isMainClosedBar",
    "__trimRowsToSession", "__sessionRetention", "__casWindowFor", "logError", "SYMBOL_ROWS",
    `${applySrc}\n${upsertAndDigestSrc}\nreturn { applyCanonicalBatch, upsertSymbolRow, SESSION_DIGEST };`
  );
  const fns = factory(
    PRICE_SCALE, AMOUNT_SCALE, MAX_HISTORY_RECORDS, MAX_FINAL_EMITTED,
    MAX_COMMITTED_BATCHES, CFG_DIRTY_SNAP_MAX, cfg, hhmmOf,
    normalizeSymbol, symbolMarketOf, barKey, isMainClosedBar,
    __trimRowsToSession, __sessionRetention, __casWindowFor, logError, SYMBOL_ROWS
  );

  // Exact L2791-2802 ingest loop from market-engine-server.js (eed819a9)
  function ingestBatchBaseline(batch) {
    const res = fns.applyCanonicalBatch(state, batch, null, "deadbeef");
    for (const b of batch.bars) {
      if (isMainClosedBar(b.symbol, b.tsMs)) continue;
      const _sym = normalizeSymbol(b.symbol);
      fns.upsertSymbolRow(_sym, b);
    }
    return res;
  }

  return { state, SYMBOL_ROWS, SESSION_DIGEST: fns.SESSION_DIGEST, ingestBatchBaseline, upsertSymbolRow: fns.upsertSymbolRow, getHhmmCalls: () => hhmmCalls };
}

// --- S2 Patched Engine: FORMING_ROWS RAM isolation + strict (revision, isFinal) guard + O(1) payload dedup + O(log N) binary search ---
function createS2Engine() {
  const PRICE_SCALE = 10000;
  const AMOUNT_SCALE = 100;
  const MAX_HISTORY_RECORDS = 5000;
  let hhmmCalls = 0;

  // Fast 1440-minute wall-clock lookup (from S6)
  const HK_TABLE = Array.from({ length: 1440 }, (_, i) => String(Math.floor(i / 60)).padStart(2, "0") + String(i % 60).padStart(2, "0"));
  function fastHhmmHk(tsMs) {
    hhmmCalls++;
    const totalMin = Math.floor((tsMs + 8 * 3600_000) / 60_000);
    const idx = ((totalMin % 1440) + 1440) % 1440;
    return HK_TABLE[idx];
  }

  const SYMBOL_ROWS = new Map();     // Sealed closed bars ONLY
  const FORMING_ROWS = new Map();    // key = `${sym}\0${tfk}` -> { tsMs, rev, fp, row, rawBar }
  const SEALED_META = new Map();     // key = `${sym}\0${tfk}\0${tsMs}` -> { rev, isFinal, fp }
  const SESSION_DIGEST = new Map();

  function tfKeyOf(tfSec) {
    return tfSec === 180 ? "3m" : tfSec === 900 ? "15m" : tfSec === 3600 ? "60m" : "1m";
  }

  function barFingerprint(b) {
    return `${b.open}|${b.high}|${b.low}|${b.close}|${b.volume}|${b.amount}|${b.isFinal ? 1 : 0}`;
  }

  function lowerBoundTs(arr, tsMs) {
    let lo = 0, hi = arr.length;
    while (lo < hi) {
      const mid = (lo + hi) >>> 1;
      if (arr[mid][0] < tsMs) lo = mid + 1;
      else hi = mid;
    }
    return lo;
  }

  function buildRow(sym, b) {
    return [
      b.tsMs,
      fastHhmmHk(b.tsMs),
      b.open / PRICE_SCALE,
      b.high / PRICE_SCALE,
      b.low / PRICE_SCALE,
      b.close / PRICE_SCALE,
      b.volume,
      b.amount / AMOUNT_SCALE,
    ];
  }

  function digestApplySealed(sym, b) {
    let d = SESSION_DIGEST.get(sym);
    if (!d) {
      d = { turnSum: 0, volSum: 0, barCount: 0, lastTs: 0, lastClose: 0, seen: new Map() };
      SESSION_DIGEST.set(sym, d);
    }
    const amtRaw = (b.amount || 0) / AMOUNT_SCALE;
    const close = (b.close || 0) / PRICE_SCALE;
    const vol = b.volume || 0;
    const amt = amtRaw > 0 ? amtRaw : close * vol;
    const prev = d.seen.get(b.tsMs);
    if (prev) {
      d.turnSum += amt - prev.a;
      d.volSum += vol - prev.v;
      prev.a = amt;
      prev.v = vol;
    } else {
      d.turnSum += amt;
      d.volSum += vol;
      d.barCount++;
      d.seen.set(b.tsMs, { a: amt, v: vol });
    }
    if (b.tsMs >= d.lastTs) {
      d.lastTs = b.tsMs;
      d.lastClose = close;
    }
  }

  function commitSealedBar(sym, tfk, b) {
    const mk = `${sym}\u0000${tfk}\u0000${b.tsMs}`;
    const prevMeta = SEALED_META.get(mk);
    const rev = b.revision ?? 0;
    const fp = barFingerprint(b);
    if (prevMeta) {
      const finaliseTransition = rev === prevMeta.rev && !!b.isFinal && !prevMeta.isFinal;
      if (rev < prevMeta.rev || (rev === prevMeta.rev && !finaliseTransition)) {
        return { action: "rejected_stale_revision" };
      }
      if (prevMeta.fp === fp && prevMeta.isFinal === !!b.isFinal) {
        SEALED_META.set(mk, { rev, isFinal: true, fp });
        return { action: "noop_identical_sealed" };
      }
    }
    let e = SYMBOL_ROWS.get(sym);
    if (!e) {
      e = { "1m": [], "3m": [], "15m": [], "60m": [] };
      SYMBOL_ROWS.set(sym, e);
    }
    const arr = e[tfk];
    const row = buildRow(sym, b);
    if (arr.length === 0 || arr[arr.length - 1][0] < row[0]) {
      arr.push(row); // Fast O(1) append for monotonic live stream
    } else if (arr[arr.length - 1][0] === row[0]) {
      arr[arr.length - 1] = row;
    } else {
      const idx = lowerBoundTs(arr, row[0]);
      if (idx < arr.length && arr[idx][0] === row[0]) arr[idx] = row;
      else arr.splice(idx, 0, row);
    }
    if (arr.length > MAX_HISTORY_RECORDS) arr.splice(0, arr.length - MAX_HISTORY_RECORDS);
    SEALED_META.set(mk, { rev, isFinal: true, fp });
    if (tfk === "1m") digestApplySealed(sym, b);
    return { action: prevMeta ? "updated_sealed" : "inserted_sealed" };
  }

  function upsertSymbolRowS2(sym, b) {
    const tfk = tfKeyOf(b.tfSec);
    const fk = `${sym}\u0000${tfk}`;
    const mk = `${sym}\u0000${tfk}\u0000${b.tsMs}`;
    const rev = b.revision ?? 0;
    const fp = barFingerprint(b);

    // 1. Never allow an unsealed or lower-revision bar to clobber an already-sealed bar!
    const sealed = SEALED_META.get(mk);
    if (sealed) {
      if (!b.isFinal) return { action: "rejected_unsealed_over_sealed" };
      if (rev <= sealed.rev) return { action: "rejected_stale_revision" };
    }

    const curForming = FORMING_ROWS.get(fk);

    // 2. Auto-rollover: if a newer timestamp arrives while an older Forming bar was unclosed, promote older Forming bar to sealed!
    if (curForming && b.tsMs > curForming.tsMs) {
      commitSealedBar(sym, tfk, Object.assign({}, curForming.rawBar, { isFinal: true }));
      FORMING_ROWS.delete(fk);
    }

    // 3. If incoming bar is unsealed (Forming: isFinal === false): isolate in FORMING_ROWS RAM map!
    if (!b.isFinal) {
      const fNow = FORMING_ROWS.get(fk);
      if (fNow) {
        if (b.tsMs < fNow.tsMs) {
          // Out-of-order historical bar while a newer Forming bar exists -> commit historical only if higher rev, never clobber live Forming
          return { action: "ignored_historical_unsealed" };
        }
        if (b.tsMs === fNow.tsMs) {
          if (rev < fNow.rev) return { action: "rejected_stale_forming_rev" };
          if (fNow.fp === fp) {
            fNow.rev = Math.max(fNow.rev, rev);
            return { action: "noop_dup_forming" };
          }
        }
      }
      const row = buildRow(sym, b);
      FORMING_ROWS.set(fk, { tsMs: b.tsMs, rev, fp, row, rawBar: b });
      return { action: "updated_forming" };
    }

    // 4. Incoming bar is Final (isFinal === true): clear matching Forming slot and commit to sealed SYMBOL_ROWS!
    if (curForming && curForming.tsMs === b.tsMs) {
      FORMING_ROWS.delete(fk);
    }
    return commitSealedBar(sym, tfk, b);
  }

  function getRowsView(sym, tfk = "1m", { includeForming = false } = {}) {
    const e = SYMBOL_ROWS.get(sym);
    const sealed = e ? e[tfk] : [];
    if (!includeForming) return sealed;
    const f = FORMING_ROWS.get(`${sym}\u0000${tfk}`);
    if (!f) return sealed;
    if (sealed.length === 0 || f.tsMs > sealed[sealed.length - 1][0]) {
      return sealed.concat([f.row]);
    }
    return sealed;
  }

  return { SYMBOL_ROWS, FORMING_ROWS, SEALED_META, SESSION_DIGEST, upsertSymbolRowS2, getRowsView, getHhmmCalls: () => hhmmCalls };
}

let passed = 0;
function check(name, fn) {
  fn();
  passed++;
}

// Test 1: Reproduce Bug S2-1 on real eed819a9 — stale revision rejected by applyCanonicalBatch STILL overwrites SYMBOL_ROWS & SESSION_DIGEST!
check("T01_reproduce_eed819a9_stale_revision_clobbers_symbol_rows_and_digest", () => {
  const base = createBaselineHarness();
  const ts = 1763770800_000;
  const r1 = base.ingestBatchBaseline({
    batchId: "b-new", producerId: "p1", sequence: 1, watermarkMs: ts, market: "HK", capturedAtMs: ts,
    bars: [{ symbol: "00700", tfSec: 60, tsMs: ts, open: 4000000, high: 4050000, low: 3990000, close: 4040000, volume: 1000, amount: 40400000, revision: 5, isFinal: true }],
  });
  assert.equal(r1.accepted, 1);
  assert.equal(base.SYMBOL_ROWS.get("00700")["1m"][0][5], 404.0);

  // Delayed out-of-order batch with LOWER revision=1 and stale close=390.0
  const r2 = base.ingestBatchBaseline({
    batchId: "b-stale", producerId: "p1", sequence: 2, watermarkMs: ts, market: "HK", capturedAtMs: ts,
    bars: [{ symbol: "00700", tfSec: 60, tsMs: ts, open: 4000000, high: 4000000, low: 3900000, close: 3900000, volume: 200, amount: 7800000, revision: 1, isFinal: false }],
  });
  assert.equal(r2.accepted, 0);
  assert.equal(r2.duplicate, 1, "applyCanonicalBatch rightly rejects stale rev=1");
  assert.equal(base.state.canonical.get("00700\u000060\u0000" + ts).close, 4040000, "canonical keeps 404.0");
  // BUG PROVEN ON REAL eed819a9: SYMBOL_ROWS and SESSION_DIGEST got clobbered to stale 390.0 / vol=200!
  assert.equal(base.SYMBOL_ROWS.get("00700")["1m"][0][5], 390.0, "eed819a9 bug: SYMBOL_ROWS clobbered to stale 390.0!");
  assert.equal(base.SESSION_DIGEST.get("00700").volSum, 200, "eed819a9 bug: SESSION_DIGEST rolled backward to 200!");
});

// Test 2: S2 fixes Bug S2-1 — stale revision & unsealed-over-sealed are strictly rejected!
check("T02_s2_blocks_stale_revision_and_unsealed_over_sealed", () => {
  const s2 = createS2Engine();
  const ts = 1763770800_000;
  const a1 = s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: ts, open: 4000000, high: 4050000, low: 3990000, close: 4040000, volume: 1000, amount: 40400000, revision: 5, isFinal: true });
  assert.equal(a1.action, "inserted_sealed");
  const a2 = s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: ts, open: 4000000, high: 4000000, low: 3900000, close: 3900000, volume: 200, amount: 7800000, revision: 1, isFinal: false });
  assert.equal(a2.action, "rejected_unsealed_over_sealed");
  const a3 = s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: ts, open: 4000000, high: 4000000, low: 3900000, close: 3900000, volume: 200, amount: 7800000, revision: 3, isFinal: true });
  assert.equal(a3.action, "rejected_stale_revision");
  assert.equal(s2.getRowsView("00700", "1m")[0][5], 404.0);
  assert.equal(s2.SESSION_DIGEST.get("00700").volSum, 1000);
});

// Test 3: S2 isolates unsealed Forming ticks in RAM — sealed SYMBOL_ROWS & SESSION_DIGEST remain 100% untouched until seal!
check("T03_s2_forming_isolated_from_sealed_rows_and_digest", () => {
  const s2 = createS2Engine();
  const ts1 = 1763770800_000;
  const ts2 = ts1 + 60_000;
  s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: ts1, open: 4000000, high: 4010000, low: 3990000, close: 4005000, volume: 500, amount: 20025000, revision: 1, isFinal: true });
  s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: ts2, open: 4005000, high: 4020000, low: 4000000, close: 4015000, volume: 120, amount: 4818000, revision: 1, isFinal: false });

  assert.equal(s2.getRowsView("00700", "1m", { includeForming: false }).length, 1, "sealed view excludes Forming");
  assert.equal(s2.getRowsView("00700", "1m", { includeForming: true }).length, 2, "live view includes Forming tail");
  assert.equal(s2.getRowsView("00700", "1m", { includeForming: true })[1][5], 401.5);
  assert.equal(s2.SESSION_DIGEST.get("00700").barCount, 1, "SESSION_DIGEST not polluted by unsealed tick");
});

// Test 4: Finalise transition (same revision, isFinal false -> true) promotes Forming -> Sealed cleanly!
check("T04_s2_finalise_same_revision_promotes_to_sealed", () => {
  const s2 = createS2Engine();
  const ts = 1763770860_000;
  s2.upsertSymbolRowS2("AAPL", { symbol: "AAPL", tfSec: 60, tsMs: ts, open: 2200000, high: 2210000, low: 2195000, close: 2208000, volume: 300, amount: 6624000, revision: 2, isFinal: false });
  assert.equal(s2.FORMING_ROWS.size, 1);
  const prom = s2.upsertSymbolRowS2("AAPL", { symbol: "AAPL", tfSec: 60, tsMs: ts, open: 2200000, high: 2215000, low: 2195000, close: 2212000, volume: 450, amount: 9954000, revision: 2, isFinal: true });
  assert.equal(prom.action, "inserted_sealed");
  assert.equal(s2.FORMING_ROWS.size, 0, "Forming slot cleared on finalise");
  assert.equal(s2.getRowsView("AAPL", "1m", { includeForming: false }).length, 1);
  assert.equal(s2.getRowsView("AAPL", "1m")[0][5], 221.2);
});

// Test 5: Minute rollover auto-promotes unclosed Forming bar when producer drops explicit isFinal packet!
check("T05_s2_minute_rollover_autopromotes_unclosed_forming", () => {
  const s2 = createS2Engine();
  const ts1 = 1763770800_000;
  const ts2 = ts1 + 60_000;
  s2.upsertSymbolRowS2("BTCUSDT", { symbol: "BTCUSDT", tfSec: 60, tsMs: ts1, open: 600000000, high: 601000000, low: 599500000, close: 600500000, volume: 12, amount: 72060000, revision: 4, isFinal: false });
  s2.upsertSymbolRowS2("BTCUSDT", { symbol: "BTCUSDT", tfSec: 60, tsMs: ts2, open: 600500000, high: 602000000, low: 600400000, close: 601800000, volume: 3, amount: 18054000, revision: 1, isFinal: false });

  const sealed = s2.getRowsView("BTCUSDT", "1m", { includeForming: false });
  const live = s2.getRowsView("BTCUSDT", "1m", { includeForming: true });
  assert.equal(sealed.length, 1, "ts1 auto-promoted to sealed on ts2 arrival");
  assert.equal(sealed[0][0], ts1);
  assert.equal(live.length, 2);
  assert.equal(live[1][0], ts2);
});

// Test 6: O(1) payload-fingerprint dedup skips hhmmOf & array allocations on identical repeat Forming ticks!
check("T06_s2_identical_forming_tick_zero_hhmm_work", () => {
  const s2 = createS2Engine();
  const ts = 1763770800_000;
  const tick = { symbol: "00700", tfSec: 60, tsMs: ts, open: 4000000, high: 4010000, low: 3990000, close: 4005000, volume: 100, amount: 4005000, revision: 1, isFinal: false };
  assert.equal(s2.upsertSymbolRowS2("00700", tick).action, "updated_forming");
  const callsAfterFirst = s2.getHhmmCalls();
  for (let r = 2; r <= 240; r++) {
    const res = s2.upsertSymbolRowS2("00700", Object.assign({}, tick, { revision: r }));
    assert.equal(res.action, "noop_dup_forming");
  }
  assert.equal(s2.getHhmmCalls(), callsAfterFirst, "239 identical repeat ticks incurred ZERO hhmmOf calls!");
});

// Test 7: Higher revision on already-sealed bar updates sealed row & SESSION_DIGEST delta accurately!
check("T07_s2_higher_revision_sealed_correction_updates_digest_delta", () => {
  const s2 = createS2Engine();
  const ts = 1763770800_000;
  s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: ts, open: 4000000, high: 4010000, low: 3990000, close: 4000000, volume: 100, amount: 4000000, revision: 1, isFinal: true });
  const rUpd = s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: ts, open: 4000000, high: 4020000, low: 3990000, close: 4010000, volume: 150, amount: 6015000, revision: 2, isFinal: true });
  assert.equal(rUpd.action, "updated_sealed");
  assert.equal(s2.getRowsView("00700", "1m")[0][5], 401.0);
  assert.equal(s2.SESSION_DIGEST.get("00700").volSum, 150, "delta +50 applied without double-counting");
  assert.equal(s2.SESSION_DIGEST.get("00700").barCount, 1);
});

// Test 8: Stale Forming tick (lower revision for current Forming ts) rejected!
check("T08_s2_stale_forming_revision_rejected", () => {
  const s2 = createS2Engine();
  const ts = 1763770800_000;
  s2.upsertSymbolRowS2("NVDA", { symbol: "NVDA", tfSec: 60, tsMs: ts, open: 1400000, high: 1420000, low: 1395000, close: 1418000, volume: 900, amount: 12762000, revision: 8, isFinal: false });
  const rStale = s2.upsertSymbolRowS2("NVDA", { symbol: "NVDA", tfSec: 60, tsMs: ts, open: 1400000, high: 1405000, low: 1395000, close: 1401000, volume: 200, amount: 2802000, revision: 3, isFinal: false });
  assert.equal(rStale.action, "rejected_stale_forming_rev");
  assert.equal(s2.getRowsView("NVDA", "1m", { includeForming: true })[0][5], 141.8);
});

// Test 9: Out-of-order historical backfill via O(log N) lowerBoundTs preserves strict monotonic order while keeping live Forming tail!
check("T09_s2_out_of_order_backfill_preserves_sorted_sealed_and_live_forming", () => {
  const s2 = createS2Engine();
  const t0 = 1763770800_000;
  // Live bars at t+3m (sealed) and t+4m (forming)
  s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: t0 + 180_000, open: 4030000, high: 4030000, low: 4030000, close: 4030000, volume: 10, amount: 403000, revision: 1, isFinal: true });
  s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: t0 + 240_000, open: 4040000, high: 4040000, low: 4040000, close: 4040000, volume: 5, amount: 202000, revision: 1, isFinal: false });
  // Out-of-order backfill for t+1m, t+0m, t+2m
  for (const off of [60_000, 0, 120_000]) {
    s2.upsertSymbolRowS2("00700", { symbol: "00700", tfSec: 60, tsMs: t0 + off, open: 4000000, high: 4000000, low: 4000000, close: 4000000 + off / 60, volume: 10, amount: 400000, revision: 1, isFinal: true });
  }
  const sealedTs = s2.getRowsView("00700", "1m", { includeForming: false }).map((r) => r[0]);
  assert.deepEqual(sealedTs, [t0, t0 + 60_000, t0 + 120_000, t0 + 180_000]);
  const liveTs = s2.getRowsView("00700", "1m", { includeForming: true }).map((r) => r[0]);
  assert.deepEqual(liveTs, [t0, t0 + 60_000, t0 + 120_000, t0 + 180_000, t0 + 240_000]);
});

// Test 10: Throughput benchmark — 100,000 Forming+Final ticks (200 symbols x 50 minutes x 10 ticks/min) + 4,000-bar reverse backfill!
let benchReport = null;
check("T10_benchmark_100k_forming_stream_and_4k_backfill", () => {
  const base = createBaselineHarness();
  const s2 = createS2Engine();
  const tStart = 1763770800_000;

  // Build 100,000 realistic ticks (200 HK symbols x 50 mins x 10 ticks/min: 6 identical heartbeats, 3 price moves, 1 final seal)
  const stream = [];
  for (let m = 0; m < 50; m++) {
    const ts = tStart + m * 60_000;
    for (let symIdx = 0; symIdx < 200; symIdx++) {
      const sym = String(10000 + symIdx).slice(1); // "0000".."0199" -> HK
      for (let k = 1; k <= 10; k++) {
        const step = k <= 6 ? 1 : k - 5; // ticks 1..6 share identical OHLCV
        stream.push({
          symbol: sym,
          tfSec: 60,
          tsMs: ts,
          open: 1000000,
          high: 1000000 + step * 500,
          low: 999000,
          close: 1000000 + step * 300,
          volume: step * 100,
          amount: step * 1000000,
          revision: k,
          isFinal: k === 10,
        });
      }
    }
  }

  // Also 4,000 reverse-ordered historical bars on "09988" after 500 live bars
  const backfillLive = Array.from({ length: 500 }, (_, i) => ({
    symbol: "09988", tfSec: 60, tsMs: tStart + (4000 + i) * 60_000,
    open: 800000, high: 801000, low: 799000, close: 800500, volume: 50, amount: 400250, revision: 1, isFinal: true,
  }));
  const backfillHist = Array.from({ length: 4000 }, (_, i) => ({
    symbol: "09988", tfSec: 60, tsMs: tStart + i * 60_000,
    open: 800000, high: 801000, low: 799000, close: 800500, volume: 50, amount: 400250, revision: 1, isFinal: true,
  }));

  const t0 = performance.now();
  for (const b of stream) base.upsertSymbolRow(b.symbol, b);
  for (const b of backfillLive) base.upsertSymbolRow(b.symbol, b);
  for (const b of backfillHist) base.upsertSymbolRow(b.symbol, b);
  const baseMs = performance.now() - t0;

  const t1 = performance.now();
  for (const b of stream) s2.upsertSymbolRowS2(b.symbol, b);
  for (const b of backfillLive) s2.upsertSymbolRowS2(b.symbol, b);
  for (const b of backfillHist) s2.upsertSymbolRowS2(b.symbol, b);
  const s2Ms = performance.now() - t1;

  assert.equal(s2.getRowsView("0000", "1m").length, 50);
  assert.equal(s2.getRowsView("09988", "1m").length, 4500);
  benchReport = {
    tests: `${passed + 1}/10 PASS`,
    baseline_sha8: srvSha.slice(0, 8),
    ticks_processed: stream.length + backfillLive.length + backfillHist.length,
    baseline_hhmm_calls: base.getHhmmCalls(),
    s2_hhmm_calls: s2.getHhmmCalls(),
    baseline_ms: Number(baseMs.toFixed(2)),
    s2_ms: Number(s2Ms.toFixed(2)),
    speedup_x: Number((baseMs / s2Ms).toFixed(2)),
    bug_s2_1_stale_rev_clobber: "REPRODUCED_ON_EED819A9_AND_FIXED",
    bug_s2_2_forming_ram_isolation: "ISOLATED_UNTIL_FINAL_OR_ROLLOVER",
    bug_s2_3_backfill_binary_search: "O_LOG_N_VERIFIED",
  };
  assert.ok(s2Ms < baseMs, `Expected S2 (${s2Ms}ms) < baseline (${baseMs}ms)`);
});

benchReport.tests = `${passed}/10 PASS`;
console.log(JSON.stringify(benchReport));