cleanRules.test.ts 41 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
// @vitest-environment node
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import {
  classifyRegion,
  flagOfMissing,
  missingDimLabels,
  presentDimLabels,
  isStreetUnresolved,
  markIsolated,
  markSmallClusters,
  markSparseRoads,
  markSparseStreets,
  streetNameOf,
  SMALL_DEFAULT_RADIUS_M,
  SMALL_DEFAULT_THRESHOLD,
  SPARSE_DEFAULT_THRESHOLD,
  SPARSE_STREET_DEFAULT_THRESHOLD,
  CLASS_DEFAULTS,
  FLAG,
} from './cleanRules';
import { applyExclusions, maskOfKeys, reconcileMeta } from './applyExclusions';
import { parseDistrictGeometry } from '../geo/districtShapes';
import { pointInPolygons } from '../geo/polygon';
import type { CleanClass, CleanClassKey, IncidentColumns, MetaFile } from '../aggregate/types';

/**
 * 清洗规则的测试。
 *
 * 这里的每一条都对应一个「错了也看不出来、等政企问起来才发现」的地方:
 *   · MultiPolygon 分块 —— 判错会让大鹏半岛整片案子被当成域外;
 *   · 辖区归属 —— 判漏会让邻市案子混进深圳的榜,判错会把深圳案子剔掉;
 *   · 孤立点三档嵌套 —— 算错会让「剔 500m」实际剔的是另一批;
 *   · 剔除后守恒 —— 不守恒就是界面上两个数加不起来,当场被问住。
 * 所以断言都拿真实区界文件和真实地址,不用假几何凑数。
 */

const GEO = new URL('../../../../public/geo/shenzhen.geojson', import.meta.url);
const raw = JSON.parse(readFileSync(GEO, 'utf8')) as unknown;

const COORD_SCALE = 1e6;

describe('区界文件解析', () => {
  const named = parseDistrictGeometry(raw);
  const all = named.flatMap((g) => g.polys);

  it('九个区都在,且块数保留完整', () => {
    expect(named.length).toBe(9);
    // 龙岗区 2 块(第二块就是大鹏半岛),块被平铺的话这条会挂
    const longgang = named.find((g) => g.name === '龙岗区');
    expect(longgang?.polys.length).toBe(2);
  });

  /**
   * 这条钉的是踩过的那个坑:把 MultiPolygon 各块的环平铺成一条数组,
   * 第二块的外环会被当成「洞」,整块判不进去。
   * 第一版探针因此把大鹏半岛的 504 条案子全判成了域外。
   *
   * 区界只用于地图绘制与区界聚焦,清洗不再拿它判归属(见 classifyRegion),
   * 但这份文件本身要是对的 —— 画错边界同样是给政企看的东西。
   */
  it('大鹏半岛(龙岗区第二块)判得进去', () => {
    for (const [lng, lat] of [
      [114.4151, 22.631],
      [114.5127, 22.6516],
      [114.5512, 22.4831],
    ]) {
      expect(pointInPolygons(lng, lat, all), `${lng},${lat}`).toBe(true);
    }
  });
});

describe('辖区归属:只看出险地址,不看坐标', () => {
  const sz = (parts: string[], districtCol = '', streetCol = '') =>
    classifyRegion(parts, districtCol, streetCol);

  it('地址写明深圳市辖区 → 不标邻市', () => {
    expect(sz(['广东省', '深圳市', '光明区', '光侨北路']).flag).toBe(0);
    expect(sz(['深圳市', '光明区', '光侨北路']).flag).toBe(0);
  });

  it('地址漏了「深圳市」但写着深圳的区名 → 不标邻市', () => {
    expect(sz(['广东省', '光明区', '光侨北路']).flag).toBe(0);
    expect(sz(['光明区', '光侨北路']).flag).toBe(0);
  });

  it('行政区列填了深圳的区 → 不标邻市', () => {
    expect(sz([], '光明区').flag).toBe(0);
    expect(sz([], '大鹏新区').flag).toBe(0);
  });

  /**
   * 「光明新区 / 龙华新区 / 坪山新区」是 2016 年前后由功能区转成的行政区旧名,
   * 对应光明区 / 龙华区 / 坪山区。它们以「区」结尾,若不单独认作深圳,
   * 会在 firstOutside 里撞上 COUNTY_TAIL 被当成邻市的区剔掉 —— 正是「光明新区 归为光明区」要堵的错路。
   */
  it('功能区旧名(光明新区 / 龙华新区 / 坪山新区)→ 不标邻市', () => {
    expect(sz(['广东省', '深圳市', '光明新区', '公明街道']).flag).toBe(0);
    expect(sz(['广东省', '深圳市', '龙华新区', '民治街道']).flag).toBe(0);
    expect(sz(['广东省', '深圳市', '坪山新区', '坑梓街道']).flag).toBe(0);
    // 连「深圳市」前缀都没有、只写旧名,也要认出来是深圳
    expect(sz(['广东省', '光明新区', '公明街道']).flag).toBe(0);
  });

  /**
   * 详细地址段(第 4 段起)不参与判定。
   *
   * 深圳的地址里满是「臣田工业区」「宝安综合港区」这类以「区」结尾的地名,
   * 若按后缀去认行政层级,这些全是深圳本地的地方会被判成邻市剔掉 ——
   * 判定只在行政层级位置(行政区列 / 街道列 / 地址前 3 段)上做。
   */
  it('详细地址段里的「××工业区 / 港区」不算外市', () => {
    expect(
      sz(['广东省', '深圳市', '宝安区', '福海街道联建商务中心深圳港宝安综合港区']).flag,
    ).toBe(0);
  });

  it('地址写着东莞市 → 邻市,并把证据念出来', () => {
    const v = sz(['广东省', '东莞市', '凤岗镇', '官井头收费站']);
    expect(v.flag).toBe(FLAG.OUTSIDE);
    expect(v.evidence).toBe('东莞市');
    // 全文硬标记扫描压过前 3 段扫描,作为首要判定路径
    expect(v.source).toBe('地址全文外市标记');
  });

  /**
   * 这条就是「邻市为什么 0 条」的根因:源数据每行都套「广东省-深圳市-…」前缀,
   * 旧判据一看到第 2 段的「深圳市」就认成深圳,东莞市被盖掉,
   * 那几行全落进了「坐标在区界之外」那一类。现在外市证据优先,前缀盖不住。
   */
  it('源数据套了「深圳市」前缀,也盖不住东莞市', () => {
    const v = sz(['广东省', '深圳市', '东莞市', '官井头收费站']);
    expect(v.flag).toBe(FLAG.OUTSIDE);
    expect(v.evidence).toBe('东莞市');
  });

  /**
   * 超人点出的那类漏判:前缀写「龙岗区」、第 4 段细节里其实在东莞。
   * 旧逻辑只扫地址前 3 段(广东省 / 深圳市 / 龙岗区),第 4 段的「东莞市 / 凤岗镇」从不被检查,
   * 于是这行被误计入龙岗区。现在整条地址硬标记扫描压过前缀,应判邻市。
   */
  it('前缀写龙岗区、细节里其实在东莞 → 邻市(全文扫描兜底)', () => {
    const v = sz(['广东省', '深圳市', '龙岗区', '东莞市南门山森林公园小草湖庄园(凤岗镇)地上停车场']);
    expect(v.flag).toBe(FLAG.OUTSIDE);
    expect(v.evidence).toBe('东莞市');
    expect(v.source).toBe('地址全文外市标记');
  });

  /**
   * 精度兜底:深圳本地地名含「凤岗」(凤岗小学)但没带「镇」后缀,不应被当成东莞凤岗镇误剔。
   * 硬标记只认「凤岗镇」整串,不认裸「凤岗」。
   */
  it('深圳本地「凤岗小学」不含「镇」后缀 → 不标邻市', () => {
    expect(sz(['广东省', '深圳市', '龙岗区', '凤岗小学']).flag).toBe(0);
  });

  /** 凤岗是东莞的镇:地址没写清辖区时,街道列(补全工具按 township 填的)就是证据 */
  it('地址没写清辖区时,街道列写着凤岗镇 → 邻市', () => {
    const v = sz(['广东省', '深圳市', '某路'], '', '凤岗镇');
    expect(v.flag).toBe(FLAG.OUTSIDE);
    expect(v.evidence).toBe('凤岗镇');
    expect(v.source).toBe('街道列');
  });

  it('行政区列回填了东莞市(地址没写清)→ 邻市', () => {
    const v = sz(['广东省', '深圳市', '某路'], '东莞市', '');
    expect(v.flag).toBe(FLAG.OUTSIDE);
    expect(v.evidence).toBe('东莞市');
    expect(v.source).toBe('行政区列');
  });

  /**
   * 反过来写的那条不能丢:地址明明白白写着深圳某区,街道列却被回填成凤岗镇
   * (交界处两个来源打架),这时候听地址的 —— 以出险地址为准。
   */
  it('地址写明深圳某区时,回填列里的外市镇名不推翻地址', () => {
    expect(sz(['广东省', '深圳市', '龙岗区', '某路'], '', '凤岗镇').flag).toBe(0);
    expect(sz(['广东省', '深圳市', '光明区', '光侨北路'], '东莞市', '').flag).toBe(0);
  });

  /** 深圳 2004 年撤镇设街道,辖内已无镇建制 —— 地址里的「××镇」就是邻市 */
  it('地址第 3 段写着别的镇 → 邻市', () => {
    expect(sz(['广东省', '东莞市', '塘厦镇', '某路']).flag).toBe(FLAG.OUTSIDE);
  });

  it('别市有同名区(鹤岗市南山区)→ 邻市,不按区名认成深圳', () => {
    const v = sz(['黑龙江省', '鹤岗市', '南山区', '某路']);
    expect(v.flag).toBe(FLAG.OUTSIDE);
    expect(v.evidence).toBe('鹤岗市');
  });

  it('外市的区县(惠阳区)→ 邻市', () => {
    expect(sz(['广东省', '惠州市', '惠阳区', '某路']).flag).toBe(FLAG.OUTSIDE);
  });

  /** 读不出辖区的一律不按邻市剔 —— 宁可留一条本该剔的,也不能把「没写清」当「写了外市」 */
  it('读不出辖区时不标邻市', () => {
    expect(sz(['白鸽湖路白鸽湖办公大楼']).flag).toBe(0);
    expect(sz([]).flag).toBe(0);
  });

  it('默认处置:邻市与三项全缺默认剔、可取消;缺一部分默认保留', () => {
    expect(CLASS_DEFAULTS.OUTSIDE).toEqual({ fixed: false, defaultOn: true });
    expect(CLASS_DEFAULTS.MISSING).toEqual({ fixed: false, defaultOn: true });
    expect(CLASS_DEFAULTS.MISSING_PARTIAL.defaultOn).toBe(false);
  });
});

describe('字段缺失判定', () => {
  /**
   * **只要有一项取得到就不剔**:三项全缺才 MISSING(固定剔除);
   * 缺一部分只标 MISSING_PARTIAL(默认保留、可勾选,缺哪一维不进那一维的排名)。
   *
   * 早先是「区读不出即 MISSING、且固定剔除」,于是「宝安区-福海街道联建商务中心
   * 深圳港宝安综合港区」这种区街道都读得出、只差路名的真实事故被无条件删掉,
   * 导入人连勾选框都没有;而「区读不出但道路读得出」的行同样被整条丢掉,
   * 明明它还能进道路榜。
   */
  it('三项全缺 → MISSING', () => {
    expect(flagOfMissing('', '', '')).toBe(FLAG.MISSING);
  });

  it('只要有一项取得到就不剔:区缺但街道或道路有值 → 只标 MISSING_PARTIAL', () => {
    expect(flagOfMissing('', '粤海街道', '深南大道')).toBe(FLAG.MISSING_PARTIAL);
    expect(flagOfMissing('', '粤海街道', '')).toBe(FLAG.MISSING_PARTIAL);
    expect(flagOfMissing('', '', '深南大道')).toBe(FLAG.MISSING_PARTIAL);
  });

  it('区读得出、缺街道或道路 → 只标 MISSING_PARTIAL', () => {
    expect(flagOfMissing('南山区', '', '深南大道')).toBe(FLAG.MISSING_PARTIAL);
    expect(flagOfMissing('南山区', '粤海街道', '')).toBe(FLAG.MISSING_PARTIAL);
    expect(flagOfMissing('南山区', '', '')).toBe(FLAG.MISSING_PARTIAL);
  });

  it('三项齐全不标任何位', () => {
    expect(flagOfMissing('南山区', '粤海街道', '深南大道')).toBe(0);
  });

  it('缺一部分的那一档默认保留、可勾选;三项全缺那一档默认剔、也可取消', () => {
    expect(CLASS_DEFAULTS.MISSING_PARTIAL).toEqual({ fixed: false, defaultOn: false });
    expect(CLASS_DEFAULTS.MISSING).toEqual({ fixed: false, defaultOn: true });
  });

  it('样例念出缺哪几维、还剩哪几维', () => {
    expect(missingDimLabels('南山区', '', '深南大道')).toEqual(['街道']);
    expect(missingDimLabels('南山区', '粤海街道', '')).toEqual(['道路']);
    expect(missingDimLabels('', '粤海街道', '')).toEqual(['行政区', '道路']);
    expect(missingDimLabels('', '', '')).toEqual(['行政区', '街道', '道路']);
    expect(presentDimLabels('南山区', '', '深南大道')).toEqual(['行政区', '道路']);
  });
});

describe('孤立点分档', () => {
  /** 三个点:前两个相距约 50m,第三个在 5km 外 */
  const pts: Array<[number, number]> = [
    [114.0, 22.6],
    [114.0, 22.60045],
    [114.05, 22.65],
  ];
  const lng = new Int32Array(pts.map((p) => Math.round(p[0] * COORD_SCALE)));
  const lat = new Int32Array(pts.map((p) => Math.round(p[1] * COORD_SCALE)));
  const flags = new Uint16Array(pts.length);
  markIsolated(lng, lat, COORD_SCALE, flags);

  it('彼此在 200m 内的点不算孤立', () => {
    expect(flags[0] & FLAG.ISO_200).toBe(0);
    expect(flags[1] & FLAG.ISO_200).toBe(0);
  });

  /** 三档是嵌套的:1km 内无邻居必然 500m 无邻居、也必然 200m 无邻居 */
  it('远处的点三档全部命中', () => {
    expect(flags[2] & FLAG.ISO_200).not.toBe(0);
    expect(flags[2] & FLAG.ISO_500).not.toBe(0);
    expect(flags[2] & FLAG.ISO_1000).not.toBe(0);
  });

  it('不覆盖已有的其它类别位', () => {
    const f = new Uint16Array(pts.length);
    f[0] = FLAG.MISSING;
    markIsolated(lng, lat, COORD_SCALE, f);
    expect(f[0] & FLAG.MISSING).not.toBe(0);
  });

  it('最近邻距离如实回填,找不到时写 Infinity', () => {
    const near = new Float32Array(pts.length);
    markIsolated(lng, lat, COORD_SCALE, new Uint16Array(pts.length), near);
    expect(near[0]).toBeGreaterThan(0);
    expect(near[0]).toBeLessThan(200);
    expect(near[2]).toBe(Infinity);
  });
});

/**
 * E 类「道路低频」。
 *
 * 这一类是唯一没有「错」可指的一类,所以口径比别处更容易被改歪 ——
 * 下面几条钉的都是「改完之后看起来还在工作、实际已经换了意思」的地方:
 *   · 「读不出路名」那一档(下标 0)一旦参与计数,两万多条不同地点的记录
 *     会被当成同一条「路」,于是要么全剔要么全留;
 *   · count 是行数、roads 是路数,阈值 ≥2 之后两个数就分开了,混用会对不上账;
 *   · 幂等性 —— 导入人拖阈值会反复调用,不幂等就会把上一轮的标记累积下来。
 */
describe('道路低频判定', () => {
  const roadNames = ['', '甲路', '乙路', '丙路', '丁路'];
  /** 下标 0(读不出)2 行 · 甲路 1 行 · 乙路 3 行 · 丙路 2 行 · 丁路 2 行 */
  const r = new Uint16Array([0, 0, 1, 2, 2, 2, 3, 3, 4, 4]);
  const lng = new Int32Array(10);
  const lat = new Int32Array(10);
  const caseNo = Array.from({ length: 10 }, (_, i) => `NO${i}`);

  function run(threshold: number, over?: { r?: Uint16Array; roadNames?: string[] }) {
    const rr = over?.r ?? r;
    const flags = new Uint16Array(rr.length);
    const res = markSparseRoads({
      r: rr,
      flags,
      threshold,
      roadNames: over?.roadNames ?? roadNames,
      caseNo,
      addressOf: (i) => `地点${i}`,
      lng,
      lat,
      coordScale: COORD_SCALE,
      maxSamples: 5,
    });
    return { ...res, flags };
  }

  it('阈值 0 表示关闭,一行都不标', () => {
    const out = run(0);
    expect(out.count).toBe(0);
    expect(out.roads).toBe(0);
    expect(out.samples.length).toBe(0);
    expect([...out.flags].every((f) => (f & FLAG.SPARSE) === 0)).toBe(true);
  });

  it('阈值 1 只标出现 1 次的路', () => {
    const out = run(1);
    // 只有甲路(1 行)命中;乙路 3 行、丙丁各 2 行都不满足
    expect(out.count).toBe(1);
    expect(out.roads).toBe(1);
    expect(out.flags[2] & FLAG.SPARSE).not.toBe(0);
    expect(out.flags[3] & FLAG.SPARSE).toBe(0);
  });

  /** count 是案件行数,roads 是路数 —— 阈值 ≥2 之后两者必然分开 */
  it('阈值 2 时行数与路数分开算', () => {
    const out = run(2);
    expect(out.count).toBe(5); // 甲 1 + 丙 2 + 丁 2
    expect(out.roads).toBe(3);
  });

  it('阈值提到 3 把乙路也扫进来,且不重复计数', () => {
    const out = run(3);
    expect(out.count).toBe(8);
    expect(out.roads).toBe(4);
  });

  /**
   * 这一条是这一类的命门。
   *
   * 下标 0 是「地址没写路名」的记号,不是一条路。它若参与计数,
   * 真实数据里那 2 万多条就会按「这一档总共几起」去比阈值 ——
   * 于是要么一整档全被剔,要么一整档全留下,两种都错得离谱。
   */
  it('「读不出路名」那一档永不参与判定', () => {
    // 只有 road 0 出现 1 行,其余路各 3 行:按路数看它最该被判低频
    const only = new Uint16Array([0, 1, 1, 1, 2, 2, 2, 3, 3, 3]);
    const out = run(1, { r: only });
    expect(out.count).toBe(0);
    expect(out.roads).toBe(0);
    expect([...out.flags].every((f) => (f & FLAG.SPARSE) === 0)).toBe(true);
  });

  /** 导入人拖阈值会反复调用;不幂等就会把上一次的标记留在里面 */
  it('反复调用幂等:先阈值 3 再回到 1,结果等于直接跑阈值 1', () => {
    const once = run(1);
    const flags = new Uint16Array(r.length);
    for (const t of [3, 5, 2, 1]) {
      markSparseRoads({
        r,
        flags,
        threshold: t,
        roadNames,
        caseNo,
        addressOf: (i) => `地点${i}`,
        lng,
        lat,
        coordScale: COORD_SCALE,
        maxSamples: 5,
      });
    }
    expect([...flags]).toEqual([...once.flags]);
  });

  it('已有的其它类别位不被清掉', () => {
    const flags = new Uint16Array(r.length);
    flags[2] = FLAG.MISSING | FLAG.OUTSIDE;
    markSparseRoads({
      r,
      flags,
      threshold: 1,
      roadNames,
      caseNo,
      addressOf: (i) => `地点${i}`,
      lng,
      lat,
      coordScale: COORD_SCALE,
      maxSamples: 5,
    });
    expect(flags[2] & FLAG.MISSING).not.toBe(0);
    expect(flags[2] & FLAG.OUTSIDE).not.toBe(0);
    expect(flags[2] & FLAG.SPARSE).not.toBe(0);
  });

  it('样例写明这一条路本批次共几起', () => {
    // 甲、乙各 1 行,丙、丁各 12 行:阈值 3 下只有甲乙命中
    const many = new Uint16Array([1, 2, ...Array.from({ length: 24 }, (_, i) => (i < 12 ? 3 : 4))]);
    const out = run(3, { r: many, roadNames });
    expect(out.count).toBe(2);
    expect(out.samples.length).toBe(2);
    expect(out.samples[0]?.note).toBe('本批次「甲路」共 1 起');
  });

  /**
   * 样例的意义是让人看到「都落在哪些路上」,所以同一条路只在样例里出一次。
   *
   * 阈值调大之后行会集中到少数几条路上(阈值 10 时 12,342 行只分属 4,568 条路),
   * 纯等距取样会让 5 条样例里出现两条同一条路 —— 等于白看一条。
   */
  it('样例按路去重:同一条路不重复占位', () => {
    // 甲路 60 行、乙路 3 行:阈值 60 下 63 行全部命中,但只分属 2 条路
    const skewed = new Uint16Array([
      ...Array.from({ length: 60 }, () => 1),
      ...Array.from({ length: 3 }, () => 2),
    ]);
    const out = run(60, { r: skewed });
    expect(out.count).toBe(63);
    expect(out.roads).toBe(2);
    // 第一轮按路去重只凑得出 2 条,第二轮补位到 5 条
    expect(out.samples.length).toBe(5);
    expect(out.samples.slice(0, 2).map((s) => s.note)).toEqual([
      '本批次「甲路」共 60 起',
      '本批次「乙路」共 3 起',
    ]);
    // 补位不能把同一条记录收两遍
    const notes = out.samples.map((s) => `${s.caseNo}|${s.address}`);
    expect(new Set(notes).size).toBe(5);
  });

  /** 定型数组越界读会静默返回 undefined,加 1 之后写回变成 0 —— 那批行会被整批误标 */
  it('r 的下标超出路名表时不静默误标,按实际下标取宽度', () => {
    const beyond = new Uint16Array([20, 20, 1, 1, 1]); // 下标 20 不在 roadNames 里
    const out = run(1, { r: beyond });
    // 路 20 有 2 行 > 阈值 1,不该被标;路 1 有 3 行,也不该被标
    expect(out.count).toBe(0);
    expect([...out.flags].every((f) => (f & FLAG.SPARSE) === 0)).toBe(true);
  });

  it('默认阈值常量为 1(与导入弹窗的初值同源)', () => {
    expect(SPARSE_DEFAULT_THRESHOLD).toBe(1);
    const out = run(SPARSE_DEFAULT_THRESHOLD);
    expect(out.count).toBe(1);
  });
});

/* ---------------------------------------------------------------------------
   G 类街道低频
   与 E 类同机制(markSparseByDim),但两处口径是街道独有的:
   ① 字典项形如「区|街道名」,判「读不出」与念名字都得先剥前缀
   ② 「未识别|凤岗镇」这种写得清清楚楚、只是不属于深圳街道体系的档,仍按有名有姓处理
      ——它该由 C 类辖区归属去管,两类各标各的,别在这里越俎代庖
   --------------------------------------------------------------------------- */

describe('街道低频判定(G 类)', () => {
  /** 与 ingestCore 的 intern 同形:竖线前是区、后是街道名 */
  const streetNames = [
    '福田区|园岭街道',
    '南山区|沙河街道',
    '龙岗区|布吉街道',
    '福田区|未识别',
    '未识别|凤岗镇',
  ];
  /** 园岭 1 行 · 沙河 3 行 · 布吉 2 行 · 福田未识别 2 行 · 凤岗镇(东莞)1 行 */
  const s = new Uint16Array([0, 1, 1, 1, 2, 2, 3, 3, 4]);
  const lng = new Int32Array(9);
  const lat = new Int32Array(9);
  const caseNo = Array.from({ length: 9 }, (_, i) => `NO${i}`);

  function run(threshold: number) {
    const flags = new Uint16Array(s.length);
    const res = markSparseStreets({
      s,
      flags,
      threshold,
      streetNames,
      caseNo,
      addressOf: (i) => `地点${i}`,
      lng,
      lat,
      coordScale: COORD_SCALE,
      maxSamples: 5,
    });
    return { ...res, flags };
  }

  it('阈值 0 表示关闭,一行都不标', () => {
    const out = run(0);
    expect(out.count).toBe(0);
    expect(out.streets).toBe(0);
    expect([...out.flags].every((f) => (f & FLAG.SPARSE_STREET) === 0)).toBe(true);
  });

  it('阈值 1 只标出现 1 次的街道(园岭 1 行 · 凤岗镇 1 行)', () => {
    const out = run(1);
    expect(out.count).toBe(2);
    expect(out.streets).toBe(2);
    expect(out.flags[0] & FLAG.SPARSE_STREET).not.toBe(0);
    expect(out.flags[8] & FLAG.SPARSE_STREET).not.toBe(0);
    // 沙河 3 行、布吉 2 行都不满足
    expect(out.flags[1] & FLAG.SPARSE_STREET).toBe(0);
    expect(out.flags[4] & FLAG.SPARSE_STREET).toBe(0);
  });

  it('阈值 2 把布吉(2 行)也扫进来,行数与街道数分开算', () => {
    const out = run(2);
    expect(out.count).toBe(4); // 园岭 1 + 布吉 2 + 凤岗镇 1
    expect(out.streets).toBe(3);
  });

  /**
   * 这一条是 G 类的命门,判据落在竖线**后**那一段上。
   *
   * 「福田区|未识别」有 2 行,若拿整个字典项去比 UNRESOLVED_LABEL 就会判不出它是未识别,
   * 于是阈值 2 时这 2 行会被当成「福田区|未识别这个街道只出了 2 起」而剔除 ——
   * 而它们本来就该整档撤出名次、归到「未标注街道名称」那一类,不该被低频清洗碰。
   */
  it('「未识别」那一档永不参与判定', () => {
    const out = run(2);
    expect(out.flags[6] & FLAG.SPARSE_STREET).toBe(0);
    expect(out.flags[7] & FLAG.SPARSE_STREET).toBe(0);
    // 反证:把阈值提到 20(全部档都低于它),未识别那 2 行仍然一个都不标
    const all = run(20);
    expect(all.flags[6] & FLAG.SPARSE_STREET).toBe(0);
    expect(all.flags[7] & FLAG.SPARSE_STREET).toBe(0);
  });

  /**
   * 「未识别|凤岗镇」:区读不出、街道写着东莞的镇。
   *
   * 它写得清清楚楚,只是不属于深圳街道体系 —— 那是 C 类辖区归属该管的事。
   * G 类的判据只认「街道字典里的档」,所以照标,不在这里越界做行政归属判断。
   */
  it('区未识别但街道有值的档按有名有姓处理', () => {
    expect(isStreetUnresolved('未识别|凤岗镇')).toBe(false);
    expect(isStreetUnresolved('福田区|未识别')).toBe(true);
    expect(isStreetUnresolved('没有竖线')).toBe(true);
    expect(isStreetUnresolved(undefined)).toBe(true);
  });

  it('街道名剥掉区前缀,样例里念的是街道名而不是整个字典项', () => {
    expect(streetNameOf('福田区|园岭街道')).toBe('园岭街道');
    expect(streetNameOf('没有竖线')).toBe('没有竖线');
    expect(streetNameOf(undefined)).toBe('');
    const out = run(1);
    expect(out.samples[0]?.note).toBe('本批次「园岭街道」共 1 起');
  });

  /** 导入人拖阈值会反复调用;不幂等就会把上一次的标记留在里面 */
  it('反复调用幂等:先阈值 3 再回到 1,结果等于直接跑阈值 1', () => {
    const once = run(1);
    const flags = new Uint16Array(s.length);
    for (const t of [3, 5, 2, 1]) {
      markSparseStreets({
        s,
        flags,
        threshold: t,
        streetNames,
        caseNo,
        addressOf: (i) => `地点${i}`,
        lng,
        lat,
        coordScale: COORD_SCALE,
        maxSamples: 5,
      });
    }
    expect([...flags]).toEqual([...once.flags]);
  });

  /** E 与 G 走的是同一个位掩码,同一行可以同时落进两类 —— 两个位互不干扰 */
  it('与道路低频共存:两个位各标各的', () => {
    const flags = new Uint16Array(s.length);
    flags[1] = FLAG.SPARSE;
    markSparseStreets({
      s,
      flags,
      threshold: 2,
      streetNames,
      caseNo,
      addressOf: (i) => `地点${i}`,
      lng,
      lat,
      coordScale: COORD_SCALE,
      maxSamples: 5,
    });
    // 沙河(3 行)不被 G 标,但 E 给它打过标记,那个位得留着
    expect(flags[1] & FLAG.SPARSE).not.toBe(0);
    expect(flags[1] & FLAG.SPARSE_STREET).toBe(0);
    // 布吉(2 行)被 G 标
    expect(flags[4] & FLAG.SPARSE_STREET).not.toBe(0);
  });

  /**
   * SPARSE_STREET 是第 10 位(1<<9),flags 是 Uint16Array 刚好兜得住。
   * 若哪天把 flags 退回 Uint8Array,这一位会被静默截断成 0 —— 界面上表现为
   * 「街道低频永远是 0 条」,而且不报错。这条钉在这里防的就是这种静默失效。
   */
  it('第 10 位不被截断', () => {
    const out = run(1);
    expect(FLAG.SPARSE_STREET).toBe(1 << 9);
    expect(out.flags[0] & FLAG.SPARSE_STREET).toBe(FLAG.SPARSE_STREET);
  });

  it('默认阈值常量为 1,与道路低频同源', () => {
    expect(SPARSE_STREET_DEFAULT_THRESHOLD).toBe(1);
    expect(SPARSE_STREET_DEFAULT_THRESHOLD).toBe(SPARSE_DEFAULT_THRESHOLD);
    expect(run(SPARSE_STREET_DEFAULT_THRESHOLD).count).toBe(2);
  });
});

/* ---------------------------------------------------------------------------
   F 类小热点
   钉住四条改了也看不出来的口径:① 计数含自身 ② 与 D 类在阈值 1 时等价
   ③ 幂等(半径/阈值可反复改)④ 半径跨格子时不能漏点
   --------------------------------------------------------------------------- */

describe('小热点(F 类)', () => {
  /** 深圳某处的基准点,往北/东偏移 `d` 米造一组点 */
  const BASE = { lng: 114.06, lat: 22.55 };
  const M_PER_DEG_LAT = 110700;
  const mPerDegLng = 111195 * Math.cos((BASE.lat * Math.PI) / 180);

  function build(
    offsets: Array<{ dx: number; dy: number }>,
    over?: Partial<Parameters<typeof markSmallClusters>[0]>,
  ) {
    const n = offsets.length;
    const lng = new Int32Array(n);
    const lat = new Int32Array(n);
    for (let i = 0; i < n; i += 1) {
      lng[i] = Math.round((BASE.lng + offsets[i].dx / mPerDegLng) * COORD_SCALE);
      lat[i] = Math.round((BASE.lat + offsets[i].dy / M_PER_DEG_LAT) * COORD_SCALE);
    }
    const flags = new Uint16Array(n);
    const out = markSmallClusters({
      lng,
      lat,
      coordScale: COORD_SCALE,
      flags,
      radiusM: SMALL_DEFAULT_RADIUS_M,
      threshold: SMALL_DEFAULT_THRESHOLD,
      caseNo: offsets.map((_, i) => `NO${i}`),
      addressOf: (i) => `地址${i}`,
      maxSamples: 5,
      ...over,
    });
    return { ...out, flags, n };
  }

  /** 三个点挤在 100m 内,另一个落在 5km 外 */
  const CLUSTERED = [
    { dx: 0, dy: 0 },
    { dx: 30, dy: 0 },
    { dx: 0, dy: 40 },
    { dx: 5000, dy: 0 },
  ];

  it('计数含自身:三个点挤在一起时每个点都算 3 起', () => {
    // 前三个点两两相距 ≤50m,1km 内各数到 3 起;第 4 个在 5km 外,只数到自己
    const t2 = build(CLUSTERED, { threshold: 2 });
    // 阈值 2:挤在一起那三个(各 3 起)不标,只有 5km 外那个(1 起)命中
    expect(t2.count).toBe(1);
    expect(t2.flags[0] & FLAG.SMALL).toBe(0);
    expect(t2.flags[3] & FLAG.SMALL).not.toBe(0);

    // 阈值 3:三个一起命中,加上远处那个共 4 条
    const t3 = build(CLUSTERED, { threshold: 3 });
    expect(t3.count).toBe(4);
  });

  it('阈值 1 时与 D 类孤立(同半径)等价 —— 半径内只有自己 = 最近邻 ≥ 半径', () => {
    const R = 500;
    const pts = [
      { dx: 0, dy: 0 },
      { dx: 100, dy: 0 }, // 两点相距 100m,都不是孤立
      { dx: 3000, dy: 0 }, // 孤立
    ];
    const lng = new Int32Array(3);
    const lat = new Int32Array(3);
    for (let i = 0; i < 3; i += 1) {
      lng[i] = Math.round((BASE.lng + pts[i].dx / mPerDegLng) * COORD_SCALE);
      lat[i] = Math.round((BASE.lat + pts[i].dy / M_PER_DEG_LAT) * COORD_SCALE);
    }
    const isoFlags = new Uint16Array(3);
    markIsolated(lng, lat, COORD_SCALE, isoFlags);

    const { flags } = build(pts, { radiusM: R, threshold: 1 });
    // ISO_500 只在第 3 个点成立,SMALL(R=500,t=1) 也应当只在第 3 个点成立
    for (let i = 0; i < 3; i += 1) {
      expect(Boolean(flags[i] & FLAG.SMALL)).toBe(Boolean(isoFlags[i] & FLAG.ISO_500));
    }
  });

  /**
   * 格边长取 R/4(R=1000 时约 250m),所以半径内的邻居会落在**斜对角的格子**里 ——
   * 扫描跨度算少一格,这批邻居就数不到,表现为「明明挨着,却判成了小热点」。
   * 这里所有点两两相距 ≤ 800m,任何一对都在 1000m 半径内,谁漏一格都会让计数掉下来。
   */
  it('半径跨格子也不漏点:格边长取 R/4,斜对角格子里的邻居必须数到', () => {
    const ring: Array<{ dx: number; dy: number }> = [{ dx: 0, dy: 0 }];
    for (let k = 0; k < 8; k += 1) {
      const a = (k / 8) * Math.PI * 2;
      ring.push({ dx: Math.round(400 * Math.cos(a)), dy: Math.round(400 * Math.sin(a)) });
    }
    // 九个点两两相距 ≤ 800m < 1000m,每个点都应当数到 9 起
    expect(build(ring, { radiusM: 1000, threshold: 8 }).count).toBe(0);
    expect(build(ring, { radiusM: 1000, threshold: 9 }).count).toBe(9);
  });

  it('南北相距 900m 的两点互为邻居(跨纬度格子)', () => {
    const pair = [
      { dx: 0, dy: 0 },
      { dx: 0, dy: 900 },
    ];
    // 各自数到 2 起:阈值 1 不命中、阈值 2 命中 —— 少扫一格就会变成各 1 起、阈值 1 就命中
    expect(build(pair, { radiusM: 1000, threshold: 1 }).count).toBe(0);
    expect(build(pair, { radiusM: 1000, threshold: 2 }).count).toBe(2);
  });

  it('阈值 0 关闭这一类,且清掉上一轮留下的标记', () => {
    const once = build(CLUSTERED, { threshold: 10 });
    expect(once.count).toBe(4);
    const off = build(CLUSTERED, { threshold: 0, flags: once.flags });
    expect(off.count).toBe(0);
    expect([...off.flags].every((f) => (f & FLAG.SMALL) === 0)).toBe(true);
  });

  it('幂等:改半径后重算,不会把上一轮的标记累积下来', () => {
    const flags = new Uint16Array(CLUSTERED.length);
    const first = build(CLUSTERED, { radiusM: 2000, threshold: 4, flags });
    const once = Uint16Array.from(flags);
    build(CLUSTERED, { radiusM: 2000, threshold: 4, flags });
    expect([...flags]).toEqual([...once]);
    expect(first.count).toBeGreaterThan(0);
  });

  it('不覆盖已有的其它类别位', () => {
    const flags = new Uint16Array(CLUSTERED.length);
    flags[0] = FLAG.MISSING;
    flags[3] = FLAG.OUTSIDE | FLAG.SPARSE;
    build(CLUSTERED, { threshold: 10, flags });
    expect(flags[0] & FLAG.MISSING).not.toBe(0);
    expect(flags[3] & FLAG.OUTSIDE).not.toBe(0);
    expect(flags[3] & FLAG.SPARSE).not.toBe(0);
  });

  it('样例念出半径与本批次起数', () => {
    const out = build(CLUSTERED, { radiusM: 1000, threshold: 10 });
    expect(out.samples.length).toBeGreaterThan(0);
    expect(out.samples[0]?.note).toMatch(/^半径 1000m 内本批次共 \d+ 起$/);
  });

  it('默认常量:半径 1000m / 阈值 10(与导入弹窗的初值同源)', () => {
    expect(SMALL_DEFAULT_RADIUS_M).toBe(1000);
    expect(SMALL_DEFAULT_THRESHOLD).toBe(10);
  });

  it('第 9 位不被截断:flags 必须是 Uint16Array', () => {
    const flags = new Uint16Array(1);
    flags[0] = FLAG.SMALL;
    expect(flags[0]).toBe(1 << 8);
    expect(flags[0] & FLAG.SMALL).not.toBe(0);
  });
});

describe('剔除执行', () => {
  const n = 10;
  const mk = () => {
    const lng = new Int32Array(n);
    const lat = new Int32Array(n);
    for (let i = 0; i < n; i += 1) {
      lng[i] = i;
      lat[i] = i * 2;
    }
    const columns = {
      n,
      lng: lng.buffer as ArrayBuffer,
      lat: lat.buffer as ArrayBuffer,
      ts: new Uint32Array(n).fill(1).buffer as ArrayBuffer,
      d: new Uint8Array(n).buffer as ArrayBuffer,
      s: new Uint16Array(n).buffer as ArrayBuffer,
      r: new Uint16Array(n).buffer as ArrayBuffer,
      u: new Uint16Array(n).buffer as ArrayBuffer,
      ne: new Uint16Array(n).buffer as ArrayBuffer,
      v: new Uint16Array(n).buffer as ArrayBuffer,
      // 营运区分 + 细分依据列:值取 i % 7(覆盖全部七档),剔除后要能按留下来的行原样读到
      op: Uint16Array.from({ length: n }, (_, i) => i % 7).buffer as ArrayBuffer,
      on: Uint16Array.from({ length: n }, (_, i) => i % 3).buffer as ArrayBuffer,
      vk: Uint16Array.from({ length: n }, (_, i) => i % 5).buffer as ArrayBuffer,
      vs: Uint16Array.from({ length: n }, (_, i) => i % 4).buffer as ArrayBuffer,
      cs: Uint16Array.from({ length: n }, (_, i) => i % 6).buffer as ArrayBuffer,
      vm: Uint16Array.from({ length: n }, (_, i) => i % 9).buffer as ArrayBuffer,
    };
    const detail = {
      n,
      caseNo: Array.from({ length: n }, (_, i) => `NO${i}`),
      a: new Uint16Array(n).buffer as ArrayBuffer,
    };
    return { columns, detail };
  };

  it('掩码为 0 时原样返回,不做无谓拷贝', () => {
    const { columns, detail } = mk();
    const res = applyExclusions(columns, detail, new Uint16Array(n), 0);
    expect(res.removed).toBe(0);
    expect(res.columns).toBe(columns);
  });

  it('剔除数与剩余数守恒,且剩下的行保持原顺序', () => {
    const { columns, detail } = mk();
    const flags = new Uint16Array(n);
    flags[2] = FLAG.MISSING;
    flags[5] = FLAG.OUTSIDE;
    const res = applyExclusions(columns, detail, flags, FLAG.MISSING | FLAG.OUTSIDE);
    expect(res.removed).toBe(2);
    expect(res.columns.n + res.removed).toBe(n);
    expect(res.detail.caseNo).toEqual(['NO0', 'NO1', 'NO3', 'NO4', 'NO6', 'NO7', 'NO8', 'NO9']);
    const outLng = new Int32Array(res.columns.lng);
    expect(Array.from(outLng)).toEqual([0, 1, 3, 4, 6, 7, 8, 9]);
    const outLat = new Int32Array(res.columns.lat);
    expect(Array.from(outLat)).toEqual([0, 2, 6, 8, 12, 14, 16, 18]);
  });

  /**
   * 回归:剔除会重建列,漏掉的那一列不会报错、只会整列变「未填」。
   *
   * 营运区分就这么丢过一次 —— 解析时算得出 5,173 辆营运车,导入人勾了清洗类别之后
   * 这一列没跟着重建,Worker 拿到的全是 0,界面上营运与非营运双双为 0、外圈一档不剩。
   * 这类错误在数据层完全无声,只能靠这条断言钉住。
   */
  it('剔除后营运区分与细分依据列都在,值跟着留下来的行走', () => {
    const { columns, detail } = mk();
    const flags = new Uint16Array(n);
    flags[2] = FLAG.MISSING;
    flags[5] = FLAG.OUTSIDE;
    const res = applyExclusions(columns, detail, flags, FLAG.MISSING | FLAG.OUTSIDE);
    const kept = [0, 1, 3, 4, 6, 7, 8, 9];
    for (const key of ['op', 'on', 'vk', 'vs', 'cs', 'vm'] as const) {
      const out = res.columns[key];
      expect(out, `${key} 列在剔除后必须还在`).toBeTruthy();
      expect(Array.from(new Uint16Array(out as ArrayBuffer))).toEqual(
        kept.map((i) => new Uint16Array(columns[key] as ArrayBuffer)[i]),
      );
    }
    // 顺带确认营运区分不是「全 0」—— 全 0 就是整维变未填的那个样子
    expect(new Uint16Array(res.columns.op as ArrayBuffer).some((v) => v > 0)).toBe(true);
  });

  it('一条命中多类时,只勾其中一类也会剔掉(类是「任一」关系)', () => {
    const { columns, detail } = mk();
    const flags = new Uint16Array(n);
    flags[3] = FLAG.MISSING | FLAG.OUTSIDE;
    expect(applyExclusions(columns, detail, flags, FLAG.OUTSIDE).removed).toBe(1);
    expect(applyExclusions(columns, detail, flags, FLAG.MISSING).removed).toBe(1);
  });

  it('掩码按类别 key 拼出来', () => {
    const keys: CleanClassKey[] = ['MISSING', 'OUTSIDE'];
    expect(maskOfKeys(keys)).toBe(FLAG.MISSING | FLAG.OUTSIDE);
    expect(maskOfKeys([])).toBe(0);
  });
});

/** 6 行里后两行带 MISSING:对应上面「剔掉乙区那两条」 */
function missingFlags(): Uint16Array {
  const f = new Uint16Array(6);
  f[4] = FLAG.MISSING;
  f[5] = FLAG.MISSING;
  return f;
}

describe('剔除后的账目', () => {
  it('count 与 rejected 一起变,且分区起数与外包框按剩余点重算', () => {
    // 原始 6 条:前 4 条在甲区,后 2 条在乙区;剔掉乙区那两条之后只剩 4 条
    const meta = {
      count: 6,
      rejected: 2,
      rejectedReasons: {},
      coordScale: COORD_SCALE,
      dict: { districts: ['甲区', '乙区'], streets: [], addrDetails: [], roads: [] },
      districtCounts: { 甲区: 4, 乙区: 2 },
      bounds: { minLng: 0, maxLng: 5, minLat: 0, maxLat: 5 },
      center: { lng: 2.5, lat: 2.5 },
    } as unknown as MetaFile;
    const classes: CleanClass[] = [
      {
        key: 'MISSING',
        label: '字段缺失',
        reason: '三列都取不到',
        count: 2,
        fixed: true,
        defaultOn: true,
        samples: [],
      },
    ];
    const kept: IncidentColumns = {
      n: 4,
      lng: new Int32Array([0, 1000, 2000, 3000]).buffer as ArrayBuffer,
      lat: new Int32Array([0, 1000, 2000, 3000]).buffer as ArrayBuffer,
      ts: new Uint32Array(4).fill(1).buffer as ArrayBuffer,
      d: new Uint8Array([0, 0, 0, 0]).buffer as ArrayBuffer,
      s: new Uint16Array(4).buffer as ArrayBuffer,
      r: new Uint16Array(4).buffer as ArrayBuffer,
      u: new Uint16Array(4).buffer as ArrayBuffer,
      ne: new Uint16Array(4).buffer as ArrayBuffer,
      v: new Uint16Array(4).buffer as ArrayBuffer,
    };

    reconcileMeta(meta, classes, new Set<CleanClassKey>(['MISSING']), kept, missingFlags());

    // 原始 8 = 入库 4 + 拒收 4(原有 2 + 本次剔除 2)
    expect(meta.count).toBe(4);
    expect(meta.rejected).toBe(4);
    expect(meta.count + meta.rejected).toBe(8);
    // 分区起数按剩余 4 条重算:乙区那两条已被剔掉,不该再出现在榜上
    expect(meta.districtCounts).toEqual({ 甲区: 4 });
    // 外包框也按剩余点重算(原来被乙区那条撑到 5,现在收到 3)
    expect(meta.bounds.maxLng).toBeCloseTo(0.003, 6);
    expect(meta.rejectedReasons['清洗剔除 · 字段缺失']).toBe(2);
  });

  /**
   * 一行命中多类时,明细各项之和必须等于实际剔除数。
   *
   * 旧实现拿各类的 count 相加(MISSING 2 + OUTSIDE 1 = 3),而 meta.rejected 记的是
   * 按位去重后的真实行数(2)—— 拒收明细比总数多一条,账目当场就不平了。
   * 真实数据里这种重叠很常见:地址写着外市的那条往往也读不出道路名。
   */
  it('一行命中多类时,明细各项之和 = 实际剔除数', () => {
    const meta = {
      count: 3,
      rejected: 0,
      rejectedReasons: {},
      coordScale: COORD_SCALE,
      dict: { districts: ['甲区'], streets: [], addrDetails: [], roads: [] },
      districtCounts: { 甲区: 3 },
      bounds: { minLng: 0, maxLng: 5, minLat: 0, maxLat: 5 },
      center: { lng: 2.5, lat: 2.5 },
    } as unknown as MetaFile;
    const classes = [
      { key: 'MISSING', label: '三项都读不出', reason: '', count: 2, fixed: false, defaultOn: true, samples: [] },
      { key: 'OUTSIDE', label: '邻市(地址写明外市)', reason: '', count: 1, fixed: false, defaultOn: true, samples: [] },
    ] as CleanClass[];
    const flags = new Uint16Array([FLAG.MISSING | FLAG.OUTSIDE, FLAG.MISSING, 0]);
    const kept: IncidentColumns = {
      n: 1,
      lng: new Int32Array([0]).buffer as ArrayBuffer,
      lat: new Int32Array([0]).buffer as ArrayBuffer,
      ts: new Uint32Array(1).fill(1).buffer as ArrayBuffer,
      d: new Uint8Array([0]).buffer as ArrayBuffer,
      s: new Uint16Array(1).buffer as ArrayBuffer,
      r: new Uint16Array(1).buffer as ArrayBuffer,
      u: new Uint16Array(1).buffer as ArrayBuffer,
      ne: new Uint16Array(1).buffer as ArrayBuffer,
      v: new Uint16Array(1).buffer as ArrayBuffer,
    };

    reconcileMeta(meta, classes, new Set<CleanClassKey>(['MISSING', 'OUTSIDE']), kept, flags);

    const removed = 3 - kept.n;
    expect(meta.rejected).toBe(removed);
    // 第一行同时命中两类,只记一次、归到排在最前的那一类(与导出的 CSV 同一口径)
    expect(meta.rejectedReasons['清洗剔除 · 三项都读不出']).toBe(2);
    expect(meta.rejectedReasons['清洗剔除 · 邻市(地址写明外市)']).toBeUndefined();
    const sum = Object.values(meta.rejectedReasons).reduce((a, b) => a + b, 0);
    expect(sum).toBe(removed);
  });
});