Files

104 lines
6.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict'
// 任务缓存契约:`cachedGenerationTasks` 的引用稳定快路径 + 有界缓存 + 图指纹。
//
// ── 2026-10-28 更新(P1 拆分批 1)──────────────────────────────────────────────
// `graphCacheKey` 已从 app.js 迁到 `src/generation-task-graph.js`(连同它的 `_graphKeyMemo` 缓存)。
// 本测试**没有删掉那条断言,而是把它改指向新模块** —— 保护语义完全不变:
// 「图指纹必须带引用稳定快路径缓存,且按 (nodes 引用, edges 引用) 命中」。
// 并且升级为**行为验证**:直接调用新模块,断言"同引用命中、异引用重算"真的成立,
// 比原来的源码文本存在断言更强。
//
// 仍在 app.js 里的部分(cachedGenerationTasks / taskParseCache)继续用源码断言 ——
// 它们尚未迁出,且是"缓存有界"这类难以行为化的结构性契约。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const appSource = fs.readFileSync(path.join(root, 'app.js'), 'utf8')
const taskGraphSource = fs.readFileSync(path.join(root, 'src', 'generation-task-graph.js'), 'utf8')
// ── 1. cachedGenerationTasks 仍在 app.js(尚未迁出,继续用源码断言)───────────
assert.ok(appSource.includes('const taskParseCache = new WeakMap()'),
'cachedGenerationTasks 应使用 WeakMap 作为任务解析缓存(按 nodes 数组引用分桶)')
assert.ok(appSource.includes('function cachedGenerationTasks(genNode, nodesArr, edgesArr)'),
'cachedGenerationTasks 定义应存在于 app.js')
assert.ok(appSource.includes('bucket.set(cacheKey, result)'),
'缓存写入应发生(否则等于每次重算)')
assert.ok(appSource.includes('if (bucket.size > 8)'),
'单张图的任务缓存桶应有上界(> 8 时淘汰最旧),防内存无界增长')
// ── 2. graphCacheKey 已迁到 src/generation-task-graph.js ⇒ 断言改指向新模块 ──────────────
assert.ok(taskGraphSource.includes('function graphCacheKey(nodesArr, edgesArr)'),
'graphCacheKey 应定义在 src/generation-task-graph.js(P1 拆分批 1 已迁出 app.js)')
assert.ok(taskGraphSource.includes('_graphKeyMemo'),
'graphCacheKey 必须保留引用稳定快路径缓存 _graphKeyMemo(否则大画布每次重渲染都 O(n) 重算)')
// ── 3. 行为验证:引用稳定快路径真的生效 ──────────────────────────────────────
// 这是本测试真正的价值 —— 证明"同引用直接命中缓存、异引用重算",而不只是"源码里有这行字"。
const { JSDOM } = require('jsdom')
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', { url: 'http://localhost:8787/', runScripts: 'dangerously' })
const { window } = dom
window.eval(fs.readFileSync(path.join(root, 'src', 'canvas-text.js'), 'utf8'))
window.eval(taskGraphSource)
// 供 graphCacheKey 用的最小依赖(它只用到数组判断 + JSON.stringify)
const TG = window.IWBWTaskGraph.create({
sortByPosition: (a) => a,
compareCanvasImageOrder: () => 0,
compareCanvasTextOrder: () => 0,
dedupeTaskRefs: (r) => r,
isBatchSrc: () => false,
batchJoinedText: () => '',
wDedupeTaskIds: (x) => x,
refArgsOf: () => [],
// P1 拆分批 4(2026-10-28):模块新增 2 个注入(本测试只用到 graphCacheKey,给最小实现即可)
batchSrcText: () => '',
standardSizeOf: () => '1024x1024',
})
const nodesA = [{ id: 'a', type: 'prompt', x: 0, y: 0, data: { text: 'x' } }]
const edgesA = [{ id: 'e', from: 'a', to: 'b' }]
const key1 = TG.graphCacheKey(nodesA, edgesA)
const key2 = TG.graphCacheKey(nodesA, edgesA)
assert.strictEqual(key1, key2, '同一组数组引用应返回同一个图指纹(引用稳定快路径)')
// 引用稳定快路径的**真实价值是性能**(避免每次重渲染都 O(n) 重算 JSON.stringify)——
// 所以用「命中次数」而不是「结果相等」来验证:同引用重复调用不应再走重算分支。
// 做法:用一个会记录调用次数的 Map 代理不可行(模块内部对象不可见),
// 改为**计时**比较:同一引用重复 200 次应显著快于每次换新引用。
{
const big = []
for (let i = 0; i < 300; i++) big.push({ id: 'n' + i, type: 'prompt', x: i, y: i, w: 10, h: 10, data: { text: 'x'.repeat(80) } })
const edgesBig = []
for (let i = 0; i < 200; i++) edgesBig.push({ id: 'e' + i, from: 'n' + i, to: 'n' + ((i + 1) % 300) })
// 预热
TG.graphCacheKey(big, edgesBig)
const t0 = Date.now()
for (let i = 0; i < 200; i++) TG.graphCacheKey(big, edgesBig) // 同引用 ⇒ 命中缓存
const cachedMs = Date.now() - t0
const t1 = Date.now()
for (let i = 0; i < 200; i++) TG.graphCacheKey(big.slice(), edgesBig.slice()) // 每次新引用 ⇒ 重算
const recomputeMs = Date.now() - t1
assert.ok(recomputedTookMore(recomputeMs, cachedMs),
'引用稳定快路径应显著快于每次重算(缓存 ' + cachedMs + 'ms vs 重算 ' + recomputeMs + 'ms)—— ' +
'若两者接近,说明 _graphKeyMemo 缓存失效了(大画布会退化为每次重渲染 O(n) 重算)')
}
function recomputedTookMore(recomputeMs, cachedMs) {
// 允许机器抖动;命中缓存至少要快 3 倍,或重算耗时本身已 > 5ms(可测规模)
if (recomputeMs < 5) return true // 太快测不准,放行(避免 flaky)
return cachedMs * 3 < recomputeMs
}
// 换新数组引用(内容已变)⇒ 必须重算。这是 CanvasStore 的不可变约定。
const nodesB = [{ id: 'a', type: 'prompt', x: 1, y: 0, data: { text: 'x' } }]
const key3 = TG.graphCacheKey(nodesB, edgesA)
assert.notStrictEqual(key3, key1, '换了新数组引用(内容已变)时必须重新计算图指纹,不得返回过期缓存')
// 空图也要能算
assert.strictEqual(typeof TG.graphCacheKey([], []), 'string', '空图也应返回字符串指纹')
console.log('task cache contract checks passed(含 graphCacheKey 引用稳定快路径的行为验证)')