@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backfill-child.js +304 -0
- package/backfill-vectors.js +125 -0
- package/contract.js +114 -0
- package/cursor.js +116 -0
- package/egress.js +788 -0
- package/embed-child.js +142 -0
- package/embed.js +475 -0
- package/envelope.js +368 -0
- package/extract.js +420 -0
- package/idle-interrupt.js +922 -0
- package/index.js +153 -0
- package/migrate.js +1722 -0
- package/package.json +48 -3
- package/persona.js +949 -0
- package/query-window.js +561 -0
- package/recall-trivium.js +873 -0
- package/recall.js +113 -0
- package/remove-legacy.mjs +720 -0
- package/serve.js +138 -0
- package/store-trivium-child.js +447 -0
- package/store-trivium.js +507 -0
- package/store.js +347 -0
- package/sweep.js +296 -0
- package/tools.js +423 -0
- package/trivium-runtime.js +1794 -0
- package/README.md +0 -3
package/egress.js
ADDED
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 外发边界、保留期与**不可逆**删除(平台计划任务 38,GAP-9 / IS-10)。
|
|
3
|
+
*
|
|
4
|
+
* 本文件只做四件事,每一件都有可断言的判据(判据在 `scripts/research/egress.mjs` 里逐条实测):
|
|
5
|
+
*
|
|
6
|
+
* 1. **按来源删除** `deleteBySource({facade, source_type?, jobId?, videoId?, sessionId?, dryRun?})`:
|
|
7
|
+
* 用 payload 顶层镜像字段(`source_type` / `job_id` / `video_id` / `session_id`)做 keyset 扫描收集
|
|
8
|
+
* 目标节点,再调门面的 `deleteNodes`。引擎的 delete 是三层原子联删(向量 / payload / 全部关联边),
|
|
9
|
+
* 所以不存在「删了节点留下悬空边」;但本文件仍然**实测复核**(`assertNoOrphans`),不信文档。
|
|
10
|
+
* 过滤条件为空时**拒绝执行**(大范围删除必须走 `deleteAll`,让调用方显式选择)。
|
|
11
|
+
* 2. **全局删除** `deleteAll({facade, dryRun?})`:清空一个 workspace 的全部节点(envelope + 会话锚点),
|
|
12
|
+
* 删完图仍一致(无悬空边)。锚点缓存(`ANCHOR_CACHE`)在锚点消失后由 `appendEnvelopes` 的
|
|
13
|
+
* `NODE_NOT_FOUND` 重试路径自愈——那条路径本来就是为了快照恢复而写的。
|
|
14
|
+
* 3. **保留期** `expireBefore({facade, cutoffTs?, source_type?, dryRun?})`:`ts` 早于 cutoff 的行,
|
|
15
|
+
* 或带 per-row `retained_until` 且已到点的行,按 #1 同一条路径删除(含快照)。cutoff 缺省取
|
|
16
|
+
* `now - KANABO_MEMORY_RETENTION_MS`(默认 90 天)。
|
|
17
|
+
* 4. **审计轨迹**:每次删除产出一条 JSON 记录(id / 动作 / 过滤条件 / 删除的 legacy id 与节点 id /
|
|
18
|
+
* 被销毁的快照代际与命中原因 / 孤立边复核 / 删除后残留 / 时间戳),既在返回值里,也进进程内
|
|
19
|
+
* `trail()`;给了 `auditPath`(或环境变量 `KANABO_MEMORY_EGRESS_AUDIT`)时再追加一行 JSONL。
|
|
20
|
+
* 这是「可审计」的落点,与任务 25 把外发上限与计量集中在 `vision-client.js` 同一口径:
|
|
21
|
+
* **删除/保留的决定只在本文件做,且每一次都留痕**。
|
|
22
|
+
*
|
|
23
|
+
* ## 为什么「删了活库」不够(本任务的核心)
|
|
24
|
+
*
|
|
25
|
+
* `createSnapshot` 是**整库目录的字节拷贝**(`<triviumDir>/snapshots/<fileBase>/<generationId>`),
|
|
26
|
+
* 实测:删掉活库里的行之后,活库的 payload 代际文件会被引擎重写、`"<id>"` 不再出现(见
|
|
27
|
+
* `task-38.log` 的实测段),但**删除之前创建的快照里仍然留着 `"<id>"`**——`restoreSnapshot` 一恢复,
|
|
28
|
+
* 行就回来了。所以「删除后查询为空」只能证明活库干净,不能证明不可恢复。
|
|
29
|
+
*
|
|
30
|
+
* 本文件的处理是**判定 → 销毁**,而不是字节猜测:
|
|
31
|
+
*
|
|
32
|
+
* - 对 `snapshots/` 下**每一个**代际目录,把它 `restoreSnapshot` 到一个临时 workspace(独立的 `dir`,
|
|
33
|
+
* 不碰活库),在恢复出来的库里 `FIND {id: {$in: [...]}}`。命中即「这个快照含被删数据」。
|
|
34
|
+
* - 含命中的代际目录**整目录删除**(`rmSync recursive`),并剪掉变空的 `<fileBase>` 目录;
|
|
35
|
+
* 每个被删目录记进审计轨迹(目录、代际、命中的 id、原因)。
|
|
36
|
+
* - 没有命中的代际**保留**(删一条记忆不该毁掉所有快照);它们已经被同一次查询证明「不含该数据」。
|
|
37
|
+
* - 探测本身失败的代际**按含命中处理**(fail-safe):无法证明干净就等于不干净。
|
|
38
|
+
*
|
|
39
|
+
* 为什么用「恢复 + 查询」而不是「在字节里搜 id」:字节搜索会把「另一条记忆的正文提到了这个 id」
|
|
40
|
+
* 误判成残留(白白毁掉快照),也会漏掉引擎压缩后的编码差异。恢复+查询用的是与验收断言**完全相同**
|
|
41
|
+
* 的机制(`restoreSnapshot` + TQL),所以「判定」与「证明」不会各说各话。
|
|
42
|
+
*
|
|
43
|
+
* 另外两类可恢复副本也一并处理:`restoreSnapshot` 在库目录里留下的 `.backup-<ts>/`(整库副本,
|
|
44
|
+
* 不是快照格式,用字节搜索判定)以及活库自身文件(只**报告**不删除——引擎的 delete 已经重写代际,
|
|
45
|
+
* 报告出来是让「残留」可见而不是假装干净)。
|
|
46
|
+
*
|
|
47
|
+
* ## 已知边界(刻意不做的事)
|
|
48
|
+
*
|
|
49
|
+
* - **不承诺自动脱敏**:本文件只删除、不修改正文。要在库里留下打码版本,是调用方的事。
|
|
50
|
+
* - 会话锚点(`kind: kanabo-session`)只带 `session_id` 与合成正文 `session <id>`,不含记忆正文;
|
|
51
|
+
* 保留期到期只删记忆行,锚点留给 `deleteBySource({sessionId})` / `deleteAll` 显式清理。
|
|
52
|
+
* - 临时探测库(`.egress-scratch-*`)在探测结束后立刻 `rmSync`(文件从目录树消失);持有它的
|
|
53
|
+
* 子进程按门面自己的空闲期限退出,之后不再有任何磁盘路径指向那份数据。
|
|
54
|
+
* - 快照里被删数据之外的内容**随代际一起消失**:这是「不可恢复」的代价,选择销毁而不是重写,
|
|
55
|
+
* 是因为重写(恢复→删行→重新快照)会把「不可恢复」变成一段有多步失败窗口的流程。
|
|
56
|
+
*/
|
|
57
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
|
|
58
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
59
|
+
|
|
60
|
+
import { EMBEDDING_DIM } from './contract.js'
|
|
61
|
+
import { MEMORY_KIND, SESSION_NODE_KIND, entryOf, restoreSnapshot } from './trivium-runtime.js'
|
|
62
|
+
import { createTriviumStore } from './store-trivium.js'
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 默认保留期:90 天。记忆是「跨会话的长期上下文」,太短会让画像与召回失去历史;
|
|
66
|
+
* 90 天对「被拍摄者/被记录者」而言仍是一个可解释的边界。可用 `KANABO_MEMORY_RETENTION_MS` 覆盖。
|
|
67
|
+
*/
|
|
68
|
+
export const DEFAULT_RETENTION_MS = 90 * 24 * 60 * 60 * 1000
|
|
69
|
+
export const RETENTION_ENV = 'KANABO_MEMORY_RETENTION_MS'
|
|
70
|
+
/** 审计轨迹的追加目标(JSONL);不设则只留在进程内 `trail()` 与返回值里。 */
|
|
71
|
+
export const AUDIT_ENV = 'KANABO_MEMORY_EGRESS_AUDIT'
|
|
72
|
+
|
|
73
|
+
/** 一次 `deleteNodes` 最多带多少 id:请求帧保持小,失败时重放的代价也可控。 */
|
|
74
|
+
const DELETE_BATCH = 512
|
|
75
|
+
/** 扫描分页粒度(keyset 游标是引擎节点号 `n.id`,升序)。 */
|
|
76
|
+
const SCAN_PAGE = 500
|
|
77
|
+
/** 扫描硬上限:超过即失败关闭,绝不拿部分集合假装「全部目标」。 */
|
|
78
|
+
const SCAN_MAX_ROWS = 100_000
|
|
79
|
+
/** 孤立边复核的行上限:测试库远小于它,超过即报告截断而不是静默。 */
|
|
80
|
+
const GRAPH_SCAN_LIMIT = 200_000
|
|
81
|
+
/** 进程内审计轨迹的保留条数(只是可观测性,真相来源是返回值与可选的 JSONL)。 */
|
|
82
|
+
const TRAIL_MAX = 500
|
|
83
|
+
|
|
84
|
+
const TRAIL = []
|
|
85
|
+
|
|
86
|
+
/** 带稳定 `code` 的错误,形状与 store.js / trivium-runtime.js 的 `KANABO_*` 约定一致。 */
|
|
87
|
+
export function egressError(code, message, details) {
|
|
88
|
+
const error = new Error(message)
|
|
89
|
+
error.code = code
|
|
90
|
+
if (details !== undefined) error.details = details
|
|
91
|
+
return error
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function tqlString(value) {
|
|
95
|
+
return JSON.stringify(String(value))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function rowsOf(result) {
|
|
99
|
+
return Array.isArray(result?.rows) ? result.rows : []
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function nodeIdOf(value) {
|
|
103
|
+
const id = typeof value === 'number' ? value : Number(value)
|
|
104
|
+
return Number.isSafeInteger(id) && id >= 0 ? id : null
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** `MATCH … RETURN n AS node` / `FIND … RETURN _ AS node` 的每一行都是 `{ id, numEdges, payload }` 包装。 */
|
|
108
|
+
function nodeOf(row) {
|
|
109
|
+
const node = row?._ ?? row?.node ?? null
|
|
110
|
+
if (node === null || typeof node !== 'object') return null
|
|
111
|
+
const id = nodeIdOf(node.id)
|
|
112
|
+
const payload = node.payload !== null && typeof node.payload === 'object' ? node.payload : null
|
|
113
|
+
return id === null ? null : { nodeId: id, payload }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function positiveInt(value, fallback) {
|
|
117
|
+
const number = Number(value)
|
|
118
|
+
return Number.isInteger(number) && number > 0 ? number : fallback
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 保留期(毫秒):每次调用重读环境变量,非法值退回默认。 */
|
|
122
|
+
export function retentionMs() {
|
|
123
|
+
return positiveInt(process.env[RETENTION_ENV], DEFAULT_RETENTION_MS)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 进程内审计轨迹(深拷贝:调用方改它不会污染账本)。 */
|
|
127
|
+
export function trail() {
|
|
128
|
+
return JSON.parse(JSON.stringify(TRAIL))
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 门面 → `{ scope, dir }`:快照的默认落点是 `<dir>/snapshots/<fileBase>/<gen>`,所以只要知道
|
|
133
|
+
* 活库路径就能定位所有快照。拿不到 scope/路径时**失败关闭**——「无法检查快照」绝不能等价于
|
|
134
|
+
* 「快照里没有数据」。
|
|
135
|
+
*/
|
|
136
|
+
function locate(facade) {
|
|
137
|
+
const scope = typeof facade?.workspace === 'string' && facade.workspace.length > 0 ? facade.workspace : null
|
|
138
|
+
const path = typeof facade?.path === 'string' && facade.path.length > 0 ? facade.path : null
|
|
139
|
+
if (scope === null || path === null) {
|
|
140
|
+
throw egressError('KANABO_EGRESS_SCOPE',
|
|
141
|
+
'egress 需要带 workspace 与 path 的已打开门面:快照与活库必须能被定位,否则无法证明删除不可恢复。',
|
|
142
|
+
{ workspace: scope, path })
|
|
143
|
+
}
|
|
144
|
+
const dir = dirname(path)
|
|
145
|
+
return { scope, dir, dbPath: path, snapshotRoot: join(dir, 'snapshots') }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* keyset 分页扫描(按引擎节点号升序)。`where` 是已经拼好的 payload 顶层条件(都来自
|
|
150
|
+
* `payloadFor` 的平铺镜像字段);kind 过滤在 JS 侧做,避免依赖 TQL 对括号 OR 的支持。
|
|
151
|
+
* 超过 `maxRows` 抛失败关闭错误:目标集合必须完整,否则「删干净了」只是错觉。
|
|
152
|
+
*/
|
|
153
|
+
async function scanNodes(facade, scope, options = {}) {
|
|
154
|
+
const pageSize = positiveInt(options.pageSize, SCAN_PAGE)
|
|
155
|
+
const maxRows = positiveInt(options.maxRows, SCAN_MAX_ROWS)
|
|
156
|
+
const kinds = Array.isArray(options.kinds) && options.kinds.length > 0 ? new Set(options.kinds) : null
|
|
157
|
+
const extra = Array.isArray(options.where) ? options.where.filter((clause) => typeof clause === 'string' && clause !== '') : []
|
|
158
|
+
const nodes = []
|
|
159
|
+
let lastId = 0
|
|
160
|
+
let pages = 0
|
|
161
|
+
for (;;) {
|
|
162
|
+
pages += 1
|
|
163
|
+
const where = [`n.workspace == ${tqlString(scope)}`, ...extra, `n.id > ${lastId}`]
|
|
164
|
+
const rows = rowsOf(await facade.tql(
|
|
165
|
+
`MATCH (n) WHERE ${where.join(' AND ')} RETURN n.id AS nodeId, n AS node ORDER BY n.id ASC LIMIT ${pageSize}`))
|
|
166
|
+
if (rows.length === 0) break
|
|
167
|
+
for (const row of rows) {
|
|
168
|
+
const node = nodeOf(row)
|
|
169
|
+
if (node === null) continue
|
|
170
|
+
if (node.nodeId <= lastId) {
|
|
171
|
+
throw egressError('KANABO_EGRESS_SCAN', `扫描游标没有前进(${lastId} → ${node.nodeId}),拒绝按不确定的集合删除。`,
|
|
172
|
+
{ scope, lastId, nodeId: node.nodeId, pages })
|
|
173
|
+
}
|
|
174
|
+
lastId = node.nodeId
|
|
175
|
+
const kind = node.payload?.kind
|
|
176
|
+
if (kinds !== null && !kinds.has(kind)) continue
|
|
177
|
+
nodes.push(node)
|
|
178
|
+
if (nodes.length > maxRows) {
|
|
179
|
+
throw egressError('KANABO_EGRESS_SCAN',
|
|
180
|
+
`目标集合超过上限 ${maxRows} 行(已读 ${nodes.length});拒绝按部分集合删除。`,
|
|
181
|
+
{ scope, maxRows, read: nodes.length, pages })
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (rows.length < pageSize) break
|
|
185
|
+
}
|
|
186
|
+
return { nodes, pages }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 目标节点的可审计投影:legacy id(信封 id 或锚点的 `session:<id>`)+ 引擎节点号 + 来源字段。 */
|
|
190
|
+
function targetOf(node) {
|
|
191
|
+
const entry = entryOf(node)
|
|
192
|
+
const payload = node.payload ?? {}
|
|
193
|
+
const envelope = payload.envelope !== null && typeof payload.envelope === 'object' ? payload.envelope : {}
|
|
194
|
+
const identity = typeof envelope?.id === 'string' && envelope.id.length > 0
|
|
195
|
+
? envelope.id
|
|
196
|
+
: (typeof payload.id === 'string' && payload.id.length > 0
|
|
197
|
+
? payload.id
|
|
198
|
+
: (typeof payload.legacy_id === 'string' && payload.legacy_id.length > 0 ? payload.legacy_id : String(node.nodeId)))
|
|
199
|
+
return {
|
|
200
|
+
nodeId: node.nodeId,
|
|
201
|
+
id: identity,
|
|
202
|
+
kind: typeof payload.kind === 'string' ? payload.kind : null,
|
|
203
|
+
sourceType: typeof payload.source_type === 'string' ? payload.source_type : null,
|
|
204
|
+
sessionId: typeof payload.session_id === 'string' ? payload.session_id : null,
|
|
205
|
+
jobId: typeof payload.job_id === 'string' ? payload.job_id : null,
|
|
206
|
+
videoId: typeof payload.video_id === 'string' ? payload.video_id : null,
|
|
207
|
+
ts: Number.isFinite(Number(entry?.ts ?? payload.ts)) ? Number(entry?.ts ?? payload.ts) : null,
|
|
208
|
+
retainedUntil: retainedUntilOf(payload, envelope),
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** per-row 保留期:信封写在 `node_metadata.retained_until`,也容忍顶层镜像(两种都读,取第一个有限数)。 */
|
|
213
|
+
function retainedUntilOf(payload, envelope) {
|
|
214
|
+
const candidates = [payload?.retained_until, payload?.node_metadata?.retained_until, envelope?.node_metadata?.retained_until]
|
|
215
|
+
for (const value of candidates) {
|
|
216
|
+
const number = Number(value)
|
|
217
|
+
if (value !== undefined && value !== null && Number.isFinite(number)) return number
|
|
218
|
+
}
|
|
219
|
+
return null
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** 按来源收集目标(`MATCH` 只过滤 payload 顶层镜像字段,全部是 `payloadFor` 写出的)。 */
|
|
223
|
+
function sourceWhere(filter) {
|
|
224
|
+
const where = []
|
|
225
|
+
if (filter.source_type) where.push(`n.source_type == ${tqlString(filter.source_type)}`)
|
|
226
|
+
if (filter.jobId) where.push(`n.job_id == ${tqlString(filter.jobId)}`)
|
|
227
|
+
if (filter.videoId) where.push(`n.video_id == ${tqlString(filter.videoId)}`)
|
|
228
|
+
if (filter.sessionId) where.push(`n.session_id == ${tqlString(filter.sessionId)}`)
|
|
229
|
+
return where
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function collectBySource(facade, scope, filter, settings) {
|
|
233
|
+
const scanned = await scanNodes(facade, scope, { ...settings, where: sourceWhere(filter), kinds: [MEMORY_KIND] })
|
|
234
|
+
return scanned.nodes.map(targetOf)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* 按来源的判定谓词(作用在节点 payload 上,与 `collectBySource` 的 TQL 条件逐项对应)。
|
|
239
|
+
* 快照判定用它而不是 id 列表,所以「活库已空」的重试仍能认出污染代际。
|
|
240
|
+
*/
|
|
241
|
+
function sourceMatcher(filter) {
|
|
242
|
+
return (payload) => {
|
|
243
|
+
if (payload?.kind !== MEMORY_KIND) return false
|
|
244
|
+
if (filter.source_type !== null && payload.source_type !== filter.source_type) return false
|
|
245
|
+
if (filter.jobId !== null && payload.job_id !== filter.jobId) return false
|
|
246
|
+
if (filter.videoId !== null && payload.video_id !== filter.videoId) return false
|
|
247
|
+
if (filter.sessionId !== null && payload.session_id !== filter.sessionId) return false
|
|
248
|
+
return true
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 按来源删除时锚点也在范围内:`sessionId` 过滤同时命中该会话的锚点节点。 */
|
|
253
|
+
function sourceAndAnchorMatcher(filter) {
|
|
254
|
+
const rows = sourceMatcher(filter)
|
|
255
|
+
return (payload) => rows(payload) || (filter.sessionId !== null
|
|
256
|
+
&& payload?.kind === SESSION_NODE_KIND && payload?.session_id === filter.sessionId)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function retentionMatcher(cutoffTs, now, sourceType) {
|
|
260
|
+
return (payload) => {
|
|
261
|
+
if (payload?.kind !== MEMORY_KIND) return false
|
|
262
|
+
if (sourceType !== null && payload.source_type !== sourceType) return false
|
|
263
|
+
return isExpired(payload, cutoffTs, now)
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 过期判定(活库收集与快照判定共用同一个函数,避免两处口径漂移)。 */
|
|
268
|
+
function isExpired(payload, cutoffTs, now) {
|
|
269
|
+
const ts = Number(payload?.ts)
|
|
270
|
+
if (Number.isFinite(ts) && ts < cutoffTs) return true
|
|
271
|
+
const retainedUntil = retainedUntilOf(payload, payload?.envelope)
|
|
272
|
+
return retainedUntil !== null && retainedUntil <= now
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* 孤立边复核:先枚举全图边端点,再枚举全库节点号(**不按 kind 过滤**,会话锚点也是活节点)。
|
|
277
|
+
* 与 `purge.js` 的检查同一判据,但用一次全库扫描而不是逐 kind 拼查询——判据是「端点是否还活着」。
|
|
278
|
+
*/
|
|
279
|
+
export async function assertNoOrphans(facade) {
|
|
280
|
+
const edgeRows = rowsOf(await facade.tql(`MATCH (a)-[r]->(b) RETURN a.id AS s, b.id AS t LIMIT ${GRAPH_SCAN_LIMIT}`))
|
|
281
|
+
const edges = []
|
|
282
|
+
for (const row of edgeRows) {
|
|
283
|
+
const from = nodeIdOf(row?.s)
|
|
284
|
+
const to = nodeIdOf(row?.t)
|
|
285
|
+
if (from === null || to === null) continue
|
|
286
|
+
edges.push({ from, to })
|
|
287
|
+
}
|
|
288
|
+
const nodeRows = rowsOf(await facade.tql(`MATCH (n) WHERE n.id > 0 RETURN n.id AS nodeId LIMIT ${GRAPH_SCAN_LIMIT}`))
|
|
289
|
+
const alive = new Set()
|
|
290
|
+
for (const row of nodeRows) {
|
|
291
|
+
const id = nodeIdOf(row?.nodeId)
|
|
292
|
+
if (id !== null) alive.add(id)
|
|
293
|
+
}
|
|
294
|
+
const endpoints = [...new Set(edges.flatMap((edge) => [edge.from, edge.to]))]
|
|
295
|
+
const missing = endpoints.filter((id) => !alive.has(id))
|
|
296
|
+
return {
|
|
297
|
+
ok: missing.length === 0,
|
|
298
|
+
edges: edges.length,
|
|
299
|
+
checked: endpoints.length,
|
|
300
|
+
missing,
|
|
301
|
+
nodes: alive.size,
|
|
302
|
+
truncated: edgeRows.length >= GRAPH_SCAN_LIMIT || nodeRows.length >= GRAPH_SCAN_LIMIT,
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ---------------------------------------------------------------------------
|
|
307
|
+
// 快照:判定(恢复 + 查询)→ 销毁 → 复核
|
|
308
|
+
// ---------------------------------------------------------------------------
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* 列出**本库**的 `<snapshotRoot>/<fileBase>/<generationId>` 代际目录。只扫自己的 fileBase 子目录:
|
|
312
|
+
* 别的 workspace 的快照不属于这次删除的授权范围,越权销毁它们是另一种数据丢失。
|
|
313
|
+
* 显式给了 `destination` 的快照落在别处,本函数看不到——这是文档里写明的边界。
|
|
314
|
+
*/
|
|
315
|
+
function listGenerations(root, dbPath) {
|
|
316
|
+
const scopeDir = join(root, basename(dbPath).replace(/\.tdb$/, ''))
|
|
317
|
+
if (!existsSync(scopeDir)) return []
|
|
318
|
+
let generations = []
|
|
319
|
+
try {
|
|
320
|
+
generations = readdirSync(scopeDir, { withFileTypes: true })
|
|
321
|
+
} catch {
|
|
322
|
+
return []
|
|
323
|
+
}
|
|
324
|
+
const out = []
|
|
325
|
+
for (const generation of generations) {
|
|
326
|
+
if (!generation.isDirectory()) continue
|
|
327
|
+
out.push({ workspaceDir: basename(scopeDir), generation: generation.name, dir: join(scopeDir, generation.name) })
|
|
328
|
+
}
|
|
329
|
+
return out
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* 把一个代际恢复到临时库,把**符合过滤谓词**的行找出来。谓词作用在 payload 上,与收集活库目标时
|
|
334
|
+
* 用的是同一个判定函数,所以「判定」与「收集」不会各说各话;也因此重试时(活库已空、没有 id 可传)
|
|
335
|
+
* 仍能认出污染代际并销毁它。
|
|
336
|
+
*
|
|
337
|
+
* 临时库落在活库目录旁的 `.egress-scratch-*`,用完**关掉门面**并整目录删除——判定用的那份数据
|
|
338
|
+
* 同样是可恢复副本,不能留在磁盘上。
|
|
339
|
+
*
|
|
340
|
+
* 这里直接用 `createTriviumStore` 而不是 `withFacade`:临时库不进进程级注册表,
|
|
341
|
+
* 因此可以确定性关闭(`close()` 会等子进程真的退出),不会给每次探测留一个常驻子进程。
|
|
342
|
+
* 维度必须显式给:门面的 `DEFAULT_DIM` 是 1536 的占位,恢复出来的库是契约的 384 维,
|
|
343
|
+
* 不给就会在 open 阶段报 `TDB_DIMENSION_MISMATCH`(那就是一次「探测失败」)。
|
|
344
|
+
*/
|
|
345
|
+
async function probeGeneration(generation, matches, settings, index) {
|
|
346
|
+
const stamp = `${process.pid}-${Date.now().toString(36)}-${index}`
|
|
347
|
+
const scratchDir = join(settings.dir, `${SCRATCH_PREFIX}${stamp}`)
|
|
348
|
+
const scratchScope = `egress-scratch-${stamp}`
|
|
349
|
+
try {
|
|
350
|
+
await restoreSnapshot({ scope: scratchScope, dir: scratchDir, snapshotDir: generation.dir, timeoutMs: settings.timeoutMs })
|
|
351
|
+
const store = createTriviumStore({ workspace: scratchScope, dir: scratchDir, dim: settings.dim })
|
|
352
|
+
try {
|
|
353
|
+
await store.open()
|
|
354
|
+
const found = new Set()
|
|
355
|
+
let lastId = 0
|
|
356
|
+
for (;;) {
|
|
357
|
+
const rows = rowsOf(await store.tql(
|
|
358
|
+
`MATCH (n) WHERE n.id > ${lastId} RETURN n.id AS nodeId, n AS node ORDER BY n.id ASC LIMIT ${SCAN_PAGE}`))
|
|
359
|
+
if (rows.length === 0) break
|
|
360
|
+
let advanced = false
|
|
361
|
+
for (const row of rows) {
|
|
362
|
+
const node = nodeOf(row)
|
|
363
|
+
if (node === null || node.nodeId <= lastId) continue
|
|
364
|
+
lastId = node.nodeId
|
|
365
|
+
advanced = true
|
|
366
|
+
if (!matches(node.payload)) continue
|
|
367
|
+
const identity = node.payload?.envelope?.id ?? node.payload?.id ?? node.payload?.legacy_id
|
|
368
|
+
found.add(typeof identity === 'string' && identity.length > 0 ? identity : String(node.nodeId))
|
|
369
|
+
}
|
|
370
|
+
if (!advanced) break
|
|
371
|
+
if (found.size > SCAN_MAX_ROWS) {
|
|
372
|
+
throw egressError('KANABO_EGRESS_SCAN', `快照 ${generation.dir} 的命中数超过 ${SCAN_MAX_ROWS};拒绝按部分集合判定。`)
|
|
373
|
+
}
|
|
374
|
+
if (rows.length < SCAN_PAGE) break
|
|
375
|
+
}
|
|
376
|
+
return [...found]
|
|
377
|
+
} finally {
|
|
378
|
+
await store.close()
|
|
379
|
+
}
|
|
380
|
+
} finally {
|
|
381
|
+
rmSync(scratchDir, { recursive: true, force: true })
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** 字节级判定(只用于 `.backup-<ts>` 这类非快照格式的整库副本):`"<id>"` 作为完整 JSON 字符串出现。 */
|
|
386
|
+
function containsId(dir, ids) {
|
|
387
|
+
const needles = ids.map((id) => Buffer.from(`"${id}"`))
|
|
388
|
+
const hits = []
|
|
389
|
+
let entries = []
|
|
390
|
+
try {
|
|
391
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
392
|
+
} catch {
|
|
393
|
+
return hits
|
|
394
|
+
}
|
|
395
|
+
for (const entry of entries) {
|
|
396
|
+
const full = join(dir, entry.name)
|
|
397
|
+
if (entry.isDirectory()) {
|
|
398
|
+
hits.push(...containsId(full, ids))
|
|
399
|
+
continue
|
|
400
|
+
}
|
|
401
|
+
if (!entry.isFile()) continue
|
|
402
|
+
let buffer
|
|
403
|
+
try {
|
|
404
|
+
buffer = readFileSync(full)
|
|
405
|
+
} catch {
|
|
406
|
+
continue
|
|
407
|
+
}
|
|
408
|
+
for (let index = 0; index < ids.length; index += 1) {
|
|
409
|
+
if (buffer.includes(needles[index])) hits.push({ file: full, id: ids[index] })
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return hits
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** 活库里是否还留着被删数据的字节(只报告,不删除:引擎的 delete 已经重写 payload 代际)。 */
|
|
416
|
+
function liveResidue(dir, dbPath, ids) {
|
|
417
|
+
const base = basename(dbPath)
|
|
418
|
+
const hits = []
|
|
419
|
+
let entries = []
|
|
420
|
+
try {
|
|
421
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
422
|
+
} catch {
|
|
423
|
+
return hits
|
|
424
|
+
}
|
|
425
|
+
for (const entry of entries) {
|
|
426
|
+
if (!entry.isFile()) continue
|
|
427
|
+
if (!(entry.name === base || entry.name.startsWith(`${base}.`))) continue
|
|
428
|
+
let buffer
|
|
429
|
+
try {
|
|
430
|
+
buffer = readFileSync(join(dir, entry.name))
|
|
431
|
+
} catch {
|
|
432
|
+
continue
|
|
433
|
+
}
|
|
434
|
+
for (const id of ids) {
|
|
435
|
+
if (buffer.includes(Buffer.from(`"${id}"`))) hits.push({ file: entry.name, id })
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return hits
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* 快照计划:逐代际恢复+扫描,命中谓词的进 `contaminated`,干净的进 `kept`,探测失败的按命中处理。
|
|
443
|
+
* `.backup-*` 整库副本按字节判定(它们不是快照格式,不能 `restoreSnapshot`),所以它仍需要 id 列表。
|
|
444
|
+
*
|
|
445
|
+
* 谓词而不是 id 列表:这样「活库已空」的重试也认得出污染代际(上一轮删了活库但没删掉快照的情形)。
|
|
446
|
+
*/
|
|
447
|
+
async function planSnapshots(settings, matches, ids) {
|
|
448
|
+
const generations = listGenerations(settings.snapshotRoot, settings.dbPath)
|
|
449
|
+
const contaminated = []
|
|
450
|
+
const kept = []
|
|
451
|
+
const probed = []
|
|
452
|
+
const errors = []
|
|
453
|
+
for (const [index, generation] of generations.entries()) {
|
|
454
|
+
probed.push(generation.dir)
|
|
455
|
+
try {
|
|
456
|
+
const found = await probeGeneration(generation, matches, settings, index)
|
|
457
|
+
if (found.length > 0) contaminated.push({ ...generation, found, reason: 'contains-deleted-rows' })
|
|
458
|
+
else kept.push(generation.dir)
|
|
459
|
+
} catch (error) {
|
|
460
|
+
// 无法证明干净 = 不干净:恢复不了的快照既不能被验证,也不能被留下。
|
|
461
|
+
errors.push({ dir: generation.dir, code: error?.code ?? 'KANABO_EGRESS_PROBE', message: String(error?.message ?? error) })
|
|
462
|
+
contaminated.push({ ...generation, found: [], reason: 'probe-failed' })
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
const backups = { scanned: 0, contaminated: [], kept: [] }
|
|
466
|
+
if (ids.length > 0) {
|
|
467
|
+
let backupEntries = []
|
|
468
|
+
try {
|
|
469
|
+
backupEntries = readdirSync(settings.dir, { withFileTypes: true })
|
|
470
|
+
} catch {
|
|
471
|
+
backupEntries = []
|
|
472
|
+
}
|
|
473
|
+
for (const entry of backupEntries) {
|
|
474
|
+
if (!entry.isDirectory() || !entry.name.startsWith('.backup-')) continue
|
|
475
|
+
backups.scanned += 1
|
|
476
|
+
const full = join(settings.dir, entry.name)
|
|
477
|
+
const hits = containsId(full, ids)
|
|
478
|
+
if (hits.length > 0) backups.contaminated.push({ dir: full, found: [...new Set(hits.map((hit) => hit.id))] })
|
|
479
|
+
else backups.kept.push(full)
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return { probed, contaminated, kept, backups, errors }
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** 销毁命中的代际目录与整库副本,剪掉变空的 workspace 目录;返回逐条可审计的清单。 */
|
|
486
|
+
function destroyContaminated(plan) {
|
|
487
|
+
const removed = []
|
|
488
|
+
const failed = []
|
|
489
|
+
const workspaceDirs = new Set()
|
|
490
|
+
for (const item of plan.contaminated) {
|
|
491
|
+
try {
|
|
492
|
+
rmSync(item.dir, { recursive: true, force: true })
|
|
493
|
+
// 引擎在代际目录旁留一个 `<gen>.snapshot.lock` 旁文件:代际没了它就是垃圾,
|
|
494
|
+
// 而且它会阻止「workspace 目录变空」的剪枝。
|
|
495
|
+
rmSync(join(dirname(item.dir), `.${item.generation}.snapshot.lock`), { force: true })
|
|
496
|
+
removed.push({ dir: item.dir, generation: item.generation, found: item.found, reason: item.reason })
|
|
497
|
+
workspaceDirs.add(dirname(item.dir))
|
|
498
|
+
} catch (error) {
|
|
499
|
+
failed.push({ dir: item.dir, reason: String(error?.message ?? error) })
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
for (const dir of workspaceDirs) {
|
|
503
|
+
try {
|
|
504
|
+
if (existsSync(dir) && readdirSync(dir).length === 0) rmSync(dir, { recursive: true, force: true })
|
|
505
|
+
} catch {
|
|
506
|
+
// 剪枝失败只影响目录整洁,不影响「代际已消失」这个事实。
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
const backupsRemoved = []
|
|
510
|
+
for (const item of plan.backups.contaminated) {
|
|
511
|
+
try {
|
|
512
|
+
rmSync(item.dir, { recursive: true, force: true })
|
|
513
|
+
backupsRemoved.push(item)
|
|
514
|
+
} catch (error) {
|
|
515
|
+
failed.push({ dir: item.dir, reason: String(error?.message ?? error) })
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return { removed, backupsRemoved, failed }
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// ---------------------------------------------------------------------------
|
|
522
|
+
// 审计轨迹
|
|
523
|
+
// ---------------------------------------------------------------------------
|
|
524
|
+
|
|
525
|
+
function auditTarget(settings) {
|
|
526
|
+
if (typeof settings.auditPath === 'string' && settings.auditPath.length > 0) return resolve(settings.auditPath)
|
|
527
|
+
const fromEnv = process.env[AUDIT_ENV]
|
|
528
|
+
return typeof fromEnv === 'string' && fromEnv.length > 0 ? resolve(fromEnv) : null
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** 追加一行 JSONL 并把结果写回记录;写不进去不推翻已经发生的事实,但必须可见。 */
|
|
532
|
+
function appendAudit(entry, settings) {
|
|
533
|
+
const path = auditTarget(settings)
|
|
534
|
+
if (path === null) return { path: null, ok: true, appended: false }
|
|
535
|
+
try {
|
|
536
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
537
|
+
appendFileSync(path, `${JSON.stringify(entry)}\n`)
|
|
538
|
+
return { path, ok: true, appended: true }
|
|
539
|
+
} catch (error) {
|
|
540
|
+
return { path, ok: false, appended: false, error: String(error?.message ?? error) }
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function record(entry) {
|
|
545
|
+
TRAIL.push(entry)
|
|
546
|
+
while (TRAIL.length > TRAIL_MAX) TRAIL.shift()
|
|
547
|
+
return entry
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// ---------------------------------------------------------------------------
|
|
551
|
+
// 删除主流程(三个入口共用:同一套快照处理、同一套复核、同一种审计记录)
|
|
552
|
+
// ---------------------------------------------------------------------------
|
|
553
|
+
|
|
554
|
+
async function deleteBatched(facade, nodeIds) {
|
|
555
|
+
let removed = 0
|
|
556
|
+
let requested = 0
|
|
557
|
+
for (let start = 0; start < nodeIds.length; start += DELETE_BATCH) {
|
|
558
|
+
const result = await facade.deleteNodes(nodeIds.slice(start, start + DELETE_BATCH))
|
|
559
|
+
requested += Number(result?.requested ?? 0)
|
|
560
|
+
removed += Number(result?.removed ?? 0)
|
|
561
|
+
}
|
|
562
|
+
return { requested, removed }
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* 删除 + 快照销毁 + 复核 + 审计。`targets` 已经收集好(dryRun 时只用来列清单)。
|
|
567
|
+
*
|
|
568
|
+
* 顺序是刻意的:**先判定快照,再删活库**。这样「哪些代际必须销毁」在动活数据之前就已确定,
|
|
569
|
+
* 中途失败时也留着一份精确清单,而不是「删了数据、还不知道快照里有没有」。
|
|
570
|
+
*/
|
|
571
|
+
async function applyDeletion(options) {
|
|
572
|
+
const facade = options.facade
|
|
573
|
+
const settings = options.settings
|
|
574
|
+
const targets = options.targets
|
|
575
|
+
const dryRun = options.dryRun === true
|
|
576
|
+
const ids = [...new Set(targets.map((target) => target.id))]
|
|
577
|
+
const nodeIds = [...new Set(targets.map((target) => target.nodeId))]
|
|
578
|
+
const atMs = Date.now()
|
|
579
|
+
|
|
580
|
+
const plan = await planSnapshots(settings, options.matches, ids)
|
|
581
|
+
const snapshotPlan = {
|
|
582
|
+
probed: plan.probed.length,
|
|
583
|
+
contaminated: plan.contaminated.map((item) => ({ dir: item.dir, generation: item.generation, found: item.found, reason: item.reason })),
|
|
584
|
+
kept: plan.kept.length,
|
|
585
|
+
backups: { scanned: plan.backups.scanned, contaminated: plan.backups.contaminated, kept: plan.backups.kept.length },
|
|
586
|
+
errors: plan.errors,
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
if (dryRun) {
|
|
590
|
+
const entry = {
|
|
591
|
+
id: `egress-${atMs.toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
592
|
+
at: new Date(atMs).toISOString(),
|
|
593
|
+
atMs,
|
|
594
|
+
action: options.action,
|
|
595
|
+
dryRun: true,
|
|
596
|
+
scope: settings.scope,
|
|
597
|
+
filter: options.filter,
|
|
598
|
+
ids,
|
|
599
|
+
nodeIds,
|
|
600
|
+
deleted: { requested: 0, removed: 0, nodes: 0 },
|
|
601
|
+
snapshots: { ...snapshotPlan, removed: [], backupsRemoved: [], failed: [] },
|
|
602
|
+
orphans: null,
|
|
603
|
+
// dry-run 没有「剩余」可言:`remaining` 显式置 null,要用的是 `wouldDelete`。
|
|
604
|
+
// 否则一个按字面读 `remaining === 0` 的调用方会把「将删 4 条」误读成「已经干净」。
|
|
605
|
+
remaining: null,
|
|
606
|
+
wouldDelete: ids.length,
|
|
607
|
+
residue: [],
|
|
608
|
+
ok: true,
|
|
609
|
+
}
|
|
610
|
+
entry.audit = appendAudit(entry, settings)
|
|
611
|
+
return record(entry)
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
const deleted = nodeIds.length > 0 ? await deleteBatched(facade, nodeIds) : { requested: 0, removed: 0 }
|
|
615
|
+
const destroyed = destroyContaminated(plan)
|
|
616
|
+
const orphans = await assertNoOrphans(facade)
|
|
617
|
+
const remaining = options.recount === undefined ? 0 : await options.recount()
|
|
618
|
+
const residue = liveResidue(settings.dir, settings.dbPath, ids)
|
|
619
|
+
const snapshotsClean = destroyed.failed.length === 0 && plan.contaminated.every((item) => !existsSync(item.dir))
|
|
620
|
+
&& plan.backups.contaminated.every((item) => !existsSync(item.dir))
|
|
621
|
+
|
|
622
|
+
const entry = {
|
|
623
|
+
id: `egress-${atMs.toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
624
|
+
at: new Date(atMs).toISOString(),
|
|
625
|
+
atMs,
|
|
626
|
+
action: options.action,
|
|
627
|
+
dryRun: false,
|
|
628
|
+
scope: settings.scope,
|
|
629
|
+
filter: options.filter,
|
|
630
|
+
ids,
|
|
631
|
+
nodeIds,
|
|
632
|
+
deleted: { requested: deleted.requested, removed: deleted.removed, nodes: nodeIds.length },
|
|
633
|
+
snapshots: { ...snapshotPlan, removed: destroyed.removed, backupsRemoved: destroyed.backupsRemoved, failed: destroyed.failed },
|
|
634
|
+
orphans,
|
|
635
|
+
remaining,
|
|
636
|
+
residue,
|
|
637
|
+
// 字节残留只是**告警**而不是失败:另有一条活着的记忆在正文里提到了这个 id 也会命中字节。
|
|
638
|
+
// 「删干净了」的权威判据是 remaining === 0(同一次过滤再查一遍),快照的判据是恢复+查询。
|
|
639
|
+
residueOk: residue.length === 0,
|
|
640
|
+
ok: remaining === 0 && orphans.ok && snapshotsClean,
|
|
641
|
+
}
|
|
642
|
+
entry.audit = appendAudit(entry, settings)
|
|
643
|
+
return record(entry)
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function settingsOf(options) {
|
|
647
|
+
const located = locate(options.facade)
|
|
648
|
+
return {
|
|
649
|
+
...located,
|
|
650
|
+
snapshotRoot: resolve(options.snapshotRoot ?? located.snapshotRoot),
|
|
651
|
+
timeoutMs: positiveInt(options.timeoutMs, 60_000),
|
|
652
|
+
dim: positiveInt(options.dim, EMBEDDING_DIM),
|
|
653
|
+
auditPath: options.auditPath,
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* 按来源删除。过滤条件至少给一个(`source_type` / `jobId` / `videoId` / `sessionId`),
|
|
659
|
+
* 空过滤**拒绝**——大范围删除必须显式调用 `deleteAll`。
|
|
660
|
+
*
|
|
661
|
+
* 给 `sessionId` 时,该会话的锚点节点也一起删除(锚点只带会话 id,属于该来源的数据)。
|
|
662
|
+
* `dryRun` 只列清单(含「会销毁哪些快照代际」),不动活库、不动快照。
|
|
663
|
+
*/
|
|
664
|
+
export async function deleteBySource(options = {}) {
|
|
665
|
+
const facade = options.facade
|
|
666
|
+
if (facade === null || typeof facade !== 'object' || typeof facade.tql !== 'function' || typeof facade.deleteNodes !== 'function') {
|
|
667
|
+
throw egressError('KANABO_EGRESS_FACADE', 'deleteBySource 需要一个已打开的门面(带 tql / deleteNodes)。')
|
|
668
|
+
}
|
|
669
|
+
const filter = {
|
|
670
|
+
source_type: typeof options.source_type === 'string' && options.source_type.length > 0 ? options.source_type : null,
|
|
671
|
+
jobId: typeof options.jobId === 'string' && options.jobId.length > 0 ? options.jobId : null,
|
|
672
|
+
videoId: typeof options.videoId === 'string' && options.videoId.length > 0 ? options.videoId : null,
|
|
673
|
+
sessionId: typeof options.sessionId === 'string' && options.sessionId.length > 0 ? options.sessionId : null,
|
|
674
|
+
}
|
|
675
|
+
if (filter.source_type === null && filter.jobId === null && filter.videoId === null && filter.sessionId === null) {
|
|
676
|
+
throw egressError('KANABO_EGRESS_FILTER',
|
|
677
|
+
'deleteBySource 需要 source_type / jobId / videoId / sessionId 至少一个;整库删除请显式用 deleteAll。',
|
|
678
|
+
{ filter })
|
|
679
|
+
}
|
|
680
|
+
const settings = settingsOf(options)
|
|
681
|
+
const targets = await collectBySource(facade, settings.scope, filter, options)
|
|
682
|
+
const countAnchors = async () => {
|
|
683
|
+
if (filter.sessionId === null) return 0
|
|
684
|
+
const left = await scanNodes(facade, settings.scope, {
|
|
685
|
+
...options,
|
|
686
|
+
where: [`n.session_id == ${tqlString(filter.sessionId)}`],
|
|
687
|
+
kinds: [SESSION_NODE_KIND],
|
|
688
|
+
})
|
|
689
|
+
return left.nodes.length
|
|
690
|
+
}
|
|
691
|
+
if (filter.sessionId !== null) {
|
|
692
|
+
const anchors = await scanNodes(facade, settings.scope, {
|
|
693
|
+
...options,
|
|
694
|
+
where: [`n.session_id == ${tqlString(filter.sessionId)}`],
|
|
695
|
+
kinds: [SESSION_NODE_KIND],
|
|
696
|
+
})
|
|
697
|
+
for (const anchor of anchors.nodes) targets.push(targetOf(anchor))
|
|
698
|
+
}
|
|
699
|
+
const entry = await applyDeletion({
|
|
700
|
+
facade,
|
|
701
|
+
settings,
|
|
702
|
+
targets,
|
|
703
|
+
matches: sourceAndAnchorMatcher(filter),
|
|
704
|
+
dryRun: options.dryRun === true,
|
|
705
|
+
action: 'deleteBySource',
|
|
706
|
+
filter,
|
|
707
|
+
// 锚点也是这次删除的对象:只数记忆行会让「锚点没删掉」也报 ok。
|
|
708
|
+
recount: async () => (await collectBySource(facade, settings.scope, filter, options)).length + await countAnchors(),
|
|
709
|
+
})
|
|
710
|
+
return { ...entry, targets }
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* 全局删除:清空一个 workspace 的全部节点(记忆行 + 会话锚点),删完图仍一致。
|
|
715
|
+
* 快照处理与按来源删除完全相同——整库删除同样不能留下能恢复的快照代际。
|
|
716
|
+
*/
|
|
717
|
+
export async function deleteAll(options = {}) {
|
|
718
|
+
const facade = options.facade
|
|
719
|
+
if (facade === null || typeof facade !== 'object' || typeof facade.tql !== 'function' || typeof facade.deleteNodes !== 'function') {
|
|
720
|
+
throw egressError('KANABO_EGRESS_FACADE', 'deleteAll 需要一个已打开的门面(带 tql / deleteNodes)。')
|
|
721
|
+
}
|
|
722
|
+
const settings = settingsOf(options)
|
|
723
|
+
const scanned = await scanNodes(facade, settings.scope, { ...options, kinds: [MEMORY_KIND, SESSION_NODE_KIND] })
|
|
724
|
+
const targets = scanned.nodes.map(targetOf)
|
|
725
|
+
const entry = await applyDeletion({
|
|
726
|
+
facade,
|
|
727
|
+
settings,
|
|
728
|
+
targets,
|
|
729
|
+
matches: (payload) => payload?.kind === MEMORY_KIND || payload?.kind === SESSION_NODE_KIND,
|
|
730
|
+
dryRun: options.dryRun === true,
|
|
731
|
+
action: 'deleteAll',
|
|
732
|
+
filter: { workspace: settings.scope },
|
|
733
|
+
recount: async () => {
|
|
734
|
+
const left = await scanNodes(facade, settings.scope, { ...options, kinds: [MEMORY_KIND, SESSION_NODE_KIND] })
|
|
735
|
+
return left.nodes.length
|
|
736
|
+
},
|
|
737
|
+
})
|
|
738
|
+
return { ...entry, targets }
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* 保留期到期删除。cutoff 缺省 `now - KANABO_MEMORY_RETENTION_MS`;
|
|
743
|
+
* 判定:`ts < cutoff` **或** 该行带 `retained_until` 且 `retained_until <= now`。
|
|
744
|
+
* 两种判据都走同一条删除路径(含快照销毁),所以「到点过期」与「按来源删除」一样不可恢复。
|
|
745
|
+
*/
|
|
746
|
+
export async function expireBefore(options = {}) {
|
|
747
|
+
const facade = options.facade
|
|
748
|
+
if (facade === null || typeof facade !== 'object' || typeof facade.tql !== 'function' || typeof facade.deleteNodes !== 'function') {
|
|
749
|
+
throw egressError('KANABO_EGRESS_FACADE', 'expireBefore 需要一个已打开的门面(带 tql / deleteNodes)。')
|
|
750
|
+
}
|
|
751
|
+
const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now()
|
|
752
|
+
const configuredRetention = retentionMs()
|
|
753
|
+
const cutoffTs = Number.isFinite(Number(options.cutoffTs))
|
|
754
|
+
? Number(options.cutoffTs)
|
|
755
|
+
: Number.isFinite(Number(options.cutoff))
|
|
756
|
+
? Number(options.cutoff)
|
|
757
|
+
: now - configuredRetention
|
|
758
|
+
const sourceType = typeof options.source_type === 'string' && options.source_type.length > 0 ? options.source_type : null
|
|
759
|
+
const settings = settingsOf(options)
|
|
760
|
+
const where = sourceType === null ? [] : [`n.source_type == ${tqlString(sourceType)}`]
|
|
761
|
+
const scanned = await scanNodes(facade, settings.scope, { ...options, where, kinds: [MEMORY_KIND] })
|
|
762
|
+
const targets = []
|
|
763
|
+
let survived = 0
|
|
764
|
+
for (const node of scanned.nodes) {
|
|
765
|
+
const target = targetOf(node)
|
|
766
|
+
if (isExpired(node.payload, cutoffTs, now)) targets.push(target)
|
|
767
|
+
else survived += 1
|
|
768
|
+
}
|
|
769
|
+
const entry = await applyDeletion({
|
|
770
|
+
facade,
|
|
771
|
+
settings,
|
|
772
|
+
targets,
|
|
773
|
+
matches: retentionMatcher(cutoffTs, now, sourceType),
|
|
774
|
+
dryRun: options.dryRun === true,
|
|
775
|
+
action: 'expireBefore',
|
|
776
|
+
filter: { source_type: sourceType, cutoffTs, now, retentionMs: configuredRetention },
|
|
777
|
+
recount: async () => {
|
|
778
|
+
const left = await scanNodes(facade, settings.scope, { ...options, where, kinds: [MEMORY_KIND] })
|
|
779
|
+
let remaining = 0
|
|
780
|
+
for (const node of left.nodes) if (isExpired(node.payload, cutoffTs, now)) remaining += 1
|
|
781
|
+
return remaining
|
|
782
|
+
},
|
|
783
|
+
})
|
|
784
|
+
return { ...entry, cutoffTs, now, survived, targets }
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** 供探针/运维判断「这个目录是不是一次 egress 的产物」:临时探测库一律带此前缀。 */
|
|
788
|
+
export const SCRATCH_PREFIX = '.egress-scratch-'
|