@evomap/evolver-cli 2.0.0-beta.8 → 2.0.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/dist/antiGeneBenchmark.js +2 -0
- package/dist/antiGeneRollout.js +9 -3
- package/dist/assetHealth.js +2 -0
- package/dist/assetTrust.js +14 -1
- package/dist/atp.d.ts +10 -5
- package/dist/atp.js +119 -26
- package/dist/atpAutoBuyer.d.ts +120 -0
- package/dist/atpAutoBuyer.js +814 -0
- package/dist/atpAutoDeliver.js +2 -2
- package/dist/autoDistillLlm.js +2 -1
- package/dist/autoDistillTranscript.js +3 -2
- package/dist/autoexec.d.ts +101 -13
- package/dist/autoexec.js +794 -91
- package/dist/cli.js +13 -0
- package/dist/cliContracts.d.ts +23 -2
- package/dist/cliContracts.js +504 -54
- package/dist/commands.d.ts +1 -0
- package/dist/commands.js +1 -0
- package/dist/curriculumCapabilityGaps.d.ts +6 -0
- package/dist/curriculumCapabilityGaps.js +24 -0
- package/dist/cycleConsumer.d.ts +13 -0
- package/dist/cycleConsumer.js +186 -20
- package/dist/dashboard.js +47 -9
- package/dist/dispatch.js +8 -2
- package/dist/distillAdmission.d.ts +13 -0
- package/dist/distillAdmission.js +35 -0
- package/dist/distillObserver.js +4 -6
- package/dist/distillPrimitives.d.ts +11 -12
- package/dist/distillPrimitives.js +115 -21
- package/dist/doctor.js +120 -11
- package/dist/identityHome.d.ts +9 -0
- package/dist/identityHome.js +47 -0
- package/dist/index.d.ts +70 -40
- package/dist/index.js +586 -200
- package/dist/learningTrace.d.ts +15 -0
- package/dist/learningTrace.js +73 -0
- package/dist/lifecycle.d.ts +67 -1
- package/dist/lifecycle.js +738 -44
- package/dist/localMemoryGraph.d.ts +90 -3
- package/dist/localMemoryGraph.js +2031 -231
- package/dist/login.d.ts +1 -1
- package/dist/login.js +3 -3
- package/dist/materialPackage.js +3 -6
- package/dist/materialSnapshot.d.ts +9 -1
- package/dist/materialSnapshot.js +23 -6
- package/dist/memoryGraphOps.d.ts +8 -0
- package/dist/memoryGraphOps.js +140 -0
- package/dist/migrate/assetFormatMap.d.ts +61 -0
- package/dist/migrate/assetFormatMap.js +53 -0
- package/dist/migrate/envTranslate.d.ts +26 -0
- package/dist/migrate/envTranslate.js +147 -0
- package/dist/migrate/fieldMap.d.ts +4 -2
- package/dist/migrate/fieldMap.js +9 -5
- package/dist/migrate/oauthImport.d.ts +66 -0
- package/dist/migrate/oauthImport.js +667 -0
- package/dist/migrate/v1Import.d.ts +92 -1
- package/dist/migrate/v1Import.js +1481 -141
- package/dist/promptRecallHook.d.ts +24 -0
- package/dist/promptRecallHook.js +425 -0
- package/dist/recallVerifyReport.d.ts +37 -0
- package/dist/recallVerifyReport.js +244 -0
- package/dist/recipe.d.ts +7 -1
- package/dist/recipe.js +426 -56
- package/dist/requiredSandboxValidation.d.ts +5 -0
- package/dist/requiredSandboxValidation.js +4 -0
- package/dist/reuse.d.ts +9 -0
- package/dist/reuse.js +159 -58
- package/dist/runtimeCapabilities.js +15 -15
- package/dist/runtimeSessionSource.d.ts +3 -2
- package/dist/runtimeSessionSource.js +63 -11
- package/dist/selectionPolicyConfig.d.ts +8 -0
- package/dist/selectionPolicyConfig.js +18 -0
- package/dist/semanticIdfConfig.d.ts +2 -0
- package/dist/semanticIdfConfig.js +4 -0
- package/dist/sessionIngest.d.ts +37 -0
- package/dist/sessionIngest.js +156 -0
- package/dist/setupHooks.js +95 -1
- package/dist/skill2gep.d.ts +13 -9
- package/dist/skill2gep.js +42 -30
- package/dist/skillDistill.d.ts +8 -4
- package/dist/skillDistill.js +38 -9
- package/dist/solo/mode.js +1 -0
- package/dist/sync.d.ts +12 -0
- package/dist/sync.js +1246 -151
- package/dist/thesis.d.ts +1 -1
- package/dist/thesis.js +20 -3
- package/dist/trajectoryExport.js +21 -3
- package/dist/v1Compat.d.ts +1 -0
- package/dist/v1Compat.js +9 -0
- package/dist/workflowRuntime.js +24 -18
- package/package.json +11 -8
package/dist/localMemoryGraph.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, realpathSync, renameSync, statSync, unlinkSync, writeSync, } from 'node:fs';
|
|
2
|
+
import { closeSync, constants, existsSync, fstatSync, ftruncateSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, realpathSync, renameSync, rmdirSync, statSync, unlinkSync, writeSync, } from 'node:fs';
|
|
3
3
|
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
4
|
import { userInfo } from 'node:os';
|
|
5
5
|
import { gzipSync, gunzipSync } from 'node:zlib';
|
|
@@ -8,8 +8,18 @@ const ACTIVE_FILE = 'memory_graph.v2.jsonl';
|
|
|
8
8
|
const COMPACT_FILE = 'memory_graph.compact.jsonl';
|
|
9
9
|
const LOCK_FILE = 'memory_graph.lock';
|
|
10
10
|
const RECOVERY_FILE = 'memory_graph.recovery.json';
|
|
11
|
+
const EPOCH_FILE = 'memory_graph.epoch.json';
|
|
12
|
+
const ROTATION_JOURNAL_FILE = 'memory_graph.rotation.json';
|
|
11
13
|
const ARCHIVE_PATTERN = /^memory_graph\.v2\.(\d{13})\.jsonl\.gz$/;
|
|
14
|
+
const ROTATION_GENERATION_PATTERN = /^\d{13}$/;
|
|
15
|
+
const ROTATION_TRANSACTION_PATTERN = /^txn_[a-f0-9]{64}$/;
|
|
16
|
+
const ROTATION_STAGE_PATTERN = /^memory_graph\.rotation\.(\d{13})\.(compact|archive|active)\.stage$/;
|
|
17
|
+
const ROTATION_TEMP_PATTERN = /^\.(?:memory_graph\.rotation\.json|memory_graph\.rotation\.(\d{13})\.(compact|archive|active)\.stage)\.(\d{13})\.tmp$/;
|
|
18
|
+
const RESET_BACKUP_PATTERN = /^memory_graph\.reset\.(\d{13,})$/;
|
|
19
|
+
const RESET_PENDING_PATTERN = /^memory_graph\.reset\.pending\.(\d{13,})$/;
|
|
20
|
+
const LEGACY_EPOCH_ID = 'legacy';
|
|
12
21
|
const DEFAULT_MAX_COMPACT_BYTES = 2 * 1024 * 1024;
|
|
22
|
+
const MAX_ROTATION_JOURNAL_BYTES = 64 * 1024;
|
|
13
23
|
export function resolveLocalMemoryUserId(info = userInfo()) {
|
|
14
24
|
if (Number.isInteger(info.uid) && info.uid >= 0)
|
|
15
25
|
return String(info.uid);
|
|
@@ -29,6 +39,7 @@ export class MemoryGraphImportStateRejectedError extends Error {
|
|
|
29
39
|
this.name = 'MemoryGraphImportStateRejectedError';
|
|
30
40
|
}
|
|
31
41
|
}
|
|
42
|
+
const memoryGraphV1OutcomePlans = new WeakMap();
|
|
32
43
|
export class MemoryGraphBusyError extends Error {
|
|
33
44
|
constructor() {
|
|
34
45
|
super('memory_graph_busy');
|
|
@@ -46,7 +57,9 @@ export class LocalMemoryGraph {
|
|
|
46
57
|
maxCompactBytes;
|
|
47
58
|
maxCompactEdges;
|
|
48
59
|
archiveRetention;
|
|
60
|
+
onRotationPhase;
|
|
49
61
|
importedFingerprints = new Map();
|
|
62
|
+
rotationCleanupFailed = false;
|
|
50
63
|
constructor(options) {
|
|
51
64
|
this.dir = resolve(options.dir);
|
|
52
65
|
this.userScope = scopeHash(`user:${options.userId}`);
|
|
@@ -61,6 +74,7 @@ export class LocalMemoryGraph {
|
|
|
61
74
|
this.maxCompactBytes = positiveInt(options.maxCompactBytes, DEFAULT_MAX_COMPACT_BYTES);
|
|
62
75
|
this.maxCompactEdges = positiveInt(options.maxCompactEdges, 4096);
|
|
63
76
|
this.archiveRetention = positiveInt(options.archiveRetention, 3);
|
|
77
|
+
this.onRotationPhase = options.onRotationPhase;
|
|
64
78
|
}
|
|
65
79
|
query(input) {
|
|
66
80
|
const diagnostics = emptyDiagnostics();
|
|
@@ -80,6 +94,8 @@ export class LocalMemoryGraph {
|
|
|
80
94
|
}
|
|
81
95
|
return true;
|
|
82
96
|
});
|
|
97
|
+
if (this.rotationCleanupFailed)
|
|
98
|
+
diagnostics.recovery = 'degraded';
|
|
83
99
|
if (records.length === 0 && diagnostics.recovery === 'healthy')
|
|
84
100
|
diagnostics.recovery = 'empty';
|
|
85
101
|
return algo.deriveMemoryGraphAdvice(records, input.signals, this.now(), diagnostics);
|
|
@@ -126,55 +142,149 @@ export class LocalMemoryGraph {
|
|
|
126
142
|
}
|
|
127
143
|
importV1Outcome(workspace, raw, source = 'legacy-memory-graph') {
|
|
128
144
|
const workspaceScope = this.workspaceScope(workspace);
|
|
145
|
+
if (!workspaceScope)
|
|
146
|
+
return false;
|
|
129
147
|
const sourceScope = scopeHash(`source:${source}`);
|
|
130
148
|
const parsed = parseV1Outcome(raw, workspaceScope, this.userScope, sourceScope);
|
|
131
149
|
if (!parsed)
|
|
132
150
|
return false;
|
|
133
151
|
return this.withGraphLock(() => {
|
|
134
152
|
const dedupeScope = `${workspaceScope}\u0000${this.userScope}\u0000${sourceScope}`;
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
if (!cache || cache.stateFingerprint !== stateFingerprint) {
|
|
138
|
-
const values = new Set();
|
|
139
|
-
for (const record of this.readImportRecords()) {
|
|
140
|
-
if (record.workspaceScope !== workspaceScope || record.userScope !== this.userScope)
|
|
141
|
-
continue;
|
|
142
|
-
if (record.sourceScope && record.sourceScope !== sourceScope)
|
|
143
|
-
continue;
|
|
144
|
-
if (record.sourceFingerprint)
|
|
145
|
-
values.add(record.sourceFingerprint);
|
|
146
|
-
if (record.legacySourceFingerprint)
|
|
147
|
-
values.add(record.legacySourceFingerprint);
|
|
148
|
-
}
|
|
149
|
-
cache = { stateFingerprint, values };
|
|
150
|
-
this.importedFingerprints.set(dedupeScope, cache);
|
|
151
|
-
}
|
|
152
|
-
if ((parsed.sourceFingerprint && cache.values.has(parsed.sourceFingerprint))
|
|
153
|
-
|| (parsed.legacySourceFingerprint && cache.values.has(parsed.legacySourceFingerprint)))
|
|
153
|
+
const cache = this.importFingerprintCache(dedupeScope, workspaceScope, sourceScope);
|
|
154
|
+
if (hasImportFingerprint(cache.values, parsed))
|
|
154
155
|
return false;
|
|
155
156
|
if (!this.appendRecordUnlocked(parsed))
|
|
156
157
|
return false;
|
|
157
|
-
|
|
158
|
-
cache.values.add(parsed.sourceFingerprint);
|
|
159
|
-
if (parsed.legacySourceFingerprint)
|
|
160
|
-
cache.values.add(parsed.legacySourceFingerprint);
|
|
158
|
+
addImportFingerprints(cache.values, parsed);
|
|
161
159
|
cache.stateFingerprint = this.importStateFingerprint();
|
|
162
160
|
return true;
|
|
163
161
|
});
|
|
164
162
|
}
|
|
163
|
+
/** Builds a stable import forecast without creating or locking the target graph. */
|
|
164
|
+
planV1Outcomes(workspace, raws, source = 'legacy-memory-graph') {
|
|
165
|
+
const total = raws.length;
|
|
166
|
+
const sourceScope = scopeHash(`source:${source}`);
|
|
167
|
+
const workspacePath = workspace ? resolve(workspace) : null;
|
|
168
|
+
const workspaceScope = workspacePath ? this.workspaceScope(workspacePath) : null;
|
|
169
|
+
if (!workspacePath || !workspaceScope) {
|
|
170
|
+
return sealV1OutcomePlan({ total, importable: 0, duplicates: 0, rejected: 0, deferred: total }, {
|
|
171
|
+
graphDir: this.dir,
|
|
172
|
+
userScope: this.userScope,
|
|
173
|
+
workspacePath: null,
|
|
174
|
+
workspaceScope: null,
|
|
175
|
+
sourceScope,
|
|
176
|
+
records: Object.freeze([]),
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const target = this.readStableImportState();
|
|
180
|
+
const fingerprints = collectImportFingerprints(target.records, workspaceScope, this.userScope, sourceScope);
|
|
181
|
+
const records = [];
|
|
182
|
+
let importable = 0;
|
|
183
|
+
let duplicates = 0;
|
|
184
|
+
let rejected = 0;
|
|
185
|
+
for (const raw of raws) {
|
|
186
|
+
const parsed = parseV1Outcome(raw, workspaceScope, this.userScope, sourceScope);
|
|
187
|
+
if (!parsed) {
|
|
188
|
+
rejected += 1;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const normalized = { ...parsed, signals: [...parsed.signals] };
|
|
192
|
+
Object.freeze(normalized.signals);
|
|
193
|
+
Object.freeze(normalized);
|
|
194
|
+
if (hasImportFingerprint(fingerprints, parsed)) {
|
|
195
|
+
duplicates += 1;
|
|
196
|
+
records.push(normalized);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (!this.importRecordFits(parsed, target.epochId)) {
|
|
200
|
+
rejected += 1;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
records.push(normalized);
|
|
204
|
+
addImportFingerprints(fingerprints, normalized);
|
|
205
|
+
importable += 1;
|
|
206
|
+
}
|
|
207
|
+
Object.freeze(records);
|
|
208
|
+
return sealV1OutcomePlan({
|
|
209
|
+
total,
|
|
210
|
+
importable,
|
|
211
|
+
duplicates,
|
|
212
|
+
rejected,
|
|
213
|
+
deferred: 0,
|
|
214
|
+
}, {
|
|
215
|
+
graphDir: this.dir,
|
|
216
|
+
userScope: this.userScope,
|
|
217
|
+
workspacePath,
|
|
218
|
+
workspaceScope,
|
|
219
|
+
sourceScope,
|
|
220
|
+
records,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/** Applies only the normalized records sealed by planV1Outcomes. */
|
|
224
|
+
applyV1OutcomePlan(plan) {
|
|
225
|
+
const data = memoryGraphV1OutcomePlans.get(plan);
|
|
226
|
+
if (!data || data.graphDir !== this.dir || data.userScope !== this.userScope) {
|
|
227
|
+
throw new Error('memory_graph_import_plan_rejected');
|
|
228
|
+
}
|
|
229
|
+
if (data.records.length === 0)
|
|
230
|
+
return 0;
|
|
231
|
+
const workspacePath = data.workspacePath;
|
|
232
|
+
const workspaceScope = data.workspaceScope;
|
|
233
|
+
if (!workspacePath || !workspaceScope
|
|
234
|
+
|| this.workspaceScope(workspacePath) !== workspaceScope) {
|
|
235
|
+
throw new Error('memory_graph_import_plan_rejected');
|
|
236
|
+
}
|
|
237
|
+
let committedImported;
|
|
238
|
+
try {
|
|
239
|
+
return this.withGraphLock(() => {
|
|
240
|
+
const dedupeScope = `${workspaceScope}\u0000${this.userScope}\u0000${data.sourceScope}`;
|
|
241
|
+
const cache = this.importFingerprintCache(dedupeScope, workspaceScope, data.sourceScope);
|
|
242
|
+
let imported = 0;
|
|
243
|
+
for (const record of data.records) {
|
|
244
|
+
if (hasImportFingerprint(cache.values, record))
|
|
245
|
+
continue;
|
|
246
|
+
if (!this.appendRecordUnlocked(record))
|
|
247
|
+
continue;
|
|
248
|
+
addImportFingerprints(cache.values, record);
|
|
249
|
+
imported += 1;
|
|
250
|
+
}
|
|
251
|
+
cache.stateFingerprint = this.importStateFingerprint();
|
|
252
|
+
committedImported = imported;
|
|
253
|
+
return imported;
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
// The completed appends are durable, so a cleanup-only failure must not invite replay.
|
|
258
|
+
if (committedImported !== undefined && committedImported > 0
|
|
259
|
+
&& error instanceof util.LockReleaseError)
|
|
260
|
+
return committedImported;
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
165
264
|
maintain() {
|
|
166
|
-
return this.withGraphLock(() => this.maintainUnlocked());
|
|
265
|
+
return this.withGraphLock(() => this.withRotationCleanupStatus(this.maintainUnlocked()));
|
|
167
266
|
}
|
|
168
267
|
maintainUnlocked() {
|
|
169
268
|
this.ensureSecureDir();
|
|
269
|
+
const state = this.managedGraphStateFiles();
|
|
270
|
+
const epoch = this.readEpochState();
|
|
170
271
|
const health = this.inspectHealthUnlocked();
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
272
|
+
const recoveryDegraded = this.recoveryMarkerState(epoch) === 'degraded';
|
|
273
|
+
if ((health.archives > 0 || recoveryDegraded) && this.compactRequiresRecovery(epoch)) {
|
|
274
|
+
const recovered = this.recoverFromArchivesUnlocked(epoch);
|
|
275
|
+
if (recovered.recovery === 'recovered' || recovered.recovery === 'degraded'
|
|
276
|
+
|| (recovered.recovery === 'empty' && health.activeRecords === 0))
|
|
174
277
|
return recovered;
|
|
175
278
|
}
|
|
176
|
-
const
|
|
177
|
-
|
|
279
|
+
const activeState = state.find((file) => file.name === ACTIVE_FILE);
|
|
280
|
+
const activeBaseline = epoch.baseline?.active;
|
|
281
|
+
const activeBaselineTruncated = Boolean(activeState && activeBaseline
|
|
282
|
+
&& serializedIdentityMatches(activeBaseline.snapshot, activeState.identity)
|
|
283
|
+
&& activeState.identity.size < BigInt(activeBaseline.offset));
|
|
284
|
+
const active = activeBaselineTruncated
|
|
285
|
+
? null
|
|
286
|
+
: this.activePayloadForEpoch(epoch, this.maxActiveBytes);
|
|
287
|
+
if (active === null || !active.exists || active.logicalSize < this.maxActiveBytes) {
|
|
178
288
|
return {
|
|
179
289
|
rotated: false,
|
|
180
290
|
compactedRecords: health.compactedRecords,
|
|
@@ -184,254 +294,1465 @@ export class LocalMemoryGraph {
|
|
|
184
294
|
recovery: health.recovery,
|
|
185
295
|
};
|
|
186
296
|
}
|
|
187
|
-
return this.rotateAndCompactUnlocked();
|
|
297
|
+
return this.rotateAndCompactUnlocked(epoch);
|
|
188
298
|
}
|
|
189
299
|
recoverFromArchives() {
|
|
190
|
-
return this.withGraphLock(() => this.recoverFromArchivesUnlocked());
|
|
300
|
+
return this.withGraphLock(() => this.withRotationCleanupStatus(this.recoverFromArchivesUnlocked()));
|
|
301
|
+
}
|
|
302
|
+
/** Enforce archive retention without changing active or compact state. */
|
|
303
|
+
prune() {
|
|
304
|
+
return this.withGraphLock(() => {
|
|
305
|
+
this.ensureSecureDir();
|
|
306
|
+
this.managedGraphStateFiles();
|
|
307
|
+
this.readEpochState();
|
|
308
|
+
this.pruneArchives();
|
|
309
|
+
const health = this.inspectHealthUnlocked();
|
|
310
|
+
return this.withRotationCleanupStatus({
|
|
311
|
+
rotated: false,
|
|
312
|
+
compactedRecords: health.compactedRecords,
|
|
313
|
+
corruptLines: health.corruptLines,
|
|
314
|
+
oversizedLines: health.oversizedLines,
|
|
315
|
+
archives: health.archives,
|
|
316
|
+
recovery: health.recovery,
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Copy every managed graph file into a non-active backup, then atomically
|
|
322
|
+
* advance the local storage epoch.
|
|
323
|
+
* The CLI requires explicit opt-in (`--yes`) before calling this method.
|
|
324
|
+
*/
|
|
325
|
+
resetGraph() {
|
|
326
|
+
let committed;
|
|
327
|
+
try {
|
|
328
|
+
return this.withGraphLock(() => {
|
|
329
|
+
this.ensureSecureDir();
|
|
330
|
+
this.managedGraphStateFiles();
|
|
331
|
+
this.readEpochState();
|
|
332
|
+
this.ensureEpochStateFile();
|
|
333
|
+
const state = this.managedGraphStateFiles();
|
|
334
|
+
const backup = this.createResetBackupDirectory();
|
|
335
|
+
const copied = [];
|
|
336
|
+
try {
|
|
337
|
+
for (const file of state) {
|
|
338
|
+
const payload = this.readResetSource(file);
|
|
339
|
+
const destination = join(backup.pendingDir, file.name);
|
|
340
|
+
this.writeAtomic(destination, payload);
|
|
341
|
+
const copiedIdentity = lstatSync(destination, { bigint: true });
|
|
342
|
+
const copiedPayload = this.readRawBounded(destination, payload.length);
|
|
343
|
+
if (!copiedIdentity.isFile() || copiedIdentity.isSymbolicLink()
|
|
344
|
+
|| copiedPayload === null || !copiedPayload.equals(payload)) {
|
|
345
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
346
|
+
}
|
|
347
|
+
copied.push({ name: file.name, path: destination, identity: copiedIdentity });
|
|
348
|
+
}
|
|
349
|
+
this.assertManagedStateUnchanged(state);
|
|
350
|
+
this.publishResetBackup(backup);
|
|
351
|
+
this.assertManagedStateUnchanged(state);
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
this.cleanupResetPendingDirectory(backup, copied);
|
|
355
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
356
|
+
}
|
|
357
|
+
const epochState = {
|
|
358
|
+
version: 1,
|
|
359
|
+
epochId: backup.backupId,
|
|
360
|
+
activatedAt: new Date(this.now()).toISOString(),
|
|
361
|
+
baseline: this.epochBaselineFromState(state),
|
|
362
|
+
};
|
|
363
|
+
const report = {
|
|
364
|
+
rotated: false,
|
|
365
|
+
compactedRecords: 0,
|
|
366
|
+
corruptLines: 0,
|
|
367
|
+
oversizedLines: 0,
|
|
368
|
+
archives: state.filter((file) => ARCHIVE_PATTERN.test(file.name)).length,
|
|
369
|
+
recovery: 'empty',
|
|
370
|
+
backupId: backup.backupId,
|
|
371
|
+
backupFiles: copied.length,
|
|
372
|
+
epochId: backup.backupId,
|
|
373
|
+
};
|
|
374
|
+
if (this.rotationCleanupFailed)
|
|
375
|
+
report.recovery = 'degraded';
|
|
376
|
+
try {
|
|
377
|
+
this.writeEpochState(epochState);
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
// The completed backup is intentionally retained. Until this atomic
|
|
381
|
+
// publish succeeds, readers continue using the previous epoch.
|
|
382
|
+
throw new Error('memory_graph_reset_failed');
|
|
383
|
+
}
|
|
384
|
+
committed = report;
|
|
385
|
+
this.importedFingerprints.clear();
|
|
386
|
+
return committed;
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
if (committed) {
|
|
391
|
+
const reason = error instanceof util.LockReleaseError
|
|
392
|
+
? error.reason
|
|
393
|
+
: 'release_failed';
|
|
394
|
+
return { ...committed, lockReleaseWarning: reason };
|
|
395
|
+
}
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
managedGraphStateFiles() {
|
|
400
|
+
const names = [
|
|
401
|
+
...this.archiveFiles(),
|
|
402
|
+
RECOVERY_FILE,
|
|
403
|
+
EPOCH_FILE,
|
|
404
|
+
ACTIVE_FILE,
|
|
405
|
+
COMPACT_FILE,
|
|
406
|
+
];
|
|
407
|
+
const state = [];
|
|
408
|
+
for (const name of names) {
|
|
409
|
+
const path = join(this.dir, name);
|
|
410
|
+
let identity;
|
|
411
|
+
try {
|
|
412
|
+
identity = lstatSync(path, { bigint: true });
|
|
413
|
+
}
|
|
414
|
+
catch (error) {
|
|
415
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
416
|
+
continue;
|
|
417
|
+
throw new Error('memory_graph_path_rejected');
|
|
418
|
+
}
|
|
419
|
+
if (!identity.isFile() || identity.isSymbolicLink())
|
|
420
|
+
throw new Error('memory_graph_path_rejected');
|
|
421
|
+
state.push({ name, path, identity });
|
|
422
|
+
}
|
|
423
|
+
return state;
|
|
424
|
+
}
|
|
425
|
+
createResetBackupDirectory() {
|
|
426
|
+
const latest = readdirSync(this.dir)
|
|
427
|
+
.map((name) => BigInt(RESET_BACKUP_PATTERN.exec(name)?.[1]
|
|
428
|
+
?? RESET_PENDING_PATTERN.exec(name)?.[1]
|
|
429
|
+
?? 0))
|
|
430
|
+
.reduce((max, value) => value > max ? value : max, 0n);
|
|
431
|
+
const now = BigInt(Math.max(0, Math.floor(this.now())));
|
|
432
|
+
const timestamp = now > latest ? now : latest + 1n;
|
|
433
|
+
const backupId = timestamp.toString().padStart(13, '0');
|
|
434
|
+
const backupDir = join(this.dir, `memory_graph.reset.${backupId}`);
|
|
435
|
+
const pendingDir = join(this.dir, `memory_graph.reset.pending.${backupId}`);
|
|
436
|
+
let created = false;
|
|
437
|
+
try {
|
|
438
|
+
assertPathMissing(backupDir, 'memory_graph_reset_backup_failed');
|
|
439
|
+
assertPathMissing(pendingDir, 'memory_graph_reset_backup_failed');
|
|
440
|
+
mkdirSync(pendingDir, { mode: 0o700 });
|
|
441
|
+
created = true;
|
|
442
|
+
const pendingIdentity = lstatSync(pendingDir, { bigint: true });
|
|
443
|
+
if (!pendingIdentity.isDirectory() || pendingIdentity.isSymbolicLink()) {
|
|
444
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
445
|
+
}
|
|
446
|
+
return { backupId, backupDir, pendingDir, pendingIdentity };
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
if (created) {
|
|
450
|
+
try {
|
|
451
|
+
rmdirSync(pendingDir);
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
// Leave an unexpected directory untouched for operator inspection.
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
publishResetBackup(backup) {
|
|
461
|
+
const identity = lstatSync(backup.pendingDir, { bigint: true });
|
|
462
|
+
if (!identity.isDirectory() || identity.isSymbolicLink()
|
|
463
|
+
|| !sameGraphFileIdentity(backup.pendingIdentity, identity)) {
|
|
464
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
465
|
+
}
|
|
466
|
+
assertPathMissing(backup.backupDir, 'memory_graph_reset_backup_failed');
|
|
467
|
+
renameSync(backup.pendingDir, backup.backupDir);
|
|
468
|
+
const published = lstatSync(backup.backupDir, { bigint: true });
|
|
469
|
+
if (!published.isDirectory() || published.isSymbolicLink()
|
|
470
|
+
|| !sameGraphFileIdentity(backup.pendingIdentity, published)) {
|
|
471
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
cleanupResetPendingDirectory(backup, copied) {
|
|
475
|
+
for (const file of [...copied].reverse()) {
|
|
476
|
+
try {
|
|
477
|
+
const current = lstatSync(file.path, { bigint: true });
|
|
478
|
+
if (current.isFile() && !current.isSymbolicLink()
|
|
479
|
+
&& sameGraphFileIdentity(file.identity, current))
|
|
480
|
+
unlinkSync(file.path);
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
// Live graph state was never changed; leave uncertain backup artifacts untouched.
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
try {
|
|
487
|
+
const current = lstatSync(backup.pendingDir, { bigint: true });
|
|
488
|
+
if (current.isDirectory() && !current.isSymbolicLink()
|
|
489
|
+
&& sameGraphFileIdentity(backup.pendingIdentity, current)
|
|
490
|
+
&& readdirSync(backup.pendingDir).length === 0)
|
|
491
|
+
rmdirSync(backup.pendingDir);
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
// A completed rename or an uncertain replacement must remain untouched.
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
readResetSource(file) {
|
|
498
|
+
const limit = file.name === ACTIVE_FILE
|
|
499
|
+
? this.maxActiveBytes + this.maxLineBytes
|
|
500
|
+
: file.name === COMPACT_FILE
|
|
501
|
+
? this.maxCompactBytes + this.maxLineBytes
|
|
502
|
+
: file.name === RECOVERY_FILE || file.name === EPOCH_FILE
|
|
503
|
+
? this.maxLineBytes
|
|
504
|
+
: this.maxActiveBytes + this.maxLineBytes;
|
|
505
|
+
if (file.identity.size > BigInt(limit))
|
|
506
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
507
|
+
const fd = openNoFollow(file.path, constants.O_RDONLY, 0o600);
|
|
508
|
+
try {
|
|
509
|
+
const before = fstatSync(fd, { bigint: true });
|
|
510
|
+
if (!before.isFile() || before.isSymbolicLink()
|
|
511
|
+
|| !sameGraphFileSnapshot(file.identity, before)
|
|
512
|
+
|| before.size > BigInt(limit))
|
|
513
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
514
|
+
const payload = readFdBytes(fd, Number(before.size), 0);
|
|
515
|
+
const after = fstatSync(fd, { bigint: true });
|
|
516
|
+
if (payload.length !== Number(before.size)
|
|
517
|
+
|| !sameGraphFileSnapshot(before, after))
|
|
518
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
519
|
+
return payload;
|
|
520
|
+
}
|
|
521
|
+
finally {
|
|
522
|
+
closeSync(fd);
|
|
523
|
+
}
|
|
191
524
|
}
|
|
192
|
-
|
|
525
|
+
assertManagedStateUnchanged(expected) {
|
|
526
|
+
const current = this.managedGraphStateFiles();
|
|
527
|
+
if (current.length !== expected.length)
|
|
528
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
529
|
+
for (let index = 0; index < expected.length; index += 1) {
|
|
530
|
+
const before = expected[index];
|
|
531
|
+
const after = current[index];
|
|
532
|
+
if (!before || !after || before.name !== after.name
|
|
533
|
+
|| !sameGraphFileSnapshot(before.identity, after.identity)) {
|
|
534
|
+
throw new Error('memory_graph_reset_backup_failed');
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
ensureEpochStateFile() {
|
|
539
|
+
const path = join(this.dir, EPOCH_FILE);
|
|
540
|
+
try {
|
|
541
|
+
lstatSync(path);
|
|
542
|
+
this.readEpochState();
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
catch (error) {
|
|
546
|
+
if (!isObject(error) || error['code'] !== 'ENOENT') {
|
|
547
|
+
if (error instanceof Error && error.message === 'memory_graph_epoch_rejected')
|
|
548
|
+
throw error;
|
|
549
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (this.hasResetBackup())
|
|
553
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
554
|
+
this.writeEpochState({
|
|
555
|
+
version: 1,
|
|
556
|
+
epochId: LEGACY_EPOCH_ID,
|
|
557
|
+
activatedAt: new Date(this.now()).toISOString(),
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
currentEpochId() {
|
|
561
|
+
return this.readEpochState().epochId;
|
|
562
|
+
}
|
|
563
|
+
epochBaselineFromState(state) {
|
|
564
|
+
const active = state.find((file) => file.name === ACTIVE_FILE);
|
|
565
|
+
const compact = state.find((file) => file.name === COMPACT_FILE);
|
|
566
|
+
const recovery = state.find((file) => file.name === RECOVERY_FILE);
|
|
567
|
+
const archives = state
|
|
568
|
+
.filter((file) => ARCHIVE_PATTERN.test(file.name))
|
|
569
|
+
.slice(-this.archiveRetention)
|
|
570
|
+
.map((file) => ({ name: file.name, snapshot: serializeGraphFileSnapshot(file.identity) }));
|
|
571
|
+
if (active && active.identity.size > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
572
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
573
|
+
}
|
|
574
|
+
return {
|
|
575
|
+
active: active
|
|
576
|
+
? { snapshot: serializeGraphFileSnapshot(active.identity), offset: Number(active.identity.size) }
|
|
577
|
+
: null,
|
|
578
|
+
compact: compact ? serializeGraphFileSnapshot(compact.identity) : null,
|
|
579
|
+
recovery: recovery ? serializeGraphFileSnapshot(recovery.identity) : null,
|
|
580
|
+
archives,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
readEpochState() {
|
|
584
|
+
const path = join(this.dir, EPOCH_FILE);
|
|
585
|
+
let identity;
|
|
586
|
+
try {
|
|
587
|
+
identity = lstatSync(path, { bigint: true });
|
|
588
|
+
}
|
|
589
|
+
catch (error) {
|
|
590
|
+
if (isObject(error) && error['code'] === 'ENOENT') {
|
|
591
|
+
if (this.hasResetBackup())
|
|
592
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
593
|
+
return { version: 1, epochId: LEGACY_EPOCH_ID, activatedAt: new Date(0).toISOString() };
|
|
594
|
+
}
|
|
595
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
596
|
+
}
|
|
597
|
+
if (!identity.isFile() || identity.isSymbolicLink()
|
|
598
|
+
|| identity.size > BigInt(this.maxLineBytes))
|
|
599
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
600
|
+
let fd;
|
|
601
|
+
try {
|
|
602
|
+
fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
603
|
+
}
|
|
604
|
+
catch {
|
|
605
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
606
|
+
}
|
|
607
|
+
try {
|
|
608
|
+
const before = fstatSync(fd, { bigint: true });
|
|
609
|
+
if (!before.isFile() || before.isSymbolicLink()
|
|
610
|
+
|| !sameGraphFileSnapshot(identity, before))
|
|
611
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
612
|
+
const payload = readFdBytes(fd, Number(before.size), 0);
|
|
613
|
+
const after = fstatSync(fd, { bigint: true });
|
|
614
|
+
if (payload.length !== Number(before.size)
|
|
615
|
+
|| !sameGraphFileSnapshot(before, after))
|
|
616
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
617
|
+
const raw = JSON.parse(payload.toString('utf8'));
|
|
618
|
+
if (!isObject(raw) || raw['version'] !== 1)
|
|
619
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
620
|
+
const epochId = safeEpochId(raw['epochId']);
|
|
621
|
+
const activatedAt = typeof raw['activatedAt'] === 'string' ? validIso(raw['activatedAt']) : null;
|
|
622
|
+
if (!epochId || !activatedAt)
|
|
623
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
624
|
+
const hasBaseline = Object.prototype.hasOwnProperty.call(raw, 'baseline');
|
|
625
|
+
const baseline = hasBaseline ? parseEpochBaseline(raw['baseline']) : null;
|
|
626
|
+
if (hasBaseline && !baseline)
|
|
627
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
628
|
+
if (epochId !== LEGACY_EPOCH_ID) {
|
|
629
|
+
if (!/^\d{13,}$/.test(epochId))
|
|
630
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
631
|
+
let backup;
|
|
632
|
+
try {
|
|
633
|
+
backup = lstatSync(join(this.dir, `memory_graph.reset.${epochId}`));
|
|
634
|
+
}
|
|
635
|
+
catch {
|
|
636
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
637
|
+
}
|
|
638
|
+
if (!backup.isDirectory() || backup.isSymbolicLink()) {
|
|
639
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return {
|
|
643
|
+
version: 1,
|
|
644
|
+
epochId,
|
|
645
|
+
activatedAt,
|
|
646
|
+
...(baseline ? { baseline } : {}),
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
catch {
|
|
650
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
651
|
+
}
|
|
652
|
+
finally {
|
|
653
|
+
closeSync(fd);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
writeEpochState(state) {
|
|
657
|
+
const payload = Buffer.from(JSON.stringify(state) + '\n', 'utf8');
|
|
658
|
+
if (payload.length > this.maxLineBytes)
|
|
659
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
660
|
+
this.writeAtomic(join(this.dir, EPOCH_FILE), payload);
|
|
661
|
+
}
|
|
662
|
+
hasResetBackup() {
|
|
663
|
+
return readdirSync(this.dir).some((name) => RESET_BACKUP_PATTERN.test(name));
|
|
664
|
+
}
|
|
665
|
+
compactMatchesEpochBaseline(epoch) {
|
|
666
|
+
const baseline = epoch.baseline?.compact;
|
|
667
|
+
if (!baseline)
|
|
668
|
+
return false;
|
|
669
|
+
try {
|
|
670
|
+
const current = lstatSync(join(this.dir, COMPACT_FILE), { bigint: true });
|
|
671
|
+
return current.isFile() && !current.isSymbolicLink()
|
|
672
|
+
&& serializedSnapshotMatches(baseline, current);
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
return false;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
readCompactForEpoch(epoch, diagnostics) {
|
|
679
|
+
return this.compactMatchesEpochBaseline(epoch) ? [] : this.readCompact(diagnostics);
|
|
680
|
+
}
|
|
681
|
+
activeLogicalWindow(epoch, identity) {
|
|
682
|
+
const active = epoch.baseline?.active;
|
|
683
|
+
if (!active || !serializedIdentityMatches(active.snapshot, identity)) {
|
|
684
|
+
return {
|
|
685
|
+
offset: 0,
|
|
686
|
+
size: identity.size > BigInt(Number.MAX_SAFE_INTEGER) ? 0 : Number(identity.size),
|
|
687
|
+
invalid: identity.size > BigInt(Number.MAX_SAFE_INTEGER),
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
const offset = active.offset;
|
|
691
|
+
if (identity.size < BigInt(offset) || identity.size > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
692
|
+
return { offset, size: 0, invalid: true };
|
|
693
|
+
}
|
|
694
|
+
return { offset, size: Number(identity.size) - offset, invalid: false };
|
|
695
|
+
}
|
|
696
|
+
activePayloadForEpoch(epoch, maxBytes) {
|
|
697
|
+
const path = join(this.dir, ACTIVE_FILE);
|
|
698
|
+
let identity;
|
|
699
|
+
try {
|
|
700
|
+
identity = lstatSync(path, { bigint: true });
|
|
701
|
+
}
|
|
702
|
+
catch (error) {
|
|
703
|
+
if (isObject(error) && error['code'] === 'ENOENT') {
|
|
704
|
+
return { payload: Buffer.alloc(0), logicalSize: 0, exists: false };
|
|
705
|
+
}
|
|
706
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
707
|
+
}
|
|
708
|
+
if (!identity.isFile() || identity.isSymbolicLink()) {
|
|
709
|
+
throw new Error('memory_graph_path_rejected');
|
|
710
|
+
}
|
|
711
|
+
const window = this.activeLogicalWindow(epoch, identity);
|
|
712
|
+
if (window.invalid || window.size > maxBytes) {
|
|
713
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
714
|
+
}
|
|
715
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
716
|
+
try {
|
|
717
|
+
const before = fstatSync(fd, { bigint: true });
|
|
718
|
+
if (!before.isFile() || before.isSymbolicLink()
|
|
719
|
+
|| !sameGraphFileSnapshot(identity, before)) {
|
|
720
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
721
|
+
}
|
|
722
|
+
const payload = readFdBytes(fd, window.size, window.offset);
|
|
723
|
+
const after = fstatSync(fd, { bigint: true });
|
|
724
|
+
if (payload.length !== window.size || !sameGraphFileSnapshot(before, after)) {
|
|
725
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
726
|
+
}
|
|
727
|
+
return { payload, logicalSize: window.size, exists: true };
|
|
728
|
+
}
|
|
729
|
+
finally {
|
|
730
|
+
closeSync(fd);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
readActiveForEpoch(epoch, diagnostics, maxBytes) {
|
|
734
|
+
const path = join(this.dir, ACTIVE_FILE);
|
|
735
|
+
if (!existsSync(path) || !this.secureRegularFile(path))
|
|
736
|
+
return [];
|
|
737
|
+
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
738
|
+
try {
|
|
739
|
+
const identity = fstatSync(fd, { bigint: true });
|
|
740
|
+
if (!identity.isFile() || identity.isSymbolicLink())
|
|
741
|
+
return [];
|
|
742
|
+
const window = this.activeLogicalWindow(epoch, identity);
|
|
743
|
+
if (window.invalid) {
|
|
744
|
+
diagnostics.truncated = true;
|
|
745
|
+
return [];
|
|
746
|
+
}
|
|
747
|
+
const bytes = Math.min(window.size, maxBytes);
|
|
748
|
+
const position = window.offset + window.size - bytes;
|
|
749
|
+
const buffer = readFdBytes(fd, bytes, position);
|
|
750
|
+
diagnostics.bytesRead += buffer.length;
|
|
751
|
+
diagnostics.truncated ||= window.size > buffer.length;
|
|
752
|
+
if (window.size <= buffer.length)
|
|
753
|
+
return this.parseBuffer(buffer, diagnostics);
|
|
754
|
+
const newline = buffer.indexOf(0x0a);
|
|
755
|
+
return this.parseBuffer(newline >= 0 ? buffer.subarray(newline + 1) : Buffer.alloc(0), diagnostics);
|
|
756
|
+
}
|
|
757
|
+
finally {
|
|
758
|
+
closeSync(fd);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
currentArchiveFiles(epoch) {
|
|
762
|
+
const baseline = new Map((epoch.baseline?.archives ?? [])
|
|
763
|
+
.map((entry) => [entry.name, entry.snapshot]));
|
|
764
|
+
return this.archiveFiles().slice(-this.archiveRetention).filter((file) => {
|
|
765
|
+
const expected = baseline.get(file);
|
|
766
|
+
if (!expected)
|
|
767
|
+
return true;
|
|
768
|
+
try {
|
|
769
|
+
const current = lstatSync(join(this.dir, file), { bigint: true });
|
|
770
|
+
return !current.isFile() || current.isSymbolicLink()
|
|
771
|
+
|| !serializedSnapshotMatches(expected, current);
|
|
772
|
+
}
|
|
773
|
+
catch {
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
recoverFromArchivesUnlocked(epochState) {
|
|
193
779
|
this.ensureSecureDir();
|
|
780
|
+
this.managedGraphStateFiles();
|
|
781
|
+
const epoch = epochState ?? this.readEpochState();
|
|
782
|
+
const currentEpoch = epoch.epochId;
|
|
194
783
|
const diagnostics = emptyDiagnostics();
|
|
195
|
-
const compactRecords = this.
|
|
784
|
+
const compactRecords = this.readCompactForEpoch(epoch, diagnostics)
|
|
785
|
+
.filter((record) => recordEpochId(record) === currentEpoch);
|
|
196
786
|
const archiveRecords = [];
|
|
197
|
-
|
|
787
|
+
const maxArchiveBytes = gzipRotationByteBound(this.maxActiveBytes);
|
|
788
|
+
const maxArchiveOutputBytes = safeRotationByteSum(this.maxActiveBytes, this.maxLineBytes);
|
|
789
|
+
for (const file of this.currentArchiveFiles(epoch)) {
|
|
198
790
|
const path = join(this.dir, file);
|
|
199
|
-
if (
|
|
791
|
+
if (maxArchiveBytes === null || maxArchiveOutputBytes === null) {
|
|
792
|
+
diagnostics.truncated = true;
|
|
200
793
|
continue;
|
|
794
|
+
}
|
|
795
|
+
if (!this.secureRegularFile(path)) {
|
|
796
|
+
diagnostics.corruptLines += 1;
|
|
797
|
+
continue;
|
|
798
|
+
}
|
|
201
799
|
try {
|
|
202
|
-
const compressed = this.readRawBounded(path,
|
|
800
|
+
const compressed = this.readRawBounded(path, maxArchiveBytes);
|
|
203
801
|
if (compressed === null) {
|
|
204
802
|
diagnostics.truncated = true;
|
|
205
803
|
continue;
|
|
206
804
|
}
|
|
207
|
-
const raw = gunzipSync(compressed, { maxOutputLength:
|
|
208
|
-
archiveRecords.push(...this.parseBuffer(raw, diagnostics)
|
|
805
|
+
const raw = gunzipSync(compressed, { maxOutputLength: maxArchiveOutputBytes });
|
|
806
|
+
archiveRecords.push(...this.parseBuffer(raw, diagnostics)
|
|
807
|
+
.filter((record) => recordEpochId(record) === currentEpoch));
|
|
209
808
|
}
|
|
210
809
|
catch {
|
|
211
810
|
diagnostics.corruptLines += 1;
|
|
212
811
|
}
|
|
213
812
|
}
|
|
214
813
|
const compacted = mergeRecoveryRecords(compactRecords, archiveRecords, this.maxCompactEdges);
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
814
|
+
const incomplete = this.recoveryMarkerState(epoch) === 'degraded'
|
|
815
|
+
|| diagnostics.corruptLines > 0
|
|
816
|
+
|| diagnostics.oversizedLines > 0
|
|
817
|
+
|| diagnostics.truncated;
|
|
818
|
+
// Persist the conservative state before publishing a partial compact so a
|
|
819
|
+
// marker-write failure cannot leave an apparently healthy partial recovery.
|
|
820
|
+
if (incomplete)
|
|
821
|
+
this.writeRecoveryMarker(currentEpoch, 'degraded');
|
|
822
|
+
const compactedRecords = compacted.length > 0 ? this.writeCompact(compacted).records : 0;
|
|
823
|
+
const recovery = incomplete
|
|
824
|
+
|| (compacted.length > 0 && compactedRecords === 0)
|
|
825
|
+
? 'degraded'
|
|
826
|
+
: compactedRecords > 0 ? 'recovered' : 'empty';
|
|
827
|
+
if (!incomplete)
|
|
828
|
+
this.writeRecoveryMarker(currentEpoch, recovery);
|
|
218
829
|
return {
|
|
219
830
|
rotated: false,
|
|
220
831
|
compactedRecords,
|
|
221
832
|
corruptLines: diagnostics.corruptLines,
|
|
222
833
|
oversizedLines: diagnostics.oversizedLines,
|
|
223
834
|
archives: this.archiveFiles().length,
|
|
224
|
-
recovery
|
|
835
|
+
recovery,
|
|
225
836
|
};
|
|
226
837
|
}
|
|
227
838
|
inspectHealth() {
|
|
228
|
-
if (!existsSync(this.dir))
|
|
229
|
-
return emptyHealth();
|
|
230
839
|
try {
|
|
231
|
-
|
|
840
|
+
const stat = lstatSync(this.dir);
|
|
841
|
+
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
842
|
+
throw new Error('memory_graph_dir_rejected');
|
|
843
|
+
}
|
|
844
|
+
catch (error) {
|
|
845
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
846
|
+
return emptyHealth();
|
|
847
|
+
throw new Error('memory_graph_dir_rejected');
|
|
848
|
+
}
|
|
849
|
+
try {
|
|
850
|
+
return this.withGraphLock(() => {
|
|
851
|
+
const health = this.inspectHealthUnlocked();
|
|
852
|
+
return this.rotationCleanupFailed ? { ...health, recovery: 'degraded' } : health;
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
catch (error) {
|
|
856
|
+
if (error instanceof MemoryGraphBusyError) {
|
|
857
|
+
return { ...emptyHealth(), recovery: 'degraded', busy: true };
|
|
858
|
+
}
|
|
859
|
+
throw error;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
inspectHealthUnlocked() {
|
|
863
|
+
let dirStat;
|
|
864
|
+
try {
|
|
865
|
+
dirStat = lstatSync(this.dir);
|
|
866
|
+
}
|
|
867
|
+
catch (error) {
|
|
868
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
869
|
+
return emptyHealth();
|
|
870
|
+
throw new Error('memory_graph_dir_rejected');
|
|
871
|
+
}
|
|
872
|
+
if (!dirStat.isDirectory() || dirStat.isSymbolicLink())
|
|
873
|
+
throw new Error('memory_graph_dir_rejected');
|
|
874
|
+
this.managedGraphStateFiles();
|
|
875
|
+
const epoch = this.readEpochState();
|
|
876
|
+
const epochId = epoch.epochId;
|
|
877
|
+
const compactDiagnostics = emptyDiagnostics();
|
|
878
|
+
const activeDiagnostics = emptyDiagnostics();
|
|
879
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
880
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
881
|
+
const compactedRecords = this.readCompactForEpoch(epoch, compactDiagnostics)
|
|
882
|
+
.filter((record) => recordEpochId(record) === epochId).length;
|
|
883
|
+
const activeRecords = this.readActiveForEpoch(epoch, activeDiagnostics, this.maxActiveBytes)
|
|
884
|
+
.filter((record) => recordEpochId(record) === epochId).length;
|
|
885
|
+
const archives = this.archiveFiles().length;
|
|
886
|
+
let activeOversized = false;
|
|
887
|
+
if (existsSync(activePath) && this.secureRegularFile(activePath)) {
|
|
888
|
+
const activeIdentity = lstatSync(activePath, { bigint: true });
|
|
889
|
+
const window = this.activeLogicalWindow(epoch, activeIdentity);
|
|
890
|
+
activeOversized = window.invalid || window.size > this.maxActiveBytes;
|
|
891
|
+
}
|
|
892
|
+
const oversizedFiles = Number(!this.compactMatchesEpochBaseline(epoch)
|
|
893
|
+
&& fileExceeds(compactPath, this.maxCompactBytes))
|
|
894
|
+
+ Number(activeOversized);
|
|
895
|
+
const rejectedFiles = Number(existsSync(compactPath) && !this.secureRegularFile(compactPath))
|
|
896
|
+
+ Number(existsSync(activePath) && !this.secureRegularFile(activePath));
|
|
897
|
+
const corruptLines = compactDiagnostics.corruptLines + activeDiagnostics.corruptLines + rejectedFiles;
|
|
898
|
+
const oversizedLines = compactDiagnostics.oversizedLines + activeDiagnostics.oversizedLines;
|
|
899
|
+
const archiveProbe = compactedRecords === 0 && archives > 0
|
|
900
|
+
? this.inspectArchivesForEpoch(epoch)
|
|
901
|
+
: { containsCurrent: false, unreadable: false };
|
|
902
|
+
const compactMissingWithArchives = archiveProbe.containsCurrent || archiveProbe.unreadable;
|
|
903
|
+
const marker = this.recoveryMarkerState(epoch);
|
|
904
|
+
const degraded = corruptLines > 0 || oversizedLines > 0 || oversizedFiles > 0
|
|
905
|
+
|| compactMissingWithArchives || marker === 'degraded';
|
|
906
|
+
const records = compactedRecords + activeRecords;
|
|
907
|
+
return {
|
|
908
|
+
recovery: degraded ? 'degraded' : records === 0 ? 'empty' : marker === 'recovered' ? 'recovered' : 'healthy',
|
|
909
|
+
compactedRecords,
|
|
910
|
+
activeRecords,
|
|
911
|
+
corruptLines,
|
|
912
|
+
oversizedLines,
|
|
913
|
+
oversizedFiles,
|
|
914
|
+
archives,
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
withGraphLock(operation) {
|
|
918
|
+
this.ensureSecureDir();
|
|
919
|
+
const lockPath = join(this.dir, LOCK_FILE);
|
|
920
|
+
try {
|
|
921
|
+
util.acquireLock(lockPath);
|
|
922
|
+
}
|
|
923
|
+
catch (error) {
|
|
924
|
+
if (error instanceof util.LockTimeoutError)
|
|
925
|
+
throw new MemoryGraphBusyError();
|
|
926
|
+
throw error;
|
|
927
|
+
}
|
|
928
|
+
this.rotationCleanupFailed = false;
|
|
929
|
+
let value;
|
|
930
|
+
let operationError;
|
|
931
|
+
let operationFailed = false;
|
|
932
|
+
try {
|
|
933
|
+
this.ensureSecureDir();
|
|
934
|
+
this.reconcileRotationUnlocked();
|
|
935
|
+
value = operation();
|
|
936
|
+
}
|
|
937
|
+
catch (error) {
|
|
938
|
+
operationFailed = true;
|
|
939
|
+
operationError = error;
|
|
940
|
+
}
|
|
941
|
+
let releaseError;
|
|
942
|
+
try {
|
|
943
|
+
const released = util.releaseLock(lockPath);
|
|
944
|
+
const reliable = released.released
|
|
945
|
+
&& (released.reason === 'released' || released.reason === 'released_with_cleanup_error');
|
|
946
|
+
if (!reliable)
|
|
947
|
+
releaseError = new util.LockReleaseError(released.reason);
|
|
948
|
+
}
|
|
949
|
+
catch (error) {
|
|
950
|
+
releaseError = error;
|
|
951
|
+
}
|
|
952
|
+
if (operationFailed)
|
|
953
|
+
throw operationError;
|
|
954
|
+
if (releaseError !== undefined)
|
|
955
|
+
throw releaseError;
|
|
956
|
+
return value;
|
|
957
|
+
}
|
|
958
|
+
importFingerprintCache(dedupeScope, workspaceScope, sourceScope) {
|
|
959
|
+
const stateFingerprint = this.importStateFingerprint();
|
|
960
|
+
let cache = this.importedFingerprints.get(dedupeScope);
|
|
961
|
+
if (!cache || cache.stateFingerprint !== stateFingerprint) {
|
|
962
|
+
cache = {
|
|
963
|
+
stateFingerprint,
|
|
964
|
+
values: collectImportFingerprints(this.readImportRecords(), workspaceScope, this.userScope, sourceScope),
|
|
965
|
+
};
|
|
966
|
+
this.importedFingerprints.set(dedupeScope, cache);
|
|
967
|
+
}
|
|
968
|
+
return cache;
|
|
969
|
+
}
|
|
970
|
+
readStableImportState() {
|
|
971
|
+
let directoryIdentity;
|
|
972
|
+
try {
|
|
973
|
+
directoryIdentity = lstatSync(this.dir, { bigint: true });
|
|
974
|
+
}
|
|
975
|
+
catch (error) {
|
|
976
|
+
if (isObject(error) && error['code'] === 'ENOENT') {
|
|
977
|
+
return { epochId: LEGACY_EPOCH_ID, records: [] };
|
|
978
|
+
}
|
|
979
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
980
|
+
}
|
|
981
|
+
if (!directoryIdentity.isDirectory() || directoryIdentity.isSymbolicLink()) {
|
|
982
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
983
|
+
}
|
|
984
|
+
const before = this.importStateFingerprint();
|
|
985
|
+
const epochId = this.currentEpochId();
|
|
986
|
+
const records = this.readImportRecordsFromExistingDir();
|
|
987
|
+
let afterDirectoryIdentity;
|
|
988
|
+
try {
|
|
989
|
+
afterDirectoryIdentity = lstatSync(this.dir, { bigint: true });
|
|
990
|
+
}
|
|
991
|
+
catch {
|
|
992
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
993
|
+
}
|
|
994
|
+
const after = this.importStateFingerprint();
|
|
995
|
+
if (!sameGraphFileSnapshot(directoryIdentity, afterDirectoryIdentity) || before !== after) {
|
|
996
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
997
|
+
}
|
|
998
|
+
return { epochId, records };
|
|
999
|
+
}
|
|
1000
|
+
persistedRecordLine(record, epochId) {
|
|
1001
|
+
return Buffer.from(JSON.stringify({ ...record, epochId }) + '\n', 'utf8');
|
|
1002
|
+
}
|
|
1003
|
+
importRecordFits(record, epochId) {
|
|
1004
|
+
const line = this.persistedRecordLine(record, epochId);
|
|
1005
|
+
return line.length <= this.maxLineBytes && line.length <= this.maxActiveBytes;
|
|
1006
|
+
}
|
|
1007
|
+
importStateFingerprint() {
|
|
1008
|
+
const epochId = this.currentEpochId();
|
|
1009
|
+
return [EPOCH_FILE, COMPACT_FILE, ACTIVE_FILE].map((file) => {
|
|
1010
|
+
const path = join(this.dir, file);
|
|
1011
|
+
let stat;
|
|
1012
|
+
try {
|
|
1013
|
+
stat = lstatSync(path, { bigint: true });
|
|
1014
|
+
}
|
|
1015
|
+
catch (error) {
|
|
1016
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
1017
|
+
return `${file}:missing`;
|
|
1018
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
1019
|
+
}
|
|
1020
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
1021
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
1022
|
+
return `${file}:${stat.dev}:${stat.ino}:${stat.mode}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
1023
|
+
}).concat(`epoch:${epochId}`).join('|');
|
|
1024
|
+
}
|
|
1025
|
+
appendRecordUnlocked(record) {
|
|
1026
|
+
this.ensureSecureDir();
|
|
1027
|
+
const state = this.managedGraphStateFiles();
|
|
1028
|
+
const epoch = this.readEpochState();
|
|
1029
|
+
const line = this.persistedRecordLine(record, epoch.epochId);
|
|
1030
|
+
if (line.length > this.maxLineBytes || line.length > this.maxActiveBytes)
|
|
1031
|
+
return false;
|
|
1032
|
+
const activePath = join(this.dir, ACTIVE_FILE);
|
|
1033
|
+
let activeState = state.find((file) => file.name === ACTIVE_FILE);
|
|
1034
|
+
const activeWindow = activeState
|
|
1035
|
+
? this.activeLogicalWindow(epoch, activeState.identity)
|
|
1036
|
+
: { offset: 0, size: 0, invalid: false };
|
|
1037
|
+
if (activeWindow.invalid)
|
|
1038
|
+
throw new Error('memory_graph_epoch_rejected');
|
|
1039
|
+
if (activeWindow.size + line.length > this.maxActiveBytes) {
|
|
1040
|
+
const maintenance = this.rotateAndCompactUnlocked(epoch);
|
|
1041
|
+
if (!maintenance.rotated)
|
|
1042
|
+
return false;
|
|
1043
|
+
activeState = this.managedGraphStateFiles().find((file) => file.name === ACTIVE_FILE);
|
|
1044
|
+
}
|
|
1045
|
+
const fd = openNoFollow(activePath, constants.O_WRONLY | constants.O_CREAT, 0o600);
|
|
1046
|
+
try {
|
|
1047
|
+
const stat = fstatSync(fd, { bigint: true });
|
|
1048
|
+
if (!stat.isFile() || stat.isSymbolicLink()
|
|
1049
|
+
|| (activeState && !sameGraphFileSnapshot(activeState.identity, stat))
|
|
1050
|
+
|| (!activeState && stat.size !== 0n)
|
|
1051
|
+
|| stat.size > BigInt(Number.MAX_SAFE_INTEGER))
|
|
1052
|
+
return false;
|
|
1053
|
+
const originalSize = Number(stat.size);
|
|
1054
|
+
try {
|
|
1055
|
+
writeAll(fd, line, originalSize);
|
|
1056
|
+
fsyncSync(fd);
|
|
1057
|
+
return true;
|
|
1058
|
+
}
|
|
1059
|
+
catch (error) {
|
|
1060
|
+
try {
|
|
1061
|
+
ftruncateSync(fd, originalSize);
|
|
1062
|
+
fsyncSync(fd);
|
|
1063
|
+
}
|
|
1064
|
+
catch {
|
|
1065
|
+
throw new Error('memory_graph_append_rollback_failed');
|
|
1066
|
+
}
|
|
1067
|
+
throw error;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
finally {
|
|
1071
|
+
closeSync(fd);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
rotateAndCompactUnlocked(epochState) {
|
|
1075
|
+
this.ensureSecureDir();
|
|
1076
|
+
const state = this.managedGraphStateFiles();
|
|
1077
|
+
const epoch = epochState ?? this.readEpochState();
|
|
1078
|
+
const currentEpoch = epoch.epochId;
|
|
1079
|
+
const diagnostics = emptyDiagnostics();
|
|
1080
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
1081
|
+
const activeState = state.find((file) => file.name === ACTIVE_FILE);
|
|
1082
|
+
const compactState = state.find((file) => file.name === COMPACT_FILE);
|
|
1083
|
+
const activePayload = this.activePayloadForEpoch(epoch, this.maxActiveBytes);
|
|
1084
|
+
if (!activeState || activePayload.logicalSize === 0) {
|
|
1085
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
1086
|
+
}
|
|
1087
|
+
const activeWindow = this.activeLogicalWindow(epoch, activeState.identity);
|
|
1088
|
+
if (activeWindow.invalid || activeWindow.size !== activePayload.logicalSize) {
|
|
1089
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
1090
|
+
}
|
|
1091
|
+
const activeSource = {
|
|
1092
|
+
snapshot: serializeGraphFileSnapshot(activeState.identity),
|
|
1093
|
+
offset: activeWindow.offset,
|
|
1094
|
+
...rotationFileDigest(activePayload.payload),
|
|
1095
|
+
};
|
|
1096
|
+
let compactSource = null;
|
|
1097
|
+
if (compactState) {
|
|
1098
|
+
const compactBound = this.compactMatchesEpochBaseline(epoch)
|
|
1099
|
+
? this.maxCompactBytes + this.maxLineBytes
|
|
1100
|
+
: this.maxCompactBytes;
|
|
1101
|
+
const verified = this.readVerifiedRotationFile(compactPath, compactBound, false, 'memory_graph_rotation_backup_failed');
|
|
1102
|
+
if (!verified || !sameGraphFileSnapshot(compactState.identity, verified.identity)) {
|
|
1103
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
1104
|
+
}
|
|
1105
|
+
compactSource = {
|
|
1106
|
+
snapshot: serializeGraphFileSnapshot(verified.identity),
|
|
1107
|
+
...rotationFileDigest(verified.payload),
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
const records = [
|
|
1111
|
+
...this.readCompactForEpoch(epoch, diagnostics),
|
|
1112
|
+
...this.parseBuffer(activePayload.payload, diagnostics),
|
|
1113
|
+
]
|
|
1114
|
+
.filter((record) => recordEpochId(record) === currentEpoch);
|
|
1115
|
+
const compacted = compactRecords(records, this.maxCompactEdges);
|
|
1116
|
+
const fitted = fitCompactRecords(compacted, this.maxCompactBytes);
|
|
1117
|
+
if (compacted.length > 0 && fitted.records.length === 0) {
|
|
1118
|
+
return {
|
|
1119
|
+
rotated: false,
|
|
1120
|
+
compactedRecords: 0,
|
|
1121
|
+
corruptLines: diagnostics.corruptLines,
|
|
1122
|
+
oversizedLines: diagnostics.oversizedLines,
|
|
1123
|
+
archives: this.archiveFiles().length,
|
|
1124
|
+
recovery: 'degraded',
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
const compactPayload = fitted.payload;
|
|
1128
|
+
const archivePayload = gzipSync(activePayload.payload);
|
|
1129
|
+
const emptyActive = Buffer.alloc(0);
|
|
1130
|
+
const archivePath = this.nextArchivePath();
|
|
1131
|
+
const generation = ARCHIVE_PATTERN.exec(basename(archivePath))?.[1];
|
|
1132
|
+
if (!generation)
|
|
1133
|
+
throw new Error('memory_graph_rotation_backup_failed');
|
|
1134
|
+
const stageNames = rotationStageNames(generation);
|
|
1135
|
+
const preparedWithoutId = {
|
|
1136
|
+
version: 1,
|
|
1137
|
+
targetGeneration: generation,
|
|
1138
|
+
phase: 'prepared',
|
|
1139
|
+
epochId: currentEpoch,
|
|
1140
|
+
createdAt: new Date(this.now()).toISOString(),
|
|
1141
|
+
limits: {
|
|
1142
|
+
maxActiveBytes: this.maxActiveBytes,
|
|
1143
|
+
maxCompactBytes: this.maxCompactBytes,
|
|
1144
|
+
maxLineBytes: this.maxLineBytes,
|
|
1145
|
+
archiveRetention: this.archiveRetention,
|
|
1146
|
+
},
|
|
1147
|
+
source: { active: activeSource, compact: compactSource },
|
|
1148
|
+
target: {
|
|
1149
|
+
compact: {
|
|
1150
|
+
stageName: stageNames.compact,
|
|
1151
|
+
finalName: COMPACT_FILE,
|
|
1152
|
+
records: fitted.records.length,
|
|
1153
|
+
...rotationFileDigest(compactPayload),
|
|
1154
|
+
},
|
|
1155
|
+
archive: {
|
|
1156
|
+
stageName: stageNames.archive,
|
|
1157
|
+
finalName: basename(archivePath),
|
|
1158
|
+
...rotationFileDigest(archivePayload),
|
|
1159
|
+
},
|
|
1160
|
+
active: {
|
|
1161
|
+
stageName: stageNames.active,
|
|
1162
|
+
finalName: ACTIVE_FILE,
|
|
1163
|
+
...rotationFileDigest(emptyActive),
|
|
1164
|
+
},
|
|
1165
|
+
},
|
|
1166
|
+
};
|
|
1167
|
+
const preparedWithId = {
|
|
1168
|
+
...preparedWithoutId,
|
|
1169
|
+
transactionId: rotationTransactionId(preparedWithoutId),
|
|
1170
|
+
};
|
|
1171
|
+
const prepared = {
|
|
1172
|
+
...preparedWithId,
|
|
1173
|
+
journalDigest: rotationJournalDigest(preparedWithId),
|
|
1174
|
+
};
|
|
1175
|
+
for (const name of Object.values(stageNames)) {
|
|
1176
|
+
assertPathMissing(join(this.dir, name), 'memory_graph_rotation_recovery_failed');
|
|
1177
|
+
}
|
|
1178
|
+
assertPathMissing(join(this.dir, ROTATION_JOURNAL_FILE), 'memory_graph_rotation_recovery_failed');
|
|
1179
|
+
const preparedJournalIdentity = this.writeRotationJournal(prepared);
|
|
1180
|
+
this.notifyRotationPhase(prepared, 'commit', 'journal_prepared');
|
|
1181
|
+
this.writeRotationStage(prepared, 'compact', compactPayload);
|
|
1182
|
+
this.notifyRotationPhase(prepared, 'commit', 'compact_staged');
|
|
1183
|
+
this.writeRotationStage(prepared, 'archive', archivePayload);
|
|
1184
|
+
this.notifyRotationPhase(prepared, 'commit', 'archive_staged');
|
|
1185
|
+
this.writeRotationStage(prepared, 'active', emptyActive);
|
|
1186
|
+
this.notifyRotationPhase(prepared, 'commit', 'active_staged');
|
|
1187
|
+
this.assertRotationSourceMatches(prepared);
|
|
1188
|
+
this.assertRotationStagesMatch(prepared);
|
|
1189
|
+
this.assertRotationJournalUnchanged(prepared, preparedJournalIdentity);
|
|
1190
|
+
const committedWithoutDigest = { ...prepared, phase: 'committed' };
|
|
1191
|
+
const committed = {
|
|
1192
|
+
...committedWithoutDigest,
|
|
1193
|
+
journalDigest: rotationJournalDigest(committedWithoutDigest),
|
|
1194
|
+
};
|
|
1195
|
+
this.writeRotationJournal(committed);
|
|
1196
|
+
this.notifyRotationPhase(committed, 'commit', 'journal_committed');
|
|
1197
|
+
this.reconcileCommittedRotation(committed, 'commit');
|
|
1198
|
+
const degraded = diagnostics.corruptLines > 0
|
|
1199
|
+
|| diagnostics.oversizedLines > 0
|
|
1200
|
+
|| diagnostics.truncated;
|
|
1201
|
+
return {
|
|
1202
|
+
rotated: true,
|
|
1203
|
+
compactedRecords: fitted.records.length,
|
|
1204
|
+
corruptLines: diagnostics.corruptLines,
|
|
1205
|
+
oversizedLines: diagnostics.oversizedLines,
|
|
1206
|
+
archives: this.archiveFiles().length,
|
|
1207
|
+
recovery: degraded ? 'degraded' : fitted.records.length > 0 ? 'healthy' : 'empty',
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
reconcileRotationUnlocked() {
|
|
1211
|
+
const journalPath = join(this.dir, ROTATION_JOURNAL_FILE);
|
|
1212
|
+
const stageFiles = this.rotationStageFiles();
|
|
1213
|
+
const tempFiles = this.rotationTempFiles();
|
|
1214
|
+
let journalPresent = true;
|
|
1215
|
+
try {
|
|
1216
|
+
lstatSync(journalPath);
|
|
1217
|
+
}
|
|
1218
|
+
catch (error) {
|
|
1219
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
1220
|
+
journalPresent = false;
|
|
1221
|
+
else
|
|
1222
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1223
|
+
}
|
|
1224
|
+
if (!journalPresent) {
|
|
1225
|
+
for (const name of tempFiles)
|
|
1226
|
+
this.removeRotationTemp(name);
|
|
1227
|
+
if (stageFiles.length > 0)
|
|
1228
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
const loaded = this.readRotationJournal();
|
|
1232
|
+
const journal = loaded.journal;
|
|
1233
|
+
const expectedStages = new Set(Object.values(rotationStageNames(journal.targetGeneration)));
|
|
1234
|
+
const expectedTemps = new Set(Object.values(rotationTempNames(journal.targetGeneration)));
|
|
1235
|
+
if (stageFiles.some((name) => !expectedStages.has(name))
|
|
1236
|
+
|| tempFiles.some((name) => !expectedTemps.has(name))) {
|
|
1237
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1238
|
+
}
|
|
1239
|
+
const epoch = this.readEpochState();
|
|
1240
|
+
if (epoch.epochId !== journal.epochId) {
|
|
1241
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1242
|
+
}
|
|
1243
|
+
if (journal.phase === 'prepared') {
|
|
1244
|
+
this.assertRotationSourceMatches(journal);
|
|
1245
|
+
for (const target of [
|
|
1246
|
+
journal.target.compact,
|
|
1247
|
+
journal.target.archive,
|
|
1248
|
+
journal.target.active,
|
|
1249
|
+
]) {
|
|
1250
|
+
this.removeRotationStage(target);
|
|
1251
|
+
}
|
|
1252
|
+
for (const name of tempFiles)
|
|
1253
|
+
this.removeRotationTemp(name);
|
|
1254
|
+
this.notifyRotationPhase(journal, 'recovery', 'before_journal_clear');
|
|
1255
|
+
this.removeVerifiedRotationFile(journalPath, loaded.identity, 'memory_graph_rotation_recovery_failed');
|
|
1256
|
+
this.notifyRotationPhase(journal, 'recovery', 'journal_cleared');
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
for (const name of tempFiles)
|
|
1260
|
+
this.removeRotationTemp(name);
|
|
1261
|
+
this.reconcileCommittedRotation(journal, 'recovery', loaded.identity);
|
|
1262
|
+
}
|
|
1263
|
+
reconcileCommittedRotation(journal, mode, journalIdentity) {
|
|
1264
|
+
let identity = journalIdentity;
|
|
1265
|
+
if (!identity) {
|
|
1266
|
+
const loaded = this.readRotationJournal();
|
|
1267
|
+
if (loaded.journal.transactionId !== journal.transactionId
|
|
1268
|
+
|| loaded.journal.phase !== 'committed') {
|
|
1269
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1270
|
+
}
|
|
1271
|
+
identity = loaded.identity;
|
|
1272
|
+
}
|
|
1273
|
+
this.assertCommittedRotationCanApply(journal);
|
|
1274
|
+
this.publishRotationFile(journal, journal.target.compact, journal.source.compact, mode, 'compact_published');
|
|
1275
|
+
this.publishRotationFile(journal, journal.target.archive, null, mode, 'archive_published');
|
|
1276
|
+
this.notifyRotationPhase(journal, mode, 'before_active_publish');
|
|
1277
|
+
this.publishRotationActive(journal, mode);
|
|
1278
|
+
for (const target of [
|
|
1279
|
+
journal.target.compact,
|
|
1280
|
+
journal.target.archive,
|
|
1281
|
+
journal.target.active,
|
|
1282
|
+
]) {
|
|
1283
|
+
this.removeRotationStage(target);
|
|
1284
|
+
}
|
|
1285
|
+
const cleanupFailed = this.completeCommittedRotationCleanup(journal);
|
|
1286
|
+
this.rotationCleanupFailed = this.rotationCleanupFailed || cleanupFailed;
|
|
1287
|
+
this.notifyRotationPhase(journal, mode, 'before_journal_clear');
|
|
1288
|
+
this.assertCommittedRotationApplied(journal);
|
|
1289
|
+
this.removeVerifiedRotationFile(join(this.dir, ROTATION_JOURNAL_FILE), identity, 'memory_graph_rotation_recovery_failed');
|
|
1290
|
+
this.notifyRotationPhase(journal, mode, 'journal_cleared');
|
|
1291
|
+
}
|
|
1292
|
+
completeCommittedRotationCleanup(journal) {
|
|
1293
|
+
const epoch = this.readEpochState();
|
|
1294
|
+
if (epoch.epochId !== journal.epochId) {
|
|
1295
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1296
|
+
}
|
|
1297
|
+
try {
|
|
1298
|
+
this.managedGraphStateFiles();
|
|
1299
|
+
this.clearRecoveryMarker(epoch, journal.limits.maxLineBytes);
|
|
1300
|
+
this.pruneArchives(journal.limits.archiveRetention);
|
|
1301
|
+
return false;
|
|
1302
|
+
}
|
|
1303
|
+
catch {
|
|
1304
|
+
return true;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
withRotationCleanupStatus(report) {
|
|
1308
|
+
return this.rotationCleanupFailed ? { ...report, recovery: 'degraded' } : report;
|
|
1309
|
+
}
|
|
1310
|
+
assertCommittedRotationApplied(journal) {
|
|
1311
|
+
for (const target of [
|
|
1312
|
+
journal.target.compact,
|
|
1313
|
+
journal.target.archive,
|
|
1314
|
+
journal.target.active,
|
|
1315
|
+
]) {
|
|
1316
|
+
if (!this.rotationTargetMatches(join(this.dir, target.finalName), target)) {
|
|
1317
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
assertCommittedRotationCanApply(journal) {
|
|
1322
|
+
this.assertRotationFileReady(journal.target.compact, journal.source.compact);
|
|
1323
|
+
this.assertRotationFileReady(journal.target.archive, null);
|
|
1324
|
+
const activeTarget = journal.target.active;
|
|
1325
|
+
const activePath = join(this.dir, activeTarget.finalName);
|
|
1326
|
+
if (this.rotationTargetMatches(activePath, activeTarget)) {
|
|
1327
|
+
this.assertOptionalRotationStage(activeTarget);
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1330
|
+
if (!this.rotationActiveSourceMatches(activePath, journal.source.active)) {
|
|
1331
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1332
|
+
}
|
|
1333
|
+
this.requireRotationTarget(join(this.dir, activeTarget.stageName), activeTarget);
|
|
1334
|
+
}
|
|
1335
|
+
assertRotationFileReady(target, source) {
|
|
1336
|
+
const finalPath = join(this.dir, target.finalName);
|
|
1337
|
+
if (this.rotationTargetMatches(finalPath, target)) {
|
|
1338
|
+
this.assertOptionalRotationStage(target);
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
if (source === null) {
|
|
1342
|
+
assertPathMissing(finalPath, 'memory_graph_rotation_recovery_failed');
|
|
1343
|
+
}
|
|
1344
|
+
else if (!this.rotationSourceMatches(finalPath, source)) {
|
|
1345
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1346
|
+
}
|
|
1347
|
+
this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1348
|
+
}
|
|
1349
|
+
assertOptionalRotationStage(target) {
|
|
1350
|
+
const path = join(this.dir, target.stageName);
|
|
1351
|
+
const staged = this.readVerifiedRotationFile(path, target.size, true, 'memory_graph_rotation_recovery_failed');
|
|
1352
|
+
if (staged && !rotationDigestMatches(staged.payload, target)) {
|
|
1353
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
publishRotationFile(journal, target, source, mode, phase) {
|
|
1357
|
+
const finalPath = join(this.dir, target.finalName);
|
|
1358
|
+
if (this.rotationTargetMatches(finalPath, target)) {
|
|
1359
|
+
this.removeRotationStage(target);
|
|
1360
|
+
this.notifyRotationPhase(journal, mode, phase);
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
if (source === null) {
|
|
1364
|
+
assertPathMissing(finalPath, 'memory_graph_rotation_recovery_failed');
|
|
1365
|
+
}
|
|
1366
|
+
else if (!this.rotationSourceMatches(finalPath, source)) {
|
|
1367
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1368
|
+
}
|
|
1369
|
+
const staged = this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1370
|
+
try {
|
|
1371
|
+
renameSync(join(this.dir, target.stageName), finalPath);
|
|
1372
|
+
this.syncGraphDirectory();
|
|
1373
|
+
}
|
|
1374
|
+
catch {
|
|
1375
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1376
|
+
}
|
|
1377
|
+
const published = this.requireRotationTarget(finalPath, target);
|
|
1378
|
+
if (!sameGraphFileIdentity(staged.identity, published.identity)) {
|
|
1379
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1380
|
+
}
|
|
1381
|
+
this.notifyRotationPhase(journal, mode, phase);
|
|
1382
|
+
}
|
|
1383
|
+
publishRotationActive(journal, mode) {
|
|
1384
|
+
const target = journal.target.active;
|
|
1385
|
+
const activePath = join(this.dir, target.finalName);
|
|
1386
|
+
if (this.rotationTargetMatches(activePath, target)) {
|
|
1387
|
+
this.removeRotationStage(target);
|
|
1388
|
+
this.notifyRotationPhase(journal, mode, 'active_published');
|
|
1389
|
+
return;
|
|
1390
|
+
}
|
|
1391
|
+
if (!this.rotationActiveSourceMatches(activePath, journal.source.active)) {
|
|
1392
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1393
|
+
}
|
|
1394
|
+
const staged = this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1395
|
+
try {
|
|
1396
|
+
renameSync(join(this.dir, target.stageName), activePath);
|
|
1397
|
+
this.syncGraphDirectory();
|
|
1398
|
+
}
|
|
1399
|
+
catch {
|
|
1400
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1401
|
+
}
|
|
1402
|
+
const published = this.requireRotationTarget(activePath, target);
|
|
1403
|
+
if (!sameGraphFileIdentity(staged.identity, published.identity)) {
|
|
1404
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1405
|
+
}
|
|
1406
|
+
this.notifyRotationPhase(journal, mode, 'active_published');
|
|
1407
|
+
}
|
|
1408
|
+
writeRotationJournal(journal) {
|
|
1409
|
+
const payload = Buffer.from(JSON.stringify(journal) + '\n', 'utf8');
|
|
1410
|
+
if (payload.length > MAX_ROTATION_JOURNAL_BYTES) {
|
|
1411
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1412
|
+
}
|
|
1413
|
+
const committedIdentity = this.writeAtomic(join(this.dir, ROTATION_JOURNAL_FILE), payload, true, journal.targetGeneration);
|
|
1414
|
+
const loaded = this.readRotationJournal();
|
|
1415
|
+
if (!sameGraphFileIdentity(committedIdentity, loaded.identity)
|
|
1416
|
+
|| loaded.journal.transactionId !== journal.transactionId
|
|
1417
|
+
|| loaded.journal.phase !== journal.phase) {
|
|
1418
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1419
|
+
}
|
|
1420
|
+
return loaded.identity;
|
|
1421
|
+
}
|
|
1422
|
+
assertRotationJournalUnchanged(journal, expectedIdentity) {
|
|
1423
|
+
const loaded = this.readRotationJournal();
|
|
1424
|
+
if (!sameGraphFileSnapshot(expectedIdentity, loaded.identity)
|
|
1425
|
+
|| loaded.journal.transactionId !== journal.transactionId
|
|
1426
|
+
|| loaded.journal.phase !== journal.phase) {
|
|
1427
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
readRotationJournal() {
|
|
1431
|
+
const verified = this.readVerifiedRotationFile(join(this.dir, ROTATION_JOURNAL_FILE), MAX_ROTATION_JOURNAL_BYTES, false, 'memory_graph_rotation_journal_rejected');
|
|
1432
|
+
if (!verified)
|
|
1433
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1434
|
+
try {
|
|
1435
|
+
const value = JSON.parse(verified.payload.toString('utf8'));
|
|
1436
|
+
const journal = parseRotationJournal(value);
|
|
1437
|
+
if (!journal)
|
|
1438
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1439
|
+
return { journal, identity: verified.identity };
|
|
1440
|
+
}
|
|
1441
|
+
catch {
|
|
1442
|
+
throw new Error('memory_graph_rotation_journal_rejected');
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
writeRotationStage(journal, kind, payload) {
|
|
1446
|
+
const target = journal.target[kind];
|
|
1447
|
+
if (!rotationDigestMatches(payload, target)) {
|
|
1448
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1449
|
+
}
|
|
1450
|
+
const committedIdentity = this.writeAtomic(join(this.dir, target.stageName), payload, true, journal.targetGeneration);
|
|
1451
|
+
const staged = this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1452
|
+
if (!sameGraphFileIdentity(committedIdentity, staged.identity)) {
|
|
1453
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
assertRotationStagesMatch(journal) {
|
|
1457
|
+
for (const target of [
|
|
1458
|
+
journal.target.compact,
|
|
1459
|
+
journal.target.archive,
|
|
1460
|
+
journal.target.active,
|
|
1461
|
+
]) {
|
|
1462
|
+
this.requireRotationTarget(join(this.dir, target.stageName), target);
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
assertRotationSourceMatches(journal) {
|
|
1466
|
+
if (!this.rotationActiveSourceMatches(join(this.dir, ACTIVE_FILE), journal.source.active)) {
|
|
1467
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1468
|
+
}
|
|
1469
|
+
const compactPath = join(this.dir, COMPACT_FILE);
|
|
1470
|
+
if (journal.source.compact === null) {
|
|
1471
|
+
assertPathMissing(compactPath, 'memory_graph_rotation_recovery_failed');
|
|
1472
|
+
}
|
|
1473
|
+
else if (!this.rotationSourceMatches(compactPath, journal.source.compact)) {
|
|
1474
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
rotationActiveSourceMatches(path, source) {
|
|
1478
|
+
const physicalSize = Number(source.snapshot.size);
|
|
1479
|
+
const verified = this.readVerifiedRotationFile(path, physicalSize, true, 'memory_graph_rotation_recovery_failed', { offset: source.offset, size: source.size });
|
|
1480
|
+
if (!verified || !serializedSnapshotMatches(source.snapshot, verified.identity))
|
|
1481
|
+
return false;
|
|
1482
|
+
if (BigInt(source.offset) + BigInt(source.size) !== verified.identity.size)
|
|
1483
|
+
return false;
|
|
1484
|
+
return rotationDigestMatches(verified.payload, source);
|
|
1485
|
+
}
|
|
1486
|
+
rotationSourceMatches(path, source) {
|
|
1487
|
+
const verified = this.readVerifiedRotationFile(path, source.size, true, 'memory_graph_rotation_recovery_failed');
|
|
1488
|
+
return verified !== null
|
|
1489
|
+
&& serializedSnapshotMatches(source.snapshot, verified.identity)
|
|
1490
|
+
&& rotationDigestMatches(verified.payload, source);
|
|
1491
|
+
}
|
|
1492
|
+
rotationTargetMatches(path, target) {
|
|
1493
|
+
let identity;
|
|
1494
|
+
try {
|
|
1495
|
+
identity = lstatSync(path, { bigint: true });
|
|
1496
|
+
}
|
|
1497
|
+
catch (error) {
|
|
1498
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
1499
|
+
return false;
|
|
1500
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1501
|
+
}
|
|
1502
|
+
if (!identity.isFile() || identity.isSymbolicLink()) {
|
|
1503
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1504
|
+
}
|
|
1505
|
+
if (identity.size !== BigInt(target.size))
|
|
1506
|
+
return false;
|
|
1507
|
+
const verified = this.readVerifiedRotationFile(path, target.size, true, 'memory_graph_rotation_recovery_failed');
|
|
1508
|
+
return verified !== null && rotationDigestMatches(verified.payload, target);
|
|
1509
|
+
}
|
|
1510
|
+
requireRotationTarget(path, target) {
|
|
1511
|
+
const verified = this.readVerifiedRotationFile(path, target.size, false, 'memory_graph_rotation_recovery_failed');
|
|
1512
|
+
if (!verified || !rotationDigestMatches(verified.payload, target)) {
|
|
1513
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1514
|
+
}
|
|
1515
|
+
return verified;
|
|
1516
|
+
}
|
|
1517
|
+
removeRotationStage(target) {
|
|
1518
|
+
const path = join(this.dir, target.stageName);
|
|
1519
|
+
const verified = this.readVerifiedRotationFile(path, target.size, true, 'memory_graph_rotation_recovery_failed');
|
|
1520
|
+
if (!verified)
|
|
1521
|
+
return;
|
|
1522
|
+
if (!rotationDigestMatches(verified.payload, target)) {
|
|
1523
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1524
|
+
}
|
|
1525
|
+
this.removeVerifiedRotationFile(path, verified.identity, 'memory_graph_rotation_recovery_failed');
|
|
1526
|
+
}
|
|
1527
|
+
removeVerifiedRotationFile(path, identity, reason) {
|
|
1528
|
+
let current;
|
|
1529
|
+
try {
|
|
1530
|
+
current = lstatSync(path, { bigint: true });
|
|
1531
|
+
}
|
|
1532
|
+
catch {
|
|
1533
|
+
throw new Error(reason);
|
|
1534
|
+
}
|
|
1535
|
+
if (!current.isFile() || current.isSymbolicLink()
|
|
1536
|
+
|| !sameGraphFileSnapshot(identity, current)) {
|
|
1537
|
+
throw new Error(reason);
|
|
1538
|
+
}
|
|
1539
|
+
try {
|
|
1540
|
+
unlinkSync(path);
|
|
1541
|
+
this.syncGraphDirectory();
|
|
1542
|
+
}
|
|
1543
|
+
catch {
|
|
1544
|
+
throw new Error(reason);
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
readVerifiedRotationFile(path, maxBytes, optional, reason, range) {
|
|
1548
|
+
let pathBefore;
|
|
1549
|
+
try {
|
|
1550
|
+
pathBefore = lstatSync(path, { bigint: true });
|
|
1551
|
+
}
|
|
1552
|
+
catch (error) {
|
|
1553
|
+
if (optional && isObject(error) && error['code'] === 'ENOENT')
|
|
1554
|
+
return null;
|
|
1555
|
+
throw new Error(reason);
|
|
1556
|
+
}
|
|
1557
|
+
if (!pathBefore.isFile() || pathBefore.isSymbolicLink()
|
|
1558
|
+
|| pathBefore.size > BigInt(maxBytes)
|
|
1559
|
+
|| pathBefore.size > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
1560
|
+
throw new Error(reason);
|
|
1561
|
+
}
|
|
1562
|
+
let fd;
|
|
1563
|
+
try {
|
|
1564
|
+
fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
232
1565
|
}
|
|
233
|
-
catch
|
|
234
|
-
|
|
235
|
-
|
|
1566
|
+
catch {
|
|
1567
|
+
throw new Error(reason);
|
|
1568
|
+
}
|
|
1569
|
+
try {
|
|
1570
|
+
const openedBefore = fstatSync(fd, { bigint: true });
|
|
1571
|
+
if (!openedBefore.isFile() || openedBefore.isSymbolicLink()
|
|
1572
|
+
|| !sameGraphFileSnapshot(pathBefore, openedBefore)) {
|
|
1573
|
+
throw new Error(reason);
|
|
236
1574
|
}
|
|
237
|
-
|
|
1575
|
+
const readOffset = range?.offset ?? 0;
|
|
1576
|
+
const readSize = range?.size ?? Number(openedBefore.size);
|
|
1577
|
+
if (!Number.isSafeInteger(readOffset) || readOffset < 0
|
|
1578
|
+
|| !Number.isSafeInteger(readSize) || readSize < 0
|
|
1579
|
+
|| BigInt(readOffset) + BigInt(readSize) > openedBefore.size) {
|
|
1580
|
+
throw new Error(reason);
|
|
1581
|
+
}
|
|
1582
|
+
const payload = readFdBytes(fd, readSize, readOffset);
|
|
1583
|
+
const openedAfter = fstatSync(fd, { bigint: true });
|
|
1584
|
+
let pathAfter;
|
|
1585
|
+
try {
|
|
1586
|
+
pathAfter = lstatSync(path, { bigint: true });
|
|
1587
|
+
}
|
|
1588
|
+
catch {
|
|
1589
|
+
throw new Error(reason);
|
|
1590
|
+
}
|
|
1591
|
+
if (payload.length !== readSize
|
|
1592
|
+
|| !sameGraphFileSnapshot(openedBefore, openedAfter)
|
|
1593
|
+
|| !sameGraphFileSnapshot(openedAfter, pathAfter)) {
|
|
1594
|
+
throw new Error(reason);
|
|
1595
|
+
}
|
|
1596
|
+
return { identity: openedAfter, payload };
|
|
1597
|
+
}
|
|
1598
|
+
finally {
|
|
1599
|
+
closeSync(fd);
|
|
238
1600
|
}
|
|
239
1601
|
}
|
|
240
|
-
|
|
241
|
-
if (!existsSync(this.dir))
|
|
242
|
-
return emptyHealth();
|
|
243
|
-
const dirStat = lstatSync(this.dir);
|
|
244
|
-
if (!dirStat.isDirectory() || dirStat.isSymbolicLink())
|
|
245
|
-
throw new Error('memory_graph_dir_rejected');
|
|
246
|
-
const compactDiagnostics = emptyDiagnostics();
|
|
247
|
-
const activeDiagnostics = emptyDiagnostics();
|
|
248
|
-
const compactPath = join(this.dir, COMPACT_FILE);
|
|
249
|
-
const activePath = join(this.dir, ACTIVE_FILE);
|
|
250
|
-
const compactedRecords = this.readCompact(compactDiagnostics).length;
|
|
251
|
-
const activeRecords = this.readWholeBounded(activePath, activeDiagnostics, this.maxActiveBytes).length;
|
|
252
|
-
const archives = this.archiveFiles().length;
|
|
253
|
-
const oversizedFiles = Number(fileExceeds(compactPath, this.maxCompactBytes)) + Number(fileExceeds(activePath, this.maxActiveBytes));
|
|
254
|
-
const rejectedFiles = Number(existsSync(compactPath) && !this.secureRegularFile(compactPath))
|
|
255
|
-
+ Number(existsSync(activePath) && !this.secureRegularFile(activePath));
|
|
256
|
-
const corruptLines = compactDiagnostics.corruptLines + activeDiagnostics.corruptLines + rejectedFiles;
|
|
257
|
-
const oversizedLines = compactDiagnostics.oversizedLines + activeDiagnostics.oversizedLines;
|
|
258
|
-
const compactMissingWithArchives = archives > 0 && (!existsSync(compactPath) || statSync(compactPath).size === 0);
|
|
259
|
-
const degraded = corruptLines > 0 || oversizedLines > 0 || oversizedFiles > 0 || compactMissingWithArchives;
|
|
260
|
-
const records = compactedRecords + activeRecords;
|
|
261
|
-
return {
|
|
262
|
-
recovery: degraded ? 'degraded' : records === 0 ? 'empty' : this.hasRecoveryMarker() ? 'recovered' : 'healthy',
|
|
263
|
-
compactedRecords,
|
|
264
|
-
activeRecords,
|
|
265
|
-
corruptLines,
|
|
266
|
-
oversizedLines,
|
|
267
|
-
oversizedFiles,
|
|
268
|
-
archives,
|
|
269
|
-
};
|
|
270
|
-
}
|
|
271
|
-
withGraphLock(operation) {
|
|
272
|
-
this.ensureSecureDir();
|
|
273
|
-
const lockPath = join(this.dir, LOCK_FILE);
|
|
1602
|
+
rotationStageFiles() {
|
|
274
1603
|
try {
|
|
275
|
-
|
|
1604
|
+
return readdirSync(this.dir).filter((name) => ROTATION_STAGE_PATTERN.test(name));
|
|
276
1605
|
}
|
|
277
|
-
catch
|
|
278
|
-
|
|
279
|
-
throw new MemoryGraphBusyError();
|
|
280
|
-
throw error;
|
|
1606
|
+
catch {
|
|
1607
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
281
1608
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
let operationFailed = false;
|
|
1609
|
+
}
|
|
1610
|
+
rotationTempFiles() {
|
|
285
1611
|
try {
|
|
286
|
-
this.
|
|
287
|
-
value = operation();
|
|
1612
|
+
return readdirSync(this.dir).filter((name) => ROTATION_TEMP_PATTERN.test(name));
|
|
288
1613
|
}
|
|
289
|
-
catch
|
|
290
|
-
|
|
291
|
-
operationError = error;
|
|
1614
|
+
catch {
|
|
1615
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
292
1616
|
}
|
|
293
|
-
|
|
1617
|
+
}
|
|
1618
|
+
removeRotationTemp(name) {
|
|
1619
|
+
if (!ROTATION_TEMP_PATTERN.test(name)) {
|
|
1620
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1621
|
+
}
|
|
1622
|
+
const path = join(this.dir, name);
|
|
1623
|
+
let identity;
|
|
294
1624
|
try {
|
|
295
|
-
|
|
296
|
-
const reliable = released.released
|
|
297
|
-
&& (released.reason === 'released' || released.reason === 'released_with_cleanup_error');
|
|
298
|
-
if (!reliable)
|
|
299
|
-
releaseError = new util.LockReleaseError(released.reason);
|
|
1625
|
+
identity = lstatSync(path, { bigint: true });
|
|
300
1626
|
}
|
|
301
1627
|
catch (error) {
|
|
302
|
-
|
|
1628
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
1629
|
+
return;
|
|
1630
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
303
1631
|
}
|
|
304
|
-
if (
|
|
305
|
-
throw
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
return value;
|
|
1632
|
+
if (!identity.isFile() || identity.isSymbolicLink()) {
|
|
1633
|
+
throw new Error('memory_graph_rotation_recovery_failed');
|
|
1634
|
+
}
|
|
1635
|
+
this.removeVerifiedRotationFile(path, identity, 'memory_graph_rotation_recovery_failed');
|
|
309
1636
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
}).join('|');
|
|
1637
|
+
notifyRotationPhase(journal, mode, phase) {
|
|
1638
|
+
this.onRotationPhase?.({
|
|
1639
|
+
mode,
|
|
1640
|
+
phase,
|
|
1641
|
+
transactionId: journal.transactionId,
|
|
1642
|
+
generation: journal.targetGeneration,
|
|
1643
|
+
});
|
|
318
1644
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
return false;
|
|
324
|
-
const activePath = join(this.dir, ACTIVE_FILE);
|
|
325
|
-
if (existsSync(activePath) && statSync(activePath).size + Buffer.byteLength(line) > this.maxActiveBytes) {
|
|
326
|
-
const maintenance = this.rotateAndCompactUnlocked();
|
|
327
|
-
if (!maintenance.rotated)
|
|
328
|
-
return false;
|
|
329
|
-
}
|
|
330
|
-
const fd = openNoFollow(activePath, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND, 0o600);
|
|
1645
|
+
syncGraphDirectory() {
|
|
1646
|
+
if (process.platform === 'win32')
|
|
1647
|
+
return;
|
|
1648
|
+
const fd = openSync(this.dir, constants.O_RDONLY);
|
|
331
1649
|
try {
|
|
332
|
-
const stat = fstatSync(fd);
|
|
333
|
-
if (!stat.isFile())
|
|
334
|
-
return false;
|
|
335
|
-
writeSync(fd, line, undefined, 'utf8');
|
|
336
1650
|
fsyncSync(fd);
|
|
337
|
-
return true;
|
|
338
1651
|
}
|
|
339
1652
|
finally {
|
|
340
1653
|
closeSync(fd);
|
|
341
1654
|
}
|
|
342
1655
|
}
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
const activePath = join(this.dir, ACTIVE_FILE);
|
|
346
|
-
const records = [...this.readCompact(diagnostics), ...this.readWholeBounded(activePath, diagnostics, this.maxActiveBytes)];
|
|
347
|
-
const compacted = compactRecords(records, this.maxCompactEdges);
|
|
348
|
-
const compactedRecords = this.writeCompact(compacted);
|
|
349
|
-
if (compacted.length > 0 && compactedRecords === 0) {
|
|
350
|
-
return {
|
|
351
|
-
rotated: false,
|
|
352
|
-
compactedRecords: 0,
|
|
353
|
-
corruptLines: diagnostics.corruptLines,
|
|
354
|
-
oversizedLines: diagnostics.oversizedLines,
|
|
355
|
-
archives: this.archiveFiles().length,
|
|
356
|
-
recovery: 'degraded',
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
if (compacted.length === 0 || compactedRecords > 0)
|
|
360
|
-
this.clearRecoveryMarker();
|
|
361
|
-
let rotated = false;
|
|
362
|
-
if (existsSync(activePath) && this.secureRegularFile(activePath)) {
|
|
363
|
-
const raw = this.readRawTail(activePath, this.maxActiveBytes);
|
|
364
|
-
if (statSync(activePath).size > raw.length)
|
|
365
|
-
diagnostics.truncated = true;
|
|
366
|
-
const archivePath = this.nextArchivePath();
|
|
367
|
-
this.writeAtomic(archivePath, gzipSync(raw));
|
|
368
|
-
this.writeAtomic(activePath, Buffer.alloc(0));
|
|
369
|
-
rotated = true;
|
|
370
|
-
}
|
|
371
|
-
this.pruneArchives();
|
|
372
|
-
return {
|
|
373
|
-
rotated,
|
|
374
|
-
compactedRecords,
|
|
375
|
-
corruptLines: diagnostics.corruptLines,
|
|
376
|
-
oversizedLines: diagnostics.oversizedLines,
|
|
377
|
-
archives: this.archiveFiles().length,
|
|
378
|
-
recovery: diagnostics.corruptLines > 0 || diagnostics.oversizedLines > 0 || diagnostics.truncated
|
|
379
|
-
? 'degraded'
|
|
380
|
-
: compactedRecords > 0 ? 'healthy' : 'empty',
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
compactRequiresRecovery() {
|
|
384
|
-
const path = join(this.dir, COMPACT_FILE);
|
|
385
|
-
if (!existsSync(path) || !this.secureRegularFile(path) || statSync(path).size === 0)
|
|
1656
|
+
compactRequiresRecovery(epoch) {
|
|
1657
|
+
if (this.recoveryMarkerState(epoch) === 'degraded')
|
|
386
1658
|
return true;
|
|
1659
|
+
const path = join(this.dir, COMPACT_FILE);
|
|
387
1660
|
const diagnostics = emptyDiagnostics();
|
|
388
|
-
this.
|
|
389
|
-
|
|
1661
|
+
const currentRecords = this.readCompactForEpoch(epoch, diagnostics)
|
|
1662
|
+
.filter((record) => recordEpochId(record) === epoch.epochId);
|
|
1663
|
+
const compactBaseline = this.compactMatchesEpochBaseline(epoch);
|
|
1664
|
+
const compactUnusable = compactBaseline || !existsSync(path)
|
|
1665
|
+
|| !this.secureRegularFile(path)
|
|
1666
|
+
|| statSync(path).size === 0
|
|
1667
|
+
|| currentRecords.length === 0
|
|
1668
|
+
|| diagnostics.corruptLines > 0
|
|
1669
|
+
|| diagnostics.oversizedLines > 0
|
|
1670
|
+
|| diagnostics.truncated;
|
|
1671
|
+
if (!compactUnusable)
|
|
1672
|
+
return false;
|
|
1673
|
+
const archives = this.inspectArchivesForEpoch(epoch);
|
|
1674
|
+
return archives.containsCurrent || archives.unreadable;
|
|
390
1675
|
}
|
|
391
1676
|
readQueryableRecords(diagnostics) {
|
|
392
1677
|
this.ensureSecureDir();
|
|
1678
|
+
this.managedGraphStateFiles();
|
|
1679
|
+
const epoch = this.readEpochState();
|
|
1680
|
+
const epochId = epoch.epochId;
|
|
393
1681
|
const compactPath = join(this.dir, COMPACT_FILE);
|
|
394
1682
|
const compactDiagnostics = emptyDiagnostics();
|
|
395
|
-
let records = this.
|
|
1683
|
+
let records = this.readCompactForEpoch(epoch, compactDiagnostics)
|
|
1684
|
+
.filter((record) => recordEpochId(record) === epochId);
|
|
396
1685
|
const archives = this.archiveFiles().length;
|
|
397
1686
|
const compactExists = existsSync(compactPath);
|
|
398
1687
|
const compactSecure = compactExists && this.secureRegularFile(compactPath);
|
|
399
|
-
const
|
|
1688
|
+
const compactUnusable = (this.compactMatchesEpochBaseline(epoch)
|
|
1689
|
+
|| !compactExists
|
|
400
1690
|
|| !compactSecure
|
|
401
1691
|
|| (compactSecure && statSync(compactPath).size === 0)
|
|
1692
|
+
|| records.length === 0
|
|
402
1693
|
|| compactDiagnostics.corruptLines > 0
|
|
403
1694
|
|| compactDiagnostics.oversizedLines > 0
|
|
404
1695
|
|| compactDiagnostics.truncated);
|
|
1696
|
+
const archiveProbe = archives > 0 && compactUnusable
|
|
1697
|
+
? this.inspectArchivesForEpoch(epoch)
|
|
1698
|
+
: { containsCurrent: false, unreadable: false };
|
|
1699
|
+
const compactNeedsRecovery = compactUnusable
|
|
1700
|
+
&& (archiveProbe.containsCurrent || archiveProbe.unreadable);
|
|
405
1701
|
mergeDiagnostics(diagnostics, compactDiagnostics);
|
|
406
1702
|
if (compactNeedsRecovery) {
|
|
407
1703
|
try {
|
|
408
|
-
const recovery = this.recoverFromArchivesUnlocked();
|
|
409
|
-
|
|
1704
|
+
const recovery = this.recoverFromArchivesUnlocked(epoch);
|
|
1705
|
+
diagnostics.corruptLines += recovery.corruptLines;
|
|
1706
|
+
diagnostics.oversizedLines += recovery.oversizedLines;
|
|
1707
|
+
if (recovery.recovery === 'recovered'
|
|
1708
|
+
|| (recovery.recovery === 'degraded' && recovery.compactedRecords > 0)) {
|
|
410
1709
|
const recoveredDiagnostics = emptyDiagnostics();
|
|
411
|
-
records = this.
|
|
1710
|
+
records = this.readCompactForEpoch(epoch, recoveredDiagnostics)
|
|
1711
|
+
.filter((record) => recordEpochId(record) === epochId);
|
|
412
1712
|
mergeDiagnostics(diagnostics, recoveredDiagnostics);
|
|
413
|
-
diagnostics.recovery =
|
|
1713
|
+
diagnostics.recovery = recovery.recovery;
|
|
1714
|
+
}
|
|
1715
|
+
else if (recovery.recovery === 'empty') {
|
|
1716
|
+
records = [];
|
|
1717
|
+
diagnostics.recovery = 'empty';
|
|
1718
|
+
}
|
|
1719
|
+
else {
|
|
1720
|
+
diagnostics.recovery = 'degraded';
|
|
414
1721
|
}
|
|
415
1722
|
}
|
|
416
1723
|
catch {
|
|
417
1724
|
diagnostics.recovery = 'degraded';
|
|
418
1725
|
}
|
|
419
1726
|
}
|
|
420
|
-
records.push(...this.
|
|
1727
|
+
records.push(...this.readActiveForEpoch(epoch, diagnostics, this.maxActiveBytes)
|
|
1728
|
+
.filter((record) => recordEpochId(record) === epochId));
|
|
1729
|
+
if (this.recoveryMarkerState(epoch) === 'degraded')
|
|
1730
|
+
diagnostics.recovery = 'degraded';
|
|
421
1731
|
if (diagnostics.recovery !== 'recovered' && (diagnostics.corruptLines > 0 || diagnostics.oversizedLines > 0 || diagnostics.truncated))
|
|
422
1732
|
diagnostics.recovery = 'degraded';
|
|
423
1733
|
return records;
|
|
424
1734
|
}
|
|
425
1735
|
readImportRecords() {
|
|
426
1736
|
this.ensureSecureDir();
|
|
1737
|
+
return this.readImportRecordsFromExistingDir();
|
|
1738
|
+
}
|
|
1739
|
+
readImportRecordsFromExistingDir() {
|
|
1740
|
+
this.managedGraphStateFiles();
|
|
1741
|
+
const epoch = this.readEpochState();
|
|
1742
|
+
const epochId = epoch.epochId;
|
|
427
1743
|
const diagnostics = emptyDiagnostics();
|
|
428
1744
|
const activePath = join(this.dir, ACTIVE_FILE);
|
|
429
1745
|
if (existsSync(activePath)) {
|
|
430
|
-
if (!this.secureRegularFile(activePath)
|
|
1746
|
+
if (!this.secureRegularFile(activePath)) {
|
|
1747
|
+
throw new MemoryGraphImportStateRejectedError();
|
|
1748
|
+
}
|
|
1749
|
+
const activeWindow = this.activeLogicalWindow(epoch, lstatSync(activePath, { bigint: true }));
|
|
1750
|
+
if (activeWindow.invalid || activeWindow.size > this.maxActiveBytes) {
|
|
431
1751
|
throw new MemoryGraphImportStateRejectedError();
|
|
432
1752
|
}
|
|
433
1753
|
}
|
|
434
|
-
return [...this.
|
|
1754
|
+
return [...this.readCompactForEpoch(epoch, diagnostics), ...this.readActiveForEpoch(epoch, diagnostics, this.maxActiveBytes)]
|
|
1755
|
+
.filter((record) => recordEpochId(record) === epochId);
|
|
435
1756
|
}
|
|
436
1757
|
readCompact(diagnostics) {
|
|
437
1758
|
const path = join(this.dir, COMPACT_FILE);
|
|
@@ -486,21 +1807,6 @@ export class LocalMemoryGraph {
|
|
|
486
1807
|
const newline = buffer.indexOf(0x0a);
|
|
487
1808
|
return this.parseBuffer(newline >= 0 ? buffer.subarray(newline + 1) : Buffer.alloc(0), diagnostics);
|
|
488
1809
|
}
|
|
489
|
-
readRawTail(path, maxBytes) {
|
|
490
|
-
const fd = openNoFollow(path, constants.O_RDONLY, 0o600);
|
|
491
|
-
try {
|
|
492
|
-
const size = fstatSync(fd).size;
|
|
493
|
-
const bytes = Math.min(size, maxBytes);
|
|
494
|
-
const buffer = readFdBytes(fd, bytes, size - bytes);
|
|
495
|
-
if (size <= bytes)
|
|
496
|
-
return buffer;
|
|
497
|
-
const newline = buffer.indexOf(0x0a);
|
|
498
|
-
return newline >= 0 ? buffer.subarray(newline + 1) : Buffer.alloc(0);
|
|
499
|
-
}
|
|
500
|
-
finally {
|
|
501
|
-
closeSync(fd);
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
1810
|
parseBuffer(buffer, diagnostics) {
|
|
505
1811
|
const out = [];
|
|
506
1812
|
for (const line of buffer.toString('utf8').split('\n')) {
|
|
@@ -533,30 +1839,79 @@ export class LocalMemoryGraph {
|
|
|
533
1839
|
}
|
|
534
1840
|
writeCompact(records) {
|
|
535
1841
|
const fitted = fitCompactRecords(records, this.maxCompactBytes);
|
|
536
|
-
if (records.length > 0 && fitted.records.length === 0)
|
|
537
|
-
return 0;
|
|
538
|
-
|
|
539
|
-
|
|
1842
|
+
if (records.length > 0 && fitted.records.length === 0) {
|
|
1843
|
+
return { records: 0, committedIdentity: null };
|
|
1844
|
+
}
|
|
1845
|
+
const committedIdentity = this.writeAtomic(join(this.dir, COMPACT_FILE), fitted.payload);
|
|
1846
|
+
return { records: fitted.records.length, committedIdentity };
|
|
540
1847
|
}
|
|
541
|
-
writeAtomic(path, payload) {
|
|
1848
|
+
writeAtomic(path, payload, syncDirectory = false, tempTag = String(this.now())) {
|
|
542
1849
|
this.ensureSecureDir();
|
|
543
1850
|
if (existsSync(path) && !this.secureRegularFile(path))
|
|
544
1851
|
throw new Error('memory_graph_path_rejected');
|
|
545
|
-
const temp = join(dirname(path), `.${basename(path)}.${
|
|
1852
|
+
const temp = join(dirname(path), `.${basename(path)}.${tempTag}.tmp`);
|
|
546
1853
|
const fd = openNoFollow(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
|
|
1854
|
+
let tempIdentity = null;
|
|
1855
|
+
let closed = false;
|
|
1856
|
+
let published = false;
|
|
547
1857
|
try {
|
|
548
|
-
|
|
1858
|
+
tempIdentity = lstatSync(temp, { bigint: true });
|
|
1859
|
+
const descriptorIdentity = fstatSync(fd, { bigint: true });
|
|
1860
|
+
if (!tempIdentity.isFile() || tempIdentity.isSymbolicLink()
|
|
1861
|
+
|| !descriptorIdentity.isFile() || descriptorIdentity.isSymbolicLink()
|
|
1862
|
+
|| !sameGraphFileIdentity(tempIdentity, descriptorIdentity)) {
|
|
1863
|
+
throw new Error('memory_graph_write_failed');
|
|
1864
|
+
}
|
|
1865
|
+
writeAll(fd, payload);
|
|
549
1866
|
fsyncSync(fd);
|
|
1867
|
+
closeSync(fd);
|
|
1868
|
+
closed = true;
|
|
1869
|
+
renameSync(temp, path);
|
|
1870
|
+
published = true;
|
|
1871
|
+
if (syncDirectory)
|
|
1872
|
+
this.syncGraphDirectory();
|
|
550
1873
|
}
|
|
551
1874
|
finally {
|
|
552
|
-
|
|
1875
|
+
if (!closed) {
|
|
1876
|
+
try {
|
|
1877
|
+
closeSync(fd);
|
|
1878
|
+
}
|
|
1879
|
+
catch {
|
|
1880
|
+
// Preserve the original write/fsync failure.
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
if (!published && tempIdentity !== null) {
|
|
1884
|
+
try {
|
|
1885
|
+
const currentIdentity = lstatSync(temp, { bigint: true });
|
|
1886
|
+
if (currentIdentity.isFile() && !currentIdentity.isSymbolicLink()
|
|
1887
|
+
&& sameGraphFileIdentity(tempIdentity, currentIdentity))
|
|
1888
|
+
unlinkSync(temp);
|
|
1889
|
+
}
|
|
1890
|
+
catch {
|
|
1891
|
+
// Never remove an unknown replacement; a same-name leftover is safer than clobbering it.
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
553
1894
|
}
|
|
554
|
-
|
|
1895
|
+
if (tempIdentity === null || !published)
|
|
1896
|
+
throw new Error('memory_graph_write_failed');
|
|
1897
|
+
return tempIdentity;
|
|
555
1898
|
}
|
|
556
1899
|
ensureSecureDir() {
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
1900
|
+
let stat;
|
|
1901
|
+
try {
|
|
1902
|
+
stat = lstatSync(this.dir);
|
|
1903
|
+
}
|
|
1904
|
+
catch (error) {
|
|
1905
|
+
if (!isObject(error) || error['code'] !== 'ENOENT')
|
|
1906
|
+
throw new Error('memory_graph_dir_rejected');
|
|
1907
|
+
try {
|
|
1908
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
1909
|
+
stat = lstatSync(this.dir);
|
|
1910
|
+
}
|
|
1911
|
+
catch {
|
|
1912
|
+
throw new Error('memory_graph_dir_rejected');
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
560
1915
|
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
561
1916
|
throw new Error('memory_graph_dir_rejected');
|
|
562
1917
|
}
|
|
@@ -588,30 +1943,91 @@ export class LocalMemoryGraph {
|
|
|
588
1943
|
const timestamp = Math.max(Math.floor(this.now()), latestTimestamp + 1);
|
|
589
1944
|
return join(this.dir, `memory_graph.v2.${timestamp}.jsonl.gz`);
|
|
590
1945
|
}
|
|
591
|
-
pruneArchives() {
|
|
1946
|
+
pruneArchives(retention = this.archiveRetention) {
|
|
592
1947
|
const files = this.archiveFiles();
|
|
593
|
-
for (const file of files.slice(0, Math.max(0, files.length -
|
|
1948
|
+
for (const file of files.slice(0, Math.max(0, files.length - retention))) {
|
|
594
1949
|
unlinkSync(join(this.dir, file));
|
|
1950
|
+
}
|
|
595
1951
|
}
|
|
596
|
-
writeRecoveryMarker() {
|
|
597
|
-
this.writeAtomic(join(this.dir, RECOVERY_FILE), Buffer.from(
|
|
1952
|
+
writeRecoveryMarker(epochId, state) {
|
|
1953
|
+
this.writeAtomic(join(this.dir, RECOVERY_FILE), Buffer.from(JSON.stringify({
|
|
1954
|
+
version: 1,
|
|
1955
|
+
recoveredAt: new Date(this.now()).toISOString(),
|
|
1956
|
+
epochId,
|
|
1957
|
+
state,
|
|
1958
|
+
}) + '\n', 'utf8'));
|
|
1959
|
+
}
|
|
1960
|
+
inspectArchivesForEpoch(epoch) {
|
|
1961
|
+
let unreadable = false;
|
|
1962
|
+
const maxArchiveBytes = gzipRotationByteBound(this.maxActiveBytes);
|
|
1963
|
+
const maxArchiveOutputBytes = safeRotationByteSum(this.maxActiveBytes, this.maxLineBytes);
|
|
1964
|
+
for (const file of this.currentArchiveFiles(epoch)) {
|
|
1965
|
+
const path = join(this.dir, file);
|
|
1966
|
+
try {
|
|
1967
|
+
if (maxArchiveBytes === null || maxArchiveOutputBytes === null) {
|
|
1968
|
+
unreadable = true;
|
|
1969
|
+
continue;
|
|
1970
|
+
}
|
|
1971
|
+
if (!this.secureRegularFile(path)) {
|
|
1972
|
+
unreadable = true;
|
|
1973
|
+
continue;
|
|
1974
|
+
}
|
|
1975
|
+
const compressed = this.readRawBounded(path, maxArchiveBytes);
|
|
1976
|
+
if (compressed === null) {
|
|
1977
|
+
unreadable = true;
|
|
1978
|
+
continue;
|
|
1979
|
+
}
|
|
1980
|
+
const raw = gunzipSync(compressed, { maxOutputLength: maxArchiveOutputBytes });
|
|
1981
|
+
const diagnostics = emptyDiagnostics();
|
|
1982
|
+
const records = this.parseBuffer(raw, diagnostics);
|
|
1983
|
+
unreadable ||= diagnostics.corruptLines > 0
|
|
1984
|
+
|| diagnostics.oversizedLines > 0
|
|
1985
|
+
|| diagnostics.truncated;
|
|
1986
|
+
if (records.some((record) => recordEpochId(record) === epoch.epochId)) {
|
|
1987
|
+
return { containsCurrent: true, unreadable };
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
catch {
|
|
1991
|
+
unreadable = true;
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
return { containsCurrent: false, unreadable };
|
|
598
1995
|
}
|
|
599
|
-
|
|
1996
|
+
recoveryMarkerState(epoch, maxBytes = this.maxLineBytes) {
|
|
600
1997
|
const path = join(this.dir, RECOVERY_FILE);
|
|
601
|
-
if (!existsSync(path)
|
|
602
|
-
return
|
|
1998
|
+
if (!existsSync(path))
|
|
1999
|
+
return null;
|
|
603
2000
|
try {
|
|
604
|
-
const
|
|
2001
|
+
const identity = lstatSync(path, { bigint: true });
|
|
2002
|
+
if (epoch.baseline?.recovery
|
|
2003
|
+
&& serializedSnapshotMatches(epoch.baseline.recovery, identity))
|
|
2004
|
+
return null;
|
|
2005
|
+
if (!identity.isFile() || identity.isSymbolicLink())
|
|
2006
|
+
return 'degraded';
|
|
2007
|
+
const bytes = this.readRawBounded(path, maxBytes);
|
|
605
2008
|
if (bytes === null)
|
|
606
|
-
return
|
|
2009
|
+
return 'degraded';
|
|
607
2010
|
const raw = JSON.parse(bytes.toString('utf8'));
|
|
608
|
-
|
|
2011
|
+
if (!isObject(raw) || raw['version'] !== 1
|
|
2012
|
+
|| typeof raw['recoveredAt'] !== 'string' || validIso(raw['recoveredAt']) === null)
|
|
2013
|
+
return 'degraded';
|
|
2014
|
+
const markerEpoch = Object.prototype.hasOwnProperty.call(raw, 'epochId')
|
|
2015
|
+
? safeEpochId(raw['epochId'])
|
|
2016
|
+
: LEGACY_EPOCH_ID;
|
|
2017
|
+
if (markerEpoch !== epoch.epochId)
|
|
2018
|
+
return 'degraded';
|
|
2019
|
+
const state = raw['state'];
|
|
2020
|
+
if (state === undefined)
|
|
2021
|
+
return 'recovered';
|
|
2022
|
+
return state === 'empty' || state === 'recovered' || state === 'degraded' ? state : 'degraded';
|
|
609
2023
|
}
|
|
610
2024
|
catch {
|
|
611
|
-
return
|
|
2025
|
+
return 'degraded';
|
|
612
2026
|
}
|
|
613
2027
|
}
|
|
614
|
-
clearRecoveryMarker() {
|
|
2028
|
+
clearRecoveryMarker(epoch, maxBytes = this.maxLineBytes) {
|
|
2029
|
+
if (this.recoveryMarkerState(epoch, maxBytes) === 'degraded')
|
|
2030
|
+
return;
|
|
615
2031
|
const path = join(this.dir, RECOVERY_FILE);
|
|
616
2032
|
if (existsSync(path) && this.secureRegularFile(path))
|
|
617
2033
|
unlinkSync(path);
|
|
@@ -631,6 +2047,232 @@ export class LocalMemoryGraph {
|
|
|
631
2047
|
}
|
|
632
2048
|
}
|
|
633
2049
|
}
|
|
2050
|
+
function rotationStageNames(generation) {
|
|
2051
|
+
return {
|
|
2052
|
+
compact: 'memory_graph.rotation.' + generation + '.compact.stage',
|
|
2053
|
+
archive: 'memory_graph.rotation.' + generation + '.archive.stage',
|
|
2054
|
+
active: 'memory_graph.rotation.' + generation + '.active.stage',
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
function rotationTempNames(generation) {
|
|
2058
|
+
const stages = rotationStageNames(generation);
|
|
2059
|
+
return {
|
|
2060
|
+
journal: '.' + ROTATION_JOURNAL_FILE + '.' + generation + '.tmp',
|
|
2061
|
+
compact: '.' + stages.compact + '.' + generation + '.tmp',
|
|
2062
|
+
archive: '.' + stages.archive + '.' + generation + '.tmp',
|
|
2063
|
+
active: '.' + stages.active + '.' + generation + '.tmp',
|
|
2064
|
+
};
|
|
2065
|
+
}
|
|
2066
|
+
function rotationFileDigest(payload) {
|
|
2067
|
+
return {
|
|
2068
|
+
size: payload.length,
|
|
2069
|
+
sha256: createHash('sha256').update(payload).digest('hex'),
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
function rotationDigestMatches(payload, expected) {
|
|
2073
|
+
const actual = rotationFileDigest(payload);
|
|
2074
|
+
return actual.size === expected.size && actual.sha256 === expected.sha256;
|
|
2075
|
+
}
|
|
2076
|
+
function rotationJournalImmutable(journal) {
|
|
2077
|
+
return {
|
|
2078
|
+
version: journal.version,
|
|
2079
|
+
targetGeneration: journal.targetGeneration,
|
|
2080
|
+
epochId: journal.epochId,
|
|
2081
|
+
createdAt: journal.createdAt,
|
|
2082
|
+
limits: {
|
|
2083
|
+
maxActiveBytes: journal.limits.maxActiveBytes,
|
|
2084
|
+
maxCompactBytes: journal.limits.maxCompactBytes,
|
|
2085
|
+
maxLineBytes: journal.limits.maxLineBytes,
|
|
2086
|
+
archiveRetention: journal.limits.archiveRetention,
|
|
2087
|
+
},
|
|
2088
|
+
source: {
|
|
2089
|
+
active: {
|
|
2090
|
+
snapshot: journal.source.active.snapshot,
|
|
2091
|
+
offset: journal.source.active.offset,
|
|
2092
|
+
size: journal.source.active.size,
|
|
2093
|
+
sha256: journal.source.active.sha256,
|
|
2094
|
+
},
|
|
2095
|
+
compact: journal.source.compact === null ? null : {
|
|
2096
|
+
snapshot: journal.source.compact.snapshot,
|
|
2097
|
+
size: journal.source.compact.size,
|
|
2098
|
+
sha256: journal.source.compact.sha256,
|
|
2099
|
+
},
|
|
2100
|
+
},
|
|
2101
|
+
target: {
|
|
2102
|
+
compact: {
|
|
2103
|
+
stageName: journal.target.compact.stageName,
|
|
2104
|
+
finalName: journal.target.compact.finalName,
|
|
2105
|
+
size: journal.target.compact.size,
|
|
2106
|
+
sha256: journal.target.compact.sha256,
|
|
2107
|
+
records: journal.target.compact.records,
|
|
2108
|
+
},
|
|
2109
|
+
archive: {
|
|
2110
|
+
stageName: journal.target.archive.stageName,
|
|
2111
|
+
finalName: journal.target.archive.finalName,
|
|
2112
|
+
size: journal.target.archive.size,
|
|
2113
|
+
sha256: journal.target.archive.sha256,
|
|
2114
|
+
},
|
|
2115
|
+
active: {
|
|
2116
|
+
stageName: journal.target.active.stageName,
|
|
2117
|
+
finalName: journal.target.active.finalName,
|
|
2118
|
+
size: journal.target.active.size,
|
|
2119
|
+
sha256: journal.target.active.sha256,
|
|
2120
|
+
},
|
|
2121
|
+
},
|
|
2122
|
+
};
|
|
2123
|
+
}
|
|
2124
|
+
function rotationTransactionId(journal) {
|
|
2125
|
+
return 'txn_' + createHash('sha256')
|
|
2126
|
+
.update(JSON.stringify(rotationJournalImmutable(journal)))
|
|
2127
|
+
.digest('hex');
|
|
2128
|
+
}
|
|
2129
|
+
function rotationJournalDigest(journal) {
|
|
2130
|
+
return createHash('sha256').update(JSON.stringify({
|
|
2131
|
+
...rotationJournalImmutable(journal),
|
|
2132
|
+
transactionId: journal.transactionId,
|
|
2133
|
+
phase: journal.phase,
|
|
2134
|
+
})).digest('hex');
|
|
2135
|
+
}
|
|
2136
|
+
function parseRotationJournal(value) {
|
|
2137
|
+
if (!isObject(value) || value['version'] !== 1)
|
|
2138
|
+
return null;
|
|
2139
|
+
const targetGeneration = typeof value['targetGeneration'] === 'string'
|
|
2140
|
+
&& ROTATION_GENERATION_PATTERN.test(value['targetGeneration'])
|
|
2141
|
+
? value['targetGeneration']
|
|
2142
|
+
: null;
|
|
2143
|
+
const transactionId = typeof value['transactionId'] === 'string'
|
|
2144
|
+
&& ROTATION_TRANSACTION_PATTERN.test(value['transactionId'])
|
|
2145
|
+
? value['transactionId']
|
|
2146
|
+
: null;
|
|
2147
|
+
const journalDigest = typeof value['journalDigest'] === 'string'
|
|
2148
|
+
&& /^[a-f0-9]{64}$/.test(value['journalDigest'])
|
|
2149
|
+
? value['journalDigest']
|
|
2150
|
+
: null;
|
|
2151
|
+
const phase = value['phase'] === 'prepared' || value['phase'] === 'committed'
|
|
2152
|
+
? value['phase']
|
|
2153
|
+
: null;
|
|
2154
|
+
const epochId = safeEpochId(value['epochId']);
|
|
2155
|
+
const createdAt = typeof value['createdAt'] === 'string' ? validIso(value['createdAt']) : null;
|
|
2156
|
+
if (!targetGeneration || !transactionId || !journalDigest
|
|
2157
|
+
|| !phase || !epochId || !createdAt)
|
|
2158
|
+
return null;
|
|
2159
|
+
const limitsValue = value['limits'];
|
|
2160
|
+
if (!isObject(limitsValue))
|
|
2161
|
+
return null;
|
|
2162
|
+
const maxActiveBytes = parseRotationLimit(limitsValue['maxActiveBytes']);
|
|
2163
|
+
const maxCompactBytes = parseRotationLimit(limitsValue['maxCompactBytes']);
|
|
2164
|
+
const maxLineBytes = parseRotationLimit(limitsValue['maxLineBytes']);
|
|
2165
|
+
const archiveRetention = parseRotationLimit(limitsValue['archiveRetention']);
|
|
2166
|
+
if (maxActiveBytes === null || maxCompactBytes === null || maxLineBytes === null
|
|
2167
|
+
|| archiveRetention === null)
|
|
2168
|
+
return null;
|
|
2169
|
+
const maxArchiveBytes = gzipRotationByteBound(maxActiveBytes);
|
|
2170
|
+
const maxCompactWithLineBytes = safeRotationByteSum(maxCompactBytes, maxLineBytes);
|
|
2171
|
+
if (maxArchiveBytes === null || maxCompactWithLineBytes === null)
|
|
2172
|
+
return null;
|
|
2173
|
+
const limits = {
|
|
2174
|
+
maxActiveBytes,
|
|
2175
|
+
maxCompactBytes,
|
|
2176
|
+
maxLineBytes,
|
|
2177
|
+
archiveRetention,
|
|
2178
|
+
};
|
|
2179
|
+
const sourceValue = value['source'];
|
|
2180
|
+
const targetValue = value['target'];
|
|
2181
|
+
if (!isObject(sourceValue) || !isObject(targetValue))
|
|
2182
|
+
return null;
|
|
2183
|
+
const activeSourceValue = sourceValue['active'];
|
|
2184
|
+
if (!isObject(activeSourceValue))
|
|
2185
|
+
return null;
|
|
2186
|
+
const activeSnapshot = parseGraphFileSnapshot(activeSourceValue['snapshot']);
|
|
2187
|
+
const activeDigest = parseRotationFileDigest(activeSourceValue, maxActiveBytes);
|
|
2188
|
+
const activeOffset = activeSourceValue['offset'];
|
|
2189
|
+
const activeSnapshotSize = activeSnapshot ? BigInt(activeSnapshot.size) : null;
|
|
2190
|
+
if (!activeSnapshot || !activeDigest || !Number.isSafeInteger(activeOffset)
|
|
2191
|
+
|| Number(activeOffset) < 0
|
|
2192
|
+
|| activeSnapshotSize === null
|
|
2193
|
+
|| activeSnapshotSize > BigInt(Number.MAX_SAFE_INTEGER)
|
|
2194
|
+
|| BigInt(Number(activeOffset)) + BigInt(activeDigest.size) !== activeSnapshotSize)
|
|
2195
|
+
return null;
|
|
2196
|
+
const activeSource = {
|
|
2197
|
+
snapshot: activeSnapshot,
|
|
2198
|
+
offset: Number(activeOffset),
|
|
2199
|
+
...activeDigest,
|
|
2200
|
+
};
|
|
2201
|
+
let compactSource = null;
|
|
2202
|
+
if (sourceValue['compact'] !== null) {
|
|
2203
|
+
if (!isObject(sourceValue['compact']))
|
|
2204
|
+
return null;
|
|
2205
|
+
const compactSnapshot = parseGraphFileSnapshot(sourceValue['compact']['snapshot']);
|
|
2206
|
+
const compactDigest = parseRotationFileDigest(sourceValue['compact'], maxCompactWithLineBytes);
|
|
2207
|
+
if (!compactSnapshot || !compactDigest
|
|
2208
|
+
|| compactSnapshot.size !== String(compactDigest.size))
|
|
2209
|
+
return null;
|
|
2210
|
+
compactSource = { snapshot: compactSnapshot, ...compactDigest };
|
|
2211
|
+
}
|
|
2212
|
+
const stages = rotationStageNames(targetGeneration);
|
|
2213
|
+
const compactTarget = parseRotationTarget(targetValue['compact'], maxCompactBytes, stages.compact, COMPACT_FILE);
|
|
2214
|
+
const archiveTarget = parseRotationTarget(targetValue['archive'], maxArchiveBytes, stages.archive, 'memory_graph.v2.' + targetGeneration + '.jsonl.gz');
|
|
2215
|
+
const activeTarget = parseRotationTarget(targetValue['active'], 0, stages.active, ACTIVE_FILE);
|
|
2216
|
+
const records = isObject(targetValue['compact']) ? targetValue['compact']['records'] : null;
|
|
2217
|
+
if (!compactTarget || !archiveTarget || !activeTarget
|
|
2218
|
+
|| !Number.isSafeInteger(records) || Number(records) < 0
|
|
2219
|
+
|| activeTarget.sha256 !== rotationFileDigest(Buffer.alloc(0)).sha256)
|
|
2220
|
+
return null;
|
|
2221
|
+
const journal = {
|
|
2222
|
+
version: 1,
|
|
2223
|
+
transactionId,
|
|
2224
|
+
journalDigest,
|
|
2225
|
+
targetGeneration,
|
|
2226
|
+
phase,
|
|
2227
|
+
epochId,
|
|
2228
|
+
createdAt,
|
|
2229
|
+
limits,
|
|
2230
|
+
source: { active: activeSource, compact: compactSource },
|
|
2231
|
+
target: {
|
|
2232
|
+
compact: { ...compactTarget, records: Number(records) },
|
|
2233
|
+
archive: archiveTarget,
|
|
2234
|
+
active: activeTarget,
|
|
2235
|
+
},
|
|
2236
|
+
};
|
|
2237
|
+
return rotationTransactionId(journal) === journal.transactionId
|
|
2238
|
+
&& rotationJournalDigest(journal) === journal.journalDigest
|
|
2239
|
+
? journal
|
|
2240
|
+
: null;
|
|
2241
|
+
}
|
|
2242
|
+
function parseRotationLimit(value) {
|
|
2243
|
+
return Number.isSafeInteger(value) && Number(value) > 0 ? Number(value) : null;
|
|
2244
|
+
}
|
|
2245
|
+
function safeRotationByteSum(left, right) {
|
|
2246
|
+
const sum = left + right;
|
|
2247
|
+
return Number.isSafeInteger(sum) ? sum : null;
|
|
2248
|
+
}
|
|
2249
|
+
function gzipRotationByteBound(sourceBytes) {
|
|
2250
|
+
if (!Number.isSafeInteger(sourceBytes) || sourceBytes < 0)
|
|
2251
|
+
return null;
|
|
2252
|
+
const source = BigInt(sourceBytes);
|
|
2253
|
+
// Mirrors zlib deflateBound's conservative stream bounds plus the gzip wrapper.
|
|
2254
|
+
const fixed = source + (source >> 3n) + (source >> 8n) + (source >> 9n) + 4n;
|
|
2255
|
+
const stored = source + (source >> 5n) + (source >> 7n) + (source >> 11n) + 7n;
|
|
2256
|
+
const bound = (fixed > stored ? fixed : stored) + 18n;
|
|
2257
|
+
return bound <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(bound) : null;
|
|
2258
|
+
}
|
|
2259
|
+
function parseRotationTarget(value, maxBytes, stageName, finalName) {
|
|
2260
|
+
if (!isObject(value) || value['stageName'] !== stageName || value['finalName'] !== finalName) {
|
|
2261
|
+
return null;
|
|
2262
|
+
}
|
|
2263
|
+
const digest = parseRotationFileDigest(value, maxBytes);
|
|
2264
|
+
return digest ? { stageName, finalName, ...digest } : null;
|
|
2265
|
+
}
|
|
2266
|
+
function parseRotationFileDigest(value, maxBytes) {
|
|
2267
|
+
if (!isObject(value))
|
|
2268
|
+
return null;
|
|
2269
|
+
const size = value['size'];
|
|
2270
|
+
const sha256 = value['sha256'];
|
|
2271
|
+
if (!Number.isSafeInteger(size) || Number(size) < 0 || Number(size) > maxBytes
|
|
2272
|
+
|| typeof sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(sha256))
|
|
2273
|
+
return null;
|
|
2274
|
+
return { size: Number(size), sha256 };
|
|
2275
|
+
}
|
|
634
2276
|
const MEMORY_GRAPH_REASON_PATTERN = /scoped memory-graph outcome ([+-]\d+\.\d{3}) \(boost=([+-]?\d+\.\d{2})\)/;
|
|
635
2277
|
export function sanitizeMemoryGraphSelectionReason(value) {
|
|
636
2278
|
if (typeof value !== 'string')
|
|
@@ -702,7 +2344,10 @@ function parseV2Record(value) {
|
|
|
702
2344
|
const geneId = typeof value['geneId'] === 'string' ? algo.safeMemoryGeneId(value['geneId']) : '';
|
|
703
2345
|
const status = value['status'];
|
|
704
2346
|
const at = typeof value['at'] === 'string' ? validIso(value['at']) : null;
|
|
705
|
-
|
|
2347
|
+
const hasEpoch = Object.prototype.hasOwnProperty.call(value, 'epochId');
|
|
2348
|
+
const epochId = hasEpoch ? safeEpochId(value['epochId']) : null;
|
|
2349
|
+
if (!workspaceScope || !userScope || !signalFingerprint || !geneId
|
|
2350
|
+
|| (status !== 'success' && status !== 'failed') || !at || (hasEpoch && !epochId))
|
|
706
2351
|
return null;
|
|
707
2352
|
return {
|
|
708
2353
|
version: 2,
|
|
@@ -716,6 +2361,7 @@ function parseV2Record(value) {
|
|
|
716
2361
|
status,
|
|
717
2362
|
score: clampScore(Number(value['score'])),
|
|
718
2363
|
at,
|
|
2364
|
+
...(epochId ? { epochId } : {}),
|
|
719
2365
|
...(safeToken(value['sourceFingerprint'], 128) ? { sourceFingerprint: safeToken(value['sourceFingerprint'], 128) } : {}),
|
|
720
2366
|
...(safeToken(value['sourceScope'], 128) ? { sourceScope: safeToken(value['sourceScope'], 128) } : {}),
|
|
721
2367
|
...(safeToken(value['legacySourceFingerprint'], 128) ? { legacySourceFingerprint: safeToken(value['legacySourceFingerprint'], 128) } : {}),
|
|
@@ -723,6 +2369,33 @@ function parseV2Record(value) {
|
|
|
723
2369
|
...(positiveCount(value['failCount']) !== undefined ? { failCount: positiveCount(value['failCount']) } : {}),
|
|
724
2370
|
};
|
|
725
2371
|
}
|
|
2372
|
+
function sealV1OutcomePlan(summary, data) {
|
|
2373
|
+
const plan = Object.freeze({ ...summary });
|
|
2374
|
+
if (data)
|
|
2375
|
+
memoryGraphV1OutcomePlans.set(plan, data);
|
|
2376
|
+
return plan;
|
|
2377
|
+
}
|
|
2378
|
+
function collectImportFingerprints(records, workspaceScope, userScope, sourceScope) {
|
|
2379
|
+
const values = new Set();
|
|
2380
|
+
for (const record of records) {
|
|
2381
|
+
if (record.workspaceScope !== workspaceScope || record.userScope !== userScope)
|
|
2382
|
+
continue;
|
|
2383
|
+
if (record.sourceScope && record.sourceScope !== sourceScope)
|
|
2384
|
+
continue;
|
|
2385
|
+
addImportFingerprints(values, record);
|
|
2386
|
+
}
|
|
2387
|
+
return values;
|
|
2388
|
+
}
|
|
2389
|
+
function hasImportFingerprint(values, record) {
|
|
2390
|
+
return Boolean((record.sourceFingerprint && values.has(record.sourceFingerprint))
|
|
2391
|
+
|| (record.legacySourceFingerprint && values.has(record.legacySourceFingerprint)));
|
|
2392
|
+
}
|
|
2393
|
+
function addImportFingerprints(values, record) {
|
|
2394
|
+
if (record.sourceFingerprint)
|
|
2395
|
+
values.add(record.sourceFingerprint);
|
|
2396
|
+
if (record.legacySourceFingerprint)
|
|
2397
|
+
values.add(record.legacySourceFingerprint);
|
|
2398
|
+
}
|
|
726
2399
|
function parseV1Outcome(value, workspaceScope, userScope, sourceScope) {
|
|
727
2400
|
if (!workspaceScope || !isObject(value) || value['type'] !== 'MemoryGraphEvent' || value['kind'] !== 'outcome')
|
|
728
2401
|
return null;
|
|
@@ -782,9 +2455,10 @@ function compactRecords(records, maxEdges) {
|
|
|
782
2455
|
.slice(0, maxEdges);
|
|
783
2456
|
}
|
|
784
2457
|
function compactRecordKey(record) {
|
|
2458
|
+
const epoch = recordEpochId(record);
|
|
785
2459
|
return record.provenance === 'v1_import' && record.sourceFingerprint
|
|
786
|
-
?
|
|
787
|
-
: `${record.workspaceScope}\u0000${record.userScope}\u0000${record.signalFingerprint}\u0000${record.geneId}`;
|
|
2460
|
+
? `${epoch}\u0000import\u0000${record.workspaceScope}\u0000${record.userScope}\u0000${record.sourceScope ?? 'legacy-unscoped'}\u0000${record.sourceFingerprint}`
|
|
2461
|
+
: `${epoch}\u0000${record.workspaceScope}\u0000${record.userScope}\u0000${record.signalFingerprint}\u0000${record.geneId}`;
|
|
788
2462
|
}
|
|
789
2463
|
function mergeRecoveryRecords(compact, archives, maxEdges) {
|
|
790
2464
|
const preserved = compactRecords(compact, compact.length);
|
|
@@ -846,6 +2520,127 @@ function fileExceeds(path, maxBytes) {
|
|
|
846
2520
|
function openNoFollow(path, flags, mode) {
|
|
847
2521
|
return openSync(path, flags | constants.O_NOFOLLOW, mode);
|
|
848
2522
|
}
|
|
2523
|
+
function writeAll(fd, payload, position = null) {
|
|
2524
|
+
let offset = 0;
|
|
2525
|
+
while (offset < payload.length) {
|
|
2526
|
+
const written = writeSync(fd, payload, offset, payload.length - offset, position === null ? null : position + offset);
|
|
2527
|
+
if (written <= 0)
|
|
2528
|
+
throw new Error('memory_graph_write_failed');
|
|
2529
|
+
offset += written;
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
function sameGraphFileIdentity(left, right) {
|
|
2533
|
+
const hasStableFileId = left.dev !== 0n || left.ino !== 0n || right.dev !== 0n || right.ino !== 0n;
|
|
2534
|
+
if (hasStableFileId)
|
|
2535
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
2536
|
+
return left.birthtimeNs === right.birthtimeNs && left.mode === right.mode;
|
|
2537
|
+
}
|
|
2538
|
+
function sameGraphFileSnapshot(left, right) {
|
|
2539
|
+
return sameGraphFileIdentity(left, right)
|
|
2540
|
+
&& left.mode === right.mode
|
|
2541
|
+
&& left.size === right.size
|
|
2542
|
+
&& left.mtimeNs === right.mtimeNs
|
|
2543
|
+
&& left.ctimeNs === right.ctimeNs;
|
|
2544
|
+
}
|
|
2545
|
+
function serializeGraphFileSnapshot(stat) {
|
|
2546
|
+
return {
|
|
2547
|
+
dev: String(stat.dev),
|
|
2548
|
+
ino: String(stat.ino),
|
|
2549
|
+
birthtimeNs: String(stat.birthtimeNs),
|
|
2550
|
+
mode: String(stat.mode),
|
|
2551
|
+
size: String(stat.size),
|
|
2552
|
+
mtimeNs: String(stat.mtimeNs),
|
|
2553
|
+
ctimeNs: String(stat.ctimeNs),
|
|
2554
|
+
};
|
|
2555
|
+
}
|
|
2556
|
+
function serializedIdentityMatches(snapshot, stat) {
|
|
2557
|
+
const hasStableFileId = snapshot.dev !== '0' || snapshot.ino !== '0'
|
|
2558
|
+
|| stat.dev !== 0n || stat.ino !== 0n;
|
|
2559
|
+
if (hasStableFileId)
|
|
2560
|
+
return snapshot.dev === String(stat.dev) && snapshot.ino === String(stat.ino);
|
|
2561
|
+
return snapshot.birthtimeNs === String(stat.birthtimeNs) && snapshot.mode === String(stat.mode);
|
|
2562
|
+
}
|
|
2563
|
+
function serializedSnapshotMatches(snapshot, stat) {
|
|
2564
|
+
return serializedIdentityMatches(snapshot, stat)
|
|
2565
|
+
&& snapshot.mode === String(stat.mode)
|
|
2566
|
+
&& snapshot.size === String(stat.size)
|
|
2567
|
+
&& snapshot.mtimeNs === String(stat.mtimeNs)
|
|
2568
|
+
&& snapshot.ctimeNs === String(stat.ctimeNs);
|
|
2569
|
+
}
|
|
2570
|
+
function parseGraphFileSnapshot(value) {
|
|
2571
|
+
if (!isObject(value))
|
|
2572
|
+
return null;
|
|
2573
|
+
const fields = ['dev', 'ino', 'birthtimeNs', 'mode', 'size', 'mtimeNs', 'ctimeNs'];
|
|
2574
|
+
for (const field of fields) {
|
|
2575
|
+
const candidate = value[field];
|
|
2576
|
+
if (typeof candidate !== 'string' || !/^\d{1,40}$/.test(candidate))
|
|
2577
|
+
return null;
|
|
2578
|
+
}
|
|
2579
|
+
return {
|
|
2580
|
+
dev: value['dev'],
|
|
2581
|
+
ino: value['ino'],
|
|
2582
|
+
birthtimeNs: value['birthtimeNs'],
|
|
2583
|
+
mode: value['mode'],
|
|
2584
|
+
size: value['size'],
|
|
2585
|
+
mtimeNs: value['mtimeNs'],
|
|
2586
|
+
ctimeNs: value['ctimeNs'],
|
|
2587
|
+
};
|
|
2588
|
+
}
|
|
2589
|
+
function parseEpochBaseline(value) {
|
|
2590
|
+
if (!isObject(value) || !Object.prototype.hasOwnProperty.call(value, 'active')
|
|
2591
|
+
|| !Object.prototype.hasOwnProperty.call(value, 'compact')
|
|
2592
|
+
|| !Array.isArray(value['archives']))
|
|
2593
|
+
return null;
|
|
2594
|
+
let active = null;
|
|
2595
|
+
if (value['active'] !== null) {
|
|
2596
|
+
if (!isObject(value['active']))
|
|
2597
|
+
return null;
|
|
2598
|
+
const snapshot = parseGraphFileSnapshot(value['active']['snapshot']);
|
|
2599
|
+
const offset = value['active']['offset'];
|
|
2600
|
+
if (!snapshot || !Number.isSafeInteger(offset) || Number(offset) < 0
|
|
2601
|
+
|| snapshot.size !== String(offset))
|
|
2602
|
+
return null;
|
|
2603
|
+
active = { snapshot, offset: Number(offset) };
|
|
2604
|
+
}
|
|
2605
|
+
const compact = value['compact'] === null
|
|
2606
|
+
? null
|
|
2607
|
+
: parseGraphFileSnapshot(value['compact']);
|
|
2608
|
+
if (value['compact'] !== null && !compact)
|
|
2609
|
+
return null;
|
|
2610
|
+
const hasRecovery = Object.prototype.hasOwnProperty.call(value, 'recovery');
|
|
2611
|
+
const recovery = !hasRecovery || value['recovery'] === null
|
|
2612
|
+
? null
|
|
2613
|
+
: parseGraphFileSnapshot(value['recovery']);
|
|
2614
|
+
if (hasRecovery && value['recovery'] !== null && !recovery)
|
|
2615
|
+
return null;
|
|
2616
|
+
const archives = [];
|
|
2617
|
+
const names = new Set();
|
|
2618
|
+
for (const entry of value['archives']) {
|
|
2619
|
+
if (!isObject(entry) || typeof entry['name'] !== 'string'
|
|
2620
|
+
|| !ARCHIVE_PATTERN.test(entry['name']) || names.has(entry['name']))
|
|
2621
|
+
return null;
|
|
2622
|
+
const snapshot = parseGraphFileSnapshot(entry['snapshot']);
|
|
2623
|
+
if (!snapshot)
|
|
2624
|
+
return null;
|
|
2625
|
+
names.add(entry['name']);
|
|
2626
|
+
archives.push({ name: entry['name'], snapshot });
|
|
2627
|
+
}
|
|
2628
|
+
return { active, compact, ...(hasRecovery ? { recovery } : {}), archives };
|
|
2629
|
+
}
|
|
2630
|
+
function assertPathMissing(path, reason) {
|
|
2631
|
+
try {
|
|
2632
|
+
lstatSync(path);
|
|
2633
|
+
}
|
|
2634
|
+
catch (error) {
|
|
2635
|
+
if (isObject(error) && error['code'] === 'ENOENT')
|
|
2636
|
+
return;
|
|
2637
|
+
throw new Error(reason);
|
|
2638
|
+
}
|
|
2639
|
+
throw new Error(reason);
|
|
2640
|
+
}
|
|
2641
|
+
function recordEpochId(record) {
|
|
2642
|
+
return record.epochId ?? LEGACY_EPOCH_ID;
|
|
2643
|
+
}
|
|
849
2644
|
function readFdBytes(fd, length, position) {
|
|
850
2645
|
const buffer = Buffer.alloc(length);
|
|
851
2646
|
let offset = 0;
|
|
@@ -866,6 +2661,10 @@ function safeToken(value, maxChars) {
|
|
|
866
2661
|
const trimmed = value.trim();
|
|
867
2662
|
return trimmed.length > 0 && trimmed.length <= maxChars ? trimmed : null;
|
|
868
2663
|
}
|
|
2664
|
+
function safeEpochId(value) {
|
|
2665
|
+
const token = safeToken(value, 128);
|
|
2666
|
+
return token && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(token) ? token : null;
|
|
2667
|
+
}
|
|
869
2668
|
function boundedOperatorCount(value) {
|
|
870
2669
|
const count = Number(value);
|
|
871
2670
|
return Number.isFinite(count) && count > 0 ? Math.min(1_000_000, Math.floor(count)) : 0;
|
|
@@ -875,7 +2674,8 @@ function positiveCount(value) {
|
|
|
875
2674
|
return Number.isFinite(count) && count > 0 ? Math.min(1_000_000, Math.floor(count)) : undefined;
|
|
876
2675
|
}
|
|
877
2676
|
function positiveInt(value, fallback) {
|
|
878
|
-
|
|
2677
|
+
const parsed = Math.floor(Number(value));
|
|
2678
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
|
|
879
2679
|
}
|
|
880
2680
|
function clampScore(value) {
|
|
881
2681
|
return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0;
|