Commit 73e5da1e by liimin

继续优化

1 parent a2e2c5df
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AggregateClient } from './aggregateClient';
/**
* Worker 初始化的 Promise 必须**总会结算**。
*
* init 失败时页面停在「正在识别」、控制台没有错,最常见的根因就是这一条:
* `postInit` 造出来的 Promise 只记了 resolve,Worker 回 error 或在 ready 之前被 dispose
* 时调用方的 await 永久 pending,useBootstrap 的 catch 永远进不去。
*/
class FakeWorker {
onmessage: ((e: MessageEvent) => void) | null = null;
onerror: ((e: ErrorEvent) => void) | null = null;
private listeners = new Set<(e: MessageEvent) => void>();
terminated = false;
constructor(readonly behavior: 'ready' | 'error' | 'silent') {}
addEventListener(type: string, fn: (e: MessageEvent) => void) {
if (type === 'message') this.listeners.add(fn);
}
removeEventListener(type: string, fn: (e: MessageEvent) => void) {
if (type === 'message') this.listeners.delete(fn);
}
postMessage() {
const data =
this.behavior === 'ready'
? { type: 'ready' }
: this.behavior === 'error'
? { type: 'error', message: 'init 阶段炸了' }
: null;
if (!data) return;
const event = { data } as MessageEvent;
this.onmessage?.(event);
for (const fn of this.listeners) fn(event);
}
terminate() {
this.terminated = true;
}
}
/** 不构造 MetaFile / IncidentsFile 全量字段:postInit 只透传它们,这里只给够读取的部分 */
type InitLike = (meta: unknown, columns: unknown, key: string) => Promise<void>;
function init(client: AggregateClient): Promise<void> {
return (client as unknown as { initFromColumns: InitLike }).initFromColumns(
{ dict: {}, grid: {}, bounds: {}, timeRange: {}, coordScale: 1e6 },
{ lng: new ArrayBuffer(4) },
'dataset-test',
);
}
/** 超时兜底:Promise 没结算时让用例明确报「挂起」,而不是整个测试文件卡住 */
function withDeadline(p: Promise<void>): Promise<void> {
return Promise.race([
p,
new Promise<void>((_, reject) => {
const t = setTimeout(() => reject(new Error('TIMEOUT: init Promise 永久挂起')), 200);
t.unref?.();
}),
]);
}
let workers: FakeWorker[] = [];
beforeEach(() => {
workers = [];
const g = globalThis as Record<string, unknown>;
vi.stubGlobal(
'Worker',
class {
constructor() {
const w = new FakeWorker((g as { __behavior?: FakeWorker['behavior'] }).__behavior ?? 'ready');
workers.push(w);
return w;
}
},
);
});
afterEach(() => {
vi.unstubAllGlobals();
delete (globalThis as { __behavior?: string }).__behavior;
});
function behavior(b: FakeWorker['behavior']) {
(globalThis as { __behavior?: FakeWorker['behavior'] }).__behavior = b;
}
describe('聚合 Worker · init Promise 结算', () => {
it('Worker 回 ready 时正常 resolve', async () => {
behavior('ready');
await expect(withDeadline(init(new AggregateClient()))).resolves.toBeUndefined();
});
it('init 阶段 Worker 回 error 时 reject,而不是永久挂起', async () => {
behavior('error');
await expect(withDeadline(init(new AggregateClient()))).rejects.toThrow('init 阶段炸了');
});
it('ready 之前 dispose 时 reject,而不是永久挂起', async () => {
behavior('silent');
const client = new AggregateClient();
const pending = init(client);
client.dispose();
await expect(withDeadline(pending)).rejects.toThrow('数据集已切换');
expect(workers[0].terminated).toBe(true);
});
});
......@@ -70,7 +70,7 @@ type SpotlightResolver = {
reject: (e: Error) => void;
};
class AggregateClient {
export class AggregateClient {
private worker: Worker | null = null;
private seq = 0;
private aggPending = new Map<number, Resolver>();
......@@ -82,6 +82,14 @@ class AggregateClient {
private spotlightPending = new Map<number, SpotlightResolver>();
private centersPending = new Map<number, CentersResolver>();
private ready: Promise<void> | null = null;
/**
* init 那个 Promise 的 reject。只到 ready / 失败 / 销毁为止有效。
*
* 没有这一条时,Worker 在 init 阶段回 error、或 ready 之前被 dispose,
* `await initFromColumns()` 会永久 pending:useBootstrap 的 catch 永远不进,
* 页面停在加载态,控制台一行错都没有。
*/
private readyReject: ((e: Error) => void) | null = null;
private detailReady = false;
/**
* 主线程侧记录的「期望点数」:init 时按 lng 的字节数算出(与 Worker 侧 handleInit 同款算法),
......@@ -266,6 +274,7 @@ class AggregateClient {
*
* 清掉这四个字段后,下一次调用会走下面的重建分支(多付一次 init 的几十毫秒)。
*/
this.failReady(new Error(`聚合 Worker 异常:${e.message}`));
this.rejectAll(new Error(`聚合 Worker 异常:${e.message}`));
this.worker?.terminate();
this.worker = null;
......@@ -288,10 +297,20 @@ class AggregateClient {
};
this.ready = new Promise<void>((resolve, reject) => {
this.readyReject = reject;
const onReady = (e: MessageEvent<WorkerResponse>) => {
if (e.data.type === 'ready') {
this.readyReject = null;
this.worker?.removeEventListener('message', onReady);
resolve();
return;
}
// init 阶段的协议错误没有 reqId(Worker 侧 fail(message, undefined))。
// onMessage 的 rejectAll 那时 pending 表还是空的,只有这里能把 init 结掉。
if (e.data.type === 'error' && e.data.reqId === undefined) {
this.readyReject = null;
this.worker?.removeEventListener('message', onReady);
reject(new Error(e.data.message));
}
};
this.worker?.addEventListener('message', onReady);
......@@ -299,6 +318,8 @@ class AggregateClient {
// 转移 ArrayBuffer:转移后主线程侧的视图失效,数据只存在于 Worker
this.worker?.postMessage(msg, transfer);
} catch (err) {
this.readyReject = null;
this.worker?.removeEventListener('message', onReady);
reject(err instanceof Error ? err : new Error(String(err)));
}
});
......@@ -535,6 +556,9 @@ class AggregateClient {
* 没有 reqId 才是协议破损(谁都不知道该记在谁头上),那时才全拒。
*/
if (msg.reqId === undefined) {
// 没有 reqId 的 error 可能是 init 阶段发来的:那时 pending 表还是空的,
// rejectAll 不会碰到 init 的那个 Promise,必须单独结掉它。
this.failReady(new Error(msg.message));
this.rejectAll(new Error(msg.message));
} else {
this.rejectOne(msg.reqId, new Error(msg.message));
......@@ -566,6 +590,13 @@ class AggregateClient {
}
}
/** ready 还没结算时把它拒掉;已 resolve / 已拒过就什么都不做 */
private failReady(err: Error): void {
const reject = this.readyReject;
this.readyReject = null;
reject?.(err);
}
private rejectAll(err: Error) {
for (const p of this.aggPending.values()) p.reject(err);
for (const p of this.rawPointsPending.values()) p.reject(err);
......@@ -593,6 +624,9 @@ class AggregateClient {
* 比报个错更难看出发生了什么。
*/
dispose() {
// ready 还没回来就要销毁时,init 的 await 也必须在这一刻结算;
// 否则页面会一直停在「正在识别」,而 Worker 早就不存在了。
this.failReady(new Error('数据集已切换,本次请求作废'));
if (this.worker) {
this.rejectAll(new Error('数据集已切换,本次请求作废'));
this.worker.terminate();
......
import { describe, expect, it } from 'vitest';
import { analyze, effectiveMinCount, gridBoxSource, type AnalysisInput } from './hotspotAnalysis';
import { analyze, effectiveMinCount, gaussianSmooth, gridBoxSource, type AnalysisInput } from './hotspotAnalysis';
import type { AnalysisParams, HotspotRow, HotspotSort } from './types';
/**
......@@ -581,3 +581,37 @@ describe('effectiveMinCount · 按口径占比折算', () => {
expect(effectiveMinCount(5, 42_800, 42_803)).toBe(5);
});
});
/**
* 边界兜底的两个漏洞(2026-11-27 黑点降噪排查)。
*
* 前两条都是「兜底写了但兜不住」:normalizeParams 的 cell 加到 400 就停手,
* 于是超出 MAX_CELLS 后照样建超大数组;resolveGridBox 的兜底框 padding 用度数写死
* 1e-6(约 0.1 米),远小于一格(100 米),命中点挤在十几米内时仍退化成 1×1 栅格。
* 第三条是导出函数的零 σ 除零(主链路 normalizeParams 保证 σ≥1,但导出函数不能假设)。
*/
describe('边界兜底 · 探针', () => {
it('大范围时 cell 必须继续放大,真把栅格压到 MAX_CELLS 以内', () => {
// 约 580km × 580km:cell=100 时 3.4e7 格,cell=400 时仍略超 2e6 格。
const m = make(4, (_i, rnd) => [113.1 + rnd() * 0.01, 20.1 + rnd() * 0.01]);
const res = analyze({
...m,
bounds: { minLng: 113, maxLng: 118.6, minLat: 20, maxLat: 25.24 },
});
expect(res.grid.w * res.grid.h).toBeLessThanOrEqual(2_000_000);
expect(res.cellMeters).toBeGreaterThan(400);
});
it('命中点挤在十几米内且边界失效时,兜底框不能退化成 1 格', () => {
const m = make(120, (_i, rnd) => [114 + rnd() * 0.00008, 22.5 + rnd() * 0.00008]);
const res = analyze({ ...m, bounds: { minLng: 0, maxLng: 0, minLat: 0, maxLat: 0 } });
expect(res.gridSource).toBe('points-fallback');
expect(res.grid.w * res.grid.h).toBeGreaterThan(1);
expect(res.occupiedCells).toBeGreaterThan(1);
});
it('gaussianSmooth 的 σ=0 不能吐出 NaN', () => {
const out = gaussianSmooth(new Int32Array(9).fill(1), 3, 3, 0);
for (const v of out) expect(Number.isFinite(v)).toBe(true);
});
});
......@@ -232,10 +232,18 @@ function resolveGridBox(input: AnalysisInput): {
if (covers) return { box: b, source: 'bounds' };
}
// 全部点重在一处时也要给一个非退化框:让「一片都没形成」由连通域与门槛去判,
// 而不是靠 1 格栅格凑出来
const padLng2 = Math.max((maxLng - minLng) * 0.02, MIN_BOX_SPAN);
const padLat2 = Math.max((maxLat - minLat) * 0.02, MIN_BOX_SPAN);
// 兜底框要跨过几个格子。原先这里拿 MIN_BOX_SPAN(1e-6°,约 0.1 米)当 padding,
// 它只是「框是否有效」的门槛,不是「框该多大」的尺度:命中点挤在十几米内时框总宽
// 仍远小于一格(100 米),全落进同一格 → occupied=1 → 留一法没有「其余地区」可比
// → z 恒 0 → 一个黑点都不产,界面却说「分布较为均匀」。按本次 cell 折算成度,
// 保证兜底框至少跨四格,让密集簇落到不同格子里由连通域与门槛去判。
const minCellM = Math.max(30, input.params.cellMeters || 100);
const fallbackLat = (minLat + maxLat) / 2;
const minSpanLatDeg = (minCellM * 4) / M_PER_DEG_LAT;
const minSpanLngDeg =
(minCellM * 4) / (M_PER_DEG_EQ * Math.cos((fallbackLat * Math.PI) / 180));
const padLng2 = Math.max((maxLng - minLng) * 0.02, minSpanLngDeg / 2);
const padLat2 = Math.max((maxLat - minLat) * 0.02, minSpanLatDeg / 2);
return {
box: {
minLng: minLng - padLng2,
......@@ -826,8 +834,13 @@ function normalizeParams(
const spanLngM = (bounds.maxLng - bounds.minLng) * mPerDegLng;
const spanLatM = (bounds.maxLat - bounds.minLat) * M_PER_DEG_LAT;
let cell = Math.min(400, Math.max(30, p.cellMeters || 100));
while ((spanLngM / cell) * (spanLatM / cell) > MAX_CELLS && cell < 400) cell += 10;
let cell = Math.max(30, p.cellMeters || 100);
// 400 不是终点:范围本身很大时,加到 400 仍会超过 MAX_CELLS,
// 原来的 `&& cell < 400` 会把兜底提前掐断,照样建几百万格的数组。
// 过 400 后改按 25% 指数放大,几步收敛,不会在超大框上做上百次循环。
while ((spanLngM / cell) * (spanLatM / cell) > MAX_CELLS) {
cell = cell < 400 ? cell + 10 : Math.ceil(cell * 1.25);
}
return {
cellMeters: cell,
......
......@@ -16,13 +16,16 @@ import type { HotspotRow } from '../aggregate/types';
interface FakeCtx {
calls: Map<string, number>;
/** 关键落笔的先后顺序:erase(destination-out 的 fill)与 text(盘心数字 / 排名牌文字) */
seq: string[];
[key: string]: unknown;
}
function fakeCtx(): FakeCtx {
const calls = new Map<string, number>();
const seq: string[] = [];
const hit = (name: string) => calls.set(name, (calls.get(name) ?? 0) + 1);
const ctx: FakeCtx = { calls };
const ctx: FakeCtx = { calls, seq };
for (const name of [
'setTransform',
'clearRect',
......@@ -44,6 +47,10 @@ function fakeCtx(): FakeCtx {
'translate',
'setLineDash',
'clip',
// jsdom 里 Path2D 是否存在随版本而变:两条命中路径都给个默认「不命中」,
// 免得探针测试在不同 jsdom 版本上走的分支不一样。
'isPointInPath',
'isPointInStroke',
]) {
ctx[name] = () => hit(name);
}
......@@ -54,7 +61,16 @@ function fakeCtx(): FakeCtx {
*/
ctx.fill = () => {
hit('fill');
if (ctx.globalCompositeOperation === 'destination-out') hit('erase');
if (ctx.globalCompositeOperation === 'destination-out') {
hit('erase');
seq.push('erase');
} else {
seq.push('fill');
}
};
ctx.fillText = () => {
hit('fillText');
seq.push('text');
};
return ctx;
}
......@@ -88,6 +104,7 @@ let restoreAmap: (() => void) | null = null;
beforeEach(() => {
ctx.calls.clear();
ctx.seq.length = 0;
FakeCustomLayer.created = [];
const proto = window.HTMLCanvasElement.prototype as unknown as { getContext: () => unknown };
const original = proto.getContext;
......@@ -190,6 +207,77 @@ describe('黑点图形 · 一片一条闭合轮廓', () => {
});
/**
* 2026-11-27 黑点降噪排查的两处命中漏洞。
*
* 第一处:画出来的排名牌与「画得见就点得着」对不上。牌心在轮廓外 effR+11 处,
* 而脚印模式的命中只认轮廓路径 + 4px 描边;等效圆退回模式却专门给了 22px 余量和
* 盘心 20px。同一个层、同一个视觉元素,两种模式的可点范围差一截。
* 第二处:setData 之后、下一帧 paint 之前,逐格矩形缓存还是全 0 —— 点屏幕左上角
* 会被误判成「命中了第 0 片黑点」,而真正的黑点此时一个都点不中。
*/
describe('黑点命中 · 画得见就点得着', () => {
it('排名牌的中心落在这一片的可点范围内', () => {
const layer = new HotspotLayer(fakeMap() as unknown as import('./provider/types').Basemap);
const { mask, row } = squareDomain();
layer.setData([row], GRID, mask);
FakeCustomLayer.created[0]?.render?.();
// 牌心公式:cx + cw/2 = x + off、cy + ch/2 = y - off,off = (effR+11)*0.7071。
// 从上一帧投影好的轮廓顶点反推 effR(不依赖命中实现新增的字段,免得测试自证)。
const internals = layer as unknown as { prepared: Array<{ screen: Float32Array[] }> };
const screen = internals.prepared[0].screen!;
let effR = 0;
for (const ring of screen) {
for (let k = 0; k < ring.length; k += 2) {
effR = Math.max(effR, Math.hypot(ring[k] - VIEW.w / 2, ring[k + 1] - VIEW.h / 2));
}
}
const off = (effR + 11) * 0.7071;
expect(layer.hitAt(VIEW.w / 2 + off, VIEW.h / 2 - off)).toBe(0);
layer.destroy();
});
it('喂完数据还没出帧时,屏幕左上角不能被误判成黑点', () => {
const layer = new HotspotLayer(fakeMap() as unknown as import('./provider/types').Basemap);
const { mask, row } = squareDomain();
layer.setData([row], GRID, mask);
// 刻意不 render:这一拍内 rects / sx / sy 还是刚分配的全 0
expect(layer.hitAt(0, 0)).toBe(-1);
layer.destroy();
});
});
/**
* 光雾的 destination-out 是按整条轮廓擦的,而同层所有黑点共用一张画布。
* 逐片「画完一整片再画下一片」时,后一片的擦会把先一片的主边、填充、盘心数字
* 与排名牌一起擦掉(两片脚印在屏幕上重叠时必现)。
* 修法是两遍画:所有擦先做完,再做所有最终落笔。
*/
describe('黑点光雾 · 擦除与落笔分两遍', () => {
it('所有片的擦都在任何盘心数字 / 排名牌之前', () => {
const layer = new HotspotLayer(fakeMap() as unknown as import('./provider/types').Basemap);
const mask = new Uint8Array(GRID.w * GRID.h);
for (let y = 0; y < 4; y += 1) {
for (let x = 0; x < 4; x += 1) mask[y * GRID.w + x] = 1;
}
for (let y = 20; y < 24; y += 1) {
for (let x = 20; x < 24; x += 1) mask[y * GRID.w + x] = 1;
}
const { row } = squareDomain();
const second = { ...row, id: 1, domainId: 2, lng: 114.0215, lat: 22.5215 } as HotspotRow;
layer.setData([row, second], GRID, mask);
FakeCustomLayer.created[0]?.render?.();
const lastErase = ctx.seq.lastIndexOf('erase');
const firstText = ctx.seq.indexOf('text');
expect(lastErase).toBeGreaterThan(-1);
expect(firstText).toBeGreaterThan(-1);
expect(lastErase).toBeLessThan(firstText);
layer.destroy();
});
});
/**
* 这两条守的是「炫」的那部分:外光雾 + 三明治描边,以及选中那一下不加戏。
*
* 它们都属于「画得好看」而不是「算得对」,没有数值可以断言,只能钉住笔数:
......
......@@ -57,7 +57,10 @@ export function runAnalysis(session: HeatmapSession): void {
// —— 检测①:筛选是否就绪(时间窗合法)——
// 非法窗(from>to)通常是筛选条件还没对齐就被触发,跳过本次,等 filter 对齐后下一拍自然重算。
if (f.from > f.to) {
// 筛选还没对齐就被触发:先熄灭绿灯,跳过本次,等 filter 对齐后下一拍自然重算
// 筛选还没对齐就被触发:先熄灭绿灯,跳过本次,等 filter 对齐后下一拍自然重算。
// 必须同时作废在飞的 token:否则先前那一份按旧筛选算出的结果稍后回包时
// token 仍相等,会把「未就绪」重新点亮成绿灯,界面念的是旧口径的黑点。
session.analysisToken += 1;
st.setDataReady(false);
console.warn('[analysis] 跳过:筛选未就绪(时间窗 %d~%d),250ms 后重试', f.from, f.to);
if (pass === 0) setTimeout(() => void runAnalysis(session), 250);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!