dsh-live-compact 1.1.14 → 1.1.15
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/CHANGELOG.md +13 -0
- package/README.md +43 -16
- package/adapter.js +43 -4
- package/bin/dsh-live-compact.js +44 -11
- package/bin/shadow-diagnostics.js +181 -0
- package/client.js +21 -3
- package/gate.js +22 -22
- package/index.js +336 -187
- package/package.json +9 -7
- package/plan.js +5 -3
- package/settings.js +40 -1
- package/shadow-search.js +26 -7
- package/shadow.js +95 -105
- package/shell.js +102 -58
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-live-compact",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.15",
|
|
4
4
|
"description": "In-place newest-turn compaction for DeepSeek Harness. Compress while the task runs and keep the prefix.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "MerkyorLynn <268568828+MerkyorLynn@users.noreply.github.com>",
|
|
@@ -44,18 +44,20 @@
|
|
|
44
44
|
"compaction"
|
|
45
45
|
],
|
|
46
46
|
"scripts": {
|
|
47
|
-
"test:gate": "node test/p0-gate.mjs && node test/p0-blockers.mjs && node test/excerpt.mjs && node test/shadow-worker.mjs && node test/shadow-worker-pool.mjs && node test/shadow-worker-fuse.mjs && node test/v107.mjs && node --test test/turn-end-bridge.mjs && node --test test/failed-diagnostics.test.mjs test/public-exports.test.mjs test/cooldown.test.mjs test/gate-config.test.mjs test/stand-down.test.mjs test/drain-stopline.mjs test/scan-once.mjs test/issue-19.mjs test/issue-20.mjs test/issue-34.mjs test/issue-49.mjs test/issue-62.mjs test/review-derived.test.mjs test/windows-acl.test.mjs test/issue-27.mjs test/issue-29.mjs test/issue-29-notice.mjs test/client-settings.test.mjs test/settings-integration.test.mjs test/runtime-lifecycle.mjs test/shadow-lifecycle.mjs test/finalize-over-32000.mjs test/p1-fable-review.mjs",
|
|
48
|
-
"test:compat41": "node test/compat
|
|
47
|
+
"test:gate": "node test/p0-gate.mjs && node test/p0-blockers.mjs && node test/excerpt.mjs && node test/shadow-worker.mjs && node test/shadow-worker-pool.mjs && node test/shadow-worker-fuse.mjs && node test/v107.mjs && node --test test/turn-end-bridge.mjs && node --test test/failed-diagnostics.test.mjs test/public-exports.test.mjs test/cooldown.test.mjs test/gate-config.test.mjs test/stand-down.test.mjs test/drain-stopline.mjs test/scan-once.mjs test/issue-19.mjs test/issue-20.mjs test/issue-34.mjs test/issue-49.mjs test/issue-62.mjs test/review-derived.test.mjs test/windows-acl.test.mjs test/issue-27.mjs test/issue-29.mjs test/issue-29-notice.mjs test/client-settings.test.mjs test/settings-integration.test.mjs test/runtime-lifecycle.mjs test/shadow-lifecycle.mjs test/finalize-over-32000.mjs test/p1-fable-review.mjs test/adapter.test.mjs test/cli-status.test.mjs test/cli-search.test.mjs test/min-gain.test.mjs test/diagnostics.test.mjs && node test/decision-log-budget.mjs",
|
|
48
|
+
"test:compat41": "node test/compat/run.mjs 41",
|
|
49
|
+
"test:compat42": "node test/compat/run.mjs 42",
|
|
50
|
+
"test:compat-rc12": "node test/compat/run.mjs rc12",
|
|
49
51
|
"test:live-gate": "python3 -B -m unittest discover -s test/live-fill -p test_*.py"
|
|
50
52
|
},
|
|
51
53
|
"engines": {
|
|
52
54
|
"node": "^22.19 || >=24",
|
|
53
|
-
"dsh": ">=0.2.0-rc.2 <0.3.0"
|
|
55
|
+
"dsh": ">=0.2.0-rc.2 <0.3.0-0 || 0.2.1-rc.3 || >=0.2.2-rc.1 <0.3.0-0 || >=0.2.3-alpha.2 <0.3.0-0"
|
|
54
56
|
},
|
|
55
57
|
"peerDependencies": {
|
|
56
|
-
"@deepseek-ai/dsh-compaction": ">=0.2.0-rc.2 <0.3.0",
|
|
57
|
-
"@deepseek-ai/dsh-compaction-basic": ">=0.2.0-rc.2 <0.3.0",
|
|
58
|
-
"@deepseek-ai/dsh-llm": ">=0.2.0-rc.2 <0.3.0",
|
|
58
|
+
"@deepseek-ai/dsh-compaction": ">=0.2.0-rc.2 <0.3.0-0 || 0.2.1-rc.3 || >=0.2.2-rc.1 <0.3.0-0 || >=0.2.3-alpha.2 <0.3.0-0",
|
|
59
|
+
"@deepseek-ai/dsh-compaction-basic": ">=0.2.0-rc.2 <0.3.0-0 || 0.2.1-rc.3 || >=0.2.2-rc.1 <0.3.0-0 || >=0.2.3-alpha.2 <0.3.0-0",
|
|
60
|
+
"@deepseek-ai/dsh-llm": ">=0.2.0-rc.2 <0.3.0-0 || 0.2.1-rc.3 || >=0.2.2-rc.1 <0.3.0-0 || >=0.2.3-alpha.2 <0.3.0-0",
|
|
59
61
|
"@deepseek-ai/schemastery": ">=3.18.0 <4",
|
|
60
62
|
"react": ">=18"
|
|
61
63
|
},
|
package/plan.js
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* Open background jobs do not delay the cut; the card records that they were still running.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { readEngineSetting } from "./settings.js";
|
|
12
|
+
|
|
11
13
|
const MARK = "Spine extract.";
|
|
12
14
|
const KEEP_BUDGET = 8000;
|
|
13
15
|
const TEXTUAL = new Set(["text", "input_text", "output_text"]);
|
|
@@ -786,9 +788,9 @@ export function resolveProviderBaseURL({
|
|
|
786
788
|
return catalogProviderURL(provider, catalog, model);
|
|
787
789
|
}
|
|
788
790
|
|
|
789
|
-
export function resolveEngine({ provider = "", baseURL = "", env = process.env } = {}) {
|
|
790
|
-
const override =
|
|
791
|
-
if (override === "local" || override === "cloud") return
|
|
791
|
+
export function resolveEngine({ provider = "", baseURL = "", env = process.env, config } = {}) {
|
|
792
|
+
const override = readEngineSetting(config, env);
|
|
793
|
+
if (override.engine === "local" || override.engine === "cloud") return override;
|
|
792
794
|
if (/strata/i.test(String(provider || ""))) return { engine: "local", source: "provider" };
|
|
793
795
|
if (provider === "deepseek-account" && baseURL) {
|
|
794
796
|
try {
|
package/settings.js
CHANGED
|
@@ -10,6 +10,9 @@ export const DEFAULTS = Object.freeze({
|
|
|
10
10
|
chunkMax: 32000, // 一刀上限,等于卡片轨道
|
|
11
11
|
bigGate: 650000, // 绝对停切线
|
|
12
12
|
cooldownMs: 0, // 0 = 只用 seq 一次性跳过
|
|
13
|
+
minGainRatio: 0, // 0 = 关闭首刀收益门
|
|
14
|
+
engine: "auto",
|
|
15
|
+
shadowMaxMb: 256,
|
|
13
16
|
});
|
|
14
17
|
|
|
15
18
|
/** 旧的环境变量仍然有效,但只作为 config 缺席时的兜底。 */
|
|
@@ -21,6 +24,9 @@ export const ENV = Object.freeze({
|
|
|
21
24
|
chunkMin: "SPINE_CHUNK_MIN",
|
|
22
25
|
chunkMax: "SPINE_CHUNK_MAX",
|
|
23
26
|
cooldownMs: "SPINE_COOLDOWN_MS",
|
|
27
|
+
minGainRatio: "SPINE_MIN_GAIN_RATIO",
|
|
28
|
+
engine: "SPINE_ENGINE",
|
|
29
|
+
shadowMaxMb: "SPINE_SHADOW_MAX_MB",
|
|
24
30
|
});
|
|
25
31
|
|
|
26
32
|
// volatile 字段的现值是 cosmokit 的取值对象,读之前先摊平。
|
|
@@ -72,17 +78,41 @@ const finite = (value) => {
|
|
|
72
78
|
return Number.isFinite(number) ? number : undefined;
|
|
73
79
|
};
|
|
74
80
|
|
|
81
|
+
const ENGINES = ["auto", "local", "cloud"];
|
|
82
|
+
|
|
83
|
+
export function readEngineSetting(config, env = process.env) {
|
|
84
|
+
const configured = plain(config?.engine);
|
|
85
|
+
if (ENGINES.includes(configured)) return { engine: configured, source: "config" };
|
|
86
|
+
const fallback = String(env?.[ENV.engine] || "").trim().toLowerCase();
|
|
87
|
+
if (fallback === "local" || fallback === "cloud") return { engine: fallback, source: "env" };
|
|
88
|
+
return { engine: DEFAULTS.engine };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function configuredShadowMaxMb(config) {
|
|
92
|
+
const mb = finite(config?.shadowMaxMb);
|
|
93
|
+
return mb > 0 && Number.isSafeInteger(Math.floor(mb * 1024 * 1024)) && mb * 1024 * 1024 >= 1 ? mb : undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
75
96
|
export function readSettings(config = {}, env = process.env) {
|
|
76
97
|
const next = {};
|
|
77
98
|
for (const [key, fallback] of Object.entries(DEFAULTS)) {
|
|
99
|
+
if (key === "engine" || key === "shadowMaxMb") continue;
|
|
78
100
|
const envName = ENV[key];
|
|
79
101
|
const numeric = (value) => {
|
|
80
102
|
const number = finite(value);
|
|
81
|
-
|
|
103
|
+
if (key === "keepRounds" && (!Number.isInteger(number) || number < 1)) return undefined;
|
|
104
|
+
if (key === "minGainRatio" && number < 0) return undefined;
|
|
105
|
+
return number;
|
|
82
106
|
};
|
|
83
107
|
next[key] =
|
|
84
108
|
numeric(config?.[key]) ?? numeric(envName ? env?.[envName] : undefined) ?? fallback;
|
|
85
109
|
}
|
|
110
|
+
next.engine = readEngineSetting(config, env).engine;
|
|
111
|
+
const bytes = Number(env?.SPINE_SHADOW_MAX_BYTES);
|
|
112
|
+
const mb = Number(env?.[ENV.shadowMaxMb]);
|
|
113
|
+
next.shadowMaxMb = configuredShadowMaxMb(config) ??
|
|
114
|
+
(Number.isFinite(bytes) && bytes > 0 ? bytes / (1024 * 1024)
|
|
115
|
+
: Number.isFinite(mb) && mb > 0 ? mb : DEFAULTS.shadowMaxMb);
|
|
86
116
|
if (!next.pointerTokens) next.pointerTokens = next.chunkMax;
|
|
87
117
|
return Object.freeze(next);
|
|
88
118
|
}
|
|
@@ -132,5 +162,14 @@ export function configSchema(z, stockSchema) {
|
|
|
132
162
|
cooldownMs: count(0)
|
|
133
163
|
.description("官方压缩之后跳过小切的时间窗;0 = 只按事件序号跳过一次。")
|
|
134
164
|
.volatile(),
|
|
165
|
+
minGainRatio: z.number().min(0)
|
|
166
|
+
.description("首刀最小节省/重写比例;0 = 关闭,紧急线以上照常切。")
|
|
167
|
+
.volatile(),
|
|
168
|
+
engine: z.union(ENGINES.map((value) => z.const(value)))
|
|
169
|
+
.description("小切模式:auto 按地址判定,local 单刀,cloud 可连续收尾。")
|
|
170
|
+
.volatile(),
|
|
171
|
+
shadowMaxMb: z.number().min(1 / (1024 * 1024))
|
|
172
|
+
.description("shadow 容量上限(MiB);留空沿用环境变量或 256 MiB。")
|
|
173
|
+
.volatile(),
|
|
135
174
|
});
|
|
136
175
|
}
|
package/shadow-search.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// 由插件自己维护(本模块不另立一套过滤规则)
|
|
15
15
|
// · 返回值是纯数据,不含句柄、不读环境变量、不碰全局状态
|
|
16
16
|
|
|
17
|
-
import {
|
|
17
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs";
|
|
18
18
|
import { resolve } from "node:path";
|
|
19
19
|
import { listPluginShadows, sessionDir } from "./shadow.js";
|
|
20
20
|
|
|
@@ -68,17 +68,36 @@ export function searchShadow(options = {}) {
|
|
|
68
68
|
|
|
69
69
|
// 只列这一层:listPluginShadows 内部就是一次 readdir + 只收符合命名的普通文件,
|
|
70
70
|
// 因此天然不会递归进别的会话目录。
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
71
|
+
let directoryStat;
|
|
72
|
+
let files = [];
|
|
73
|
+
try {
|
|
74
|
+
directoryStat = lstatSync(directory);
|
|
75
|
+
if (directoryStat.isDirectory()) files = listPluginShadows(directory, { stat: lstatSync });
|
|
76
|
+
} catch {}
|
|
77
|
+
for (const file of files) {
|
|
78
|
+
let fd;
|
|
76
79
|
let text;
|
|
77
80
|
try {
|
|
78
|
-
|
|
81
|
+
fd = openSync(file.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
82
|
+
const opened = fstatSync(fd);
|
|
83
|
+
const named = lstatSync(file.path);
|
|
84
|
+
const parent = lstatSync(directory);
|
|
85
|
+
if (!opened.isFile() || !named.isFile() || opened.dev !== named.dev || opened.ino !== named.ino ||
|
|
86
|
+
opened.size > maxFileBytes || !parent.isDirectory() || parent.dev !== directoryStat.dev ||
|
|
87
|
+
parent.ino !== directoryStat.ino) throw new Error("unsupported search file");
|
|
88
|
+
const data = Buffer.alloc(opened.size);
|
|
89
|
+
let end = 0;
|
|
90
|
+
while (end < data.length) {
|
|
91
|
+
const bytes = readSync(fd, data, end, data.length - end, end);
|
|
92
|
+
if (!bytes) break;
|
|
93
|
+
end += bytes;
|
|
94
|
+
}
|
|
95
|
+
text = data.toString("utf8", 0, end);
|
|
79
96
|
} catch {
|
|
80
97
|
skipped += 1;
|
|
81
98
|
continue;
|
|
99
|
+
} finally {
|
|
100
|
+
if (fd !== undefined) closeSync(fd);
|
|
82
101
|
}
|
|
83
102
|
scanned += 1;
|
|
84
103
|
let hitThisFile = false;
|
package/shadow.js
CHANGED
|
@@ -58,10 +58,16 @@ const lockedFiles = new Map();
|
|
|
58
58
|
const MAX_LOCK_ENTRIES = 4096;
|
|
59
59
|
let shadowFuseState = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
60
60
|
const shadowWarnings = new Set();
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
61
|
+
let rotationScanCount = 0;
|
|
62
|
+
let decisionWriteFailures = 0;
|
|
63
|
+
|
|
64
|
+
export function getRotationScanCount() {
|
|
65
|
+
return rotationScanCount;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function getDecisionWriteFailureCount() {
|
|
69
|
+
return decisionWriteFailures;
|
|
70
|
+
}
|
|
65
71
|
|
|
66
72
|
// No shared byte ledger. A positively dead holder leaves an immutable fence:
|
|
67
73
|
// recovery enables the original shared scans, never ownership or an estimate.
|
|
@@ -681,6 +687,9 @@ export function noteShadowWarning(logger, error) {
|
|
|
681
687
|
const key = separateReason ? `${code}:${step}` : code;
|
|
682
688
|
if (shadowWarnings.has(key)) return;
|
|
683
689
|
shadowWarnings.add(key);
|
|
690
|
+
if (error?.code === "ESHADOWACCESS") {
|
|
691
|
+
appendMaintenanceStatus(shadowDirectory(), { phase: "shadow-access", code: "ESHADOWACCESS" });
|
|
692
|
+
}
|
|
684
693
|
const status = error?.cause?.status ?? error?.status;
|
|
685
694
|
const where = step ? ` ${step}` : "";
|
|
686
695
|
const exit = status == null ? "" : ` exit ${status}`;
|
|
@@ -689,7 +698,7 @@ export function noteShadowWarning(logger, error) {
|
|
|
689
698
|
const SESSION_MARK = /^# spine-session (\S+)/;
|
|
690
699
|
|
|
691
700
|
export function isPluginShadowName(name) {
|
|
692
|
-
return
|
|
701
|
+
return PLUGIN_NAME.test(name);
|
|
693
702
|
}
|
|
694
703
|
|
|
695
704
|
export function sanitizeSessionKey(key) {
|
|
@@ -730,88 +739,24 @@ export const CUTS_NAME = "spine-cuts.jsonl";
|
|
|
730
739
|
export const DECISIONS_NAME = "spine-decisions.jsonl";
|
|
731
740
|
export const MAINTENANCE_NAME = "spine-maintenance.jsonl";
|
|
732
741
|
const CUTS_LOG_MAX_BYTES = 1024 * 1024;
|
|
742
|
+
const DECISIONS_LOG_MAX_BYTES = 1024 * 1024;
|
|
733
743
|
const MAINTENANCE_LOG_MAX_BYTES = 256 * 1024;
|
|
734
744
|
|
|
735
|
-
|
|
745
|
+
// The third argument remains accepted for callers that passed rotation protection.
|
|
746
|
+
export function appendDecision(dir, record = {}, _options = {}) {
|
|
747
|
+
if (!existsSync(dir)) return false;
|
|
736
748
|
try {
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
...record,
|
|
742
|
-
|
|
743
|
-
const file = join(dir, DECISIONS_NAME);
|
|
744
|
-
return withShadowRoot(dir, () => {
|
|
745
|
-
const path = scopedFile(file, rotationScope.root);
|
|
746
|
-
if (!path) throw coordinationError(new Error("shadow decision outside root scope"));
|
|
747
|
-
const rotationKey = rotationScope.root;
|
|
748
|
-
const now = Date.now();
|
|
749
|
-
const lastRotation = decisionRotationAt.get(rotationKey) || 0;
|
|
750
|
-
const incomingBytes = Buffer.byteLength(body, "utf8");
|
|
751
|
-
const cap = shadowMaxBytes();
|
|
752
|
-
let knownUsage = decisionUsageBytes.get(rotationKey);
|
|
753
|
-
let rootMtime = null;
|
|
754
|
-
try { rootMtime = statSync(rotationKey).mtimeMs; } catch {}
|
|
755
|
-
const knownMtime = decisionUsageMtime.get(rotationKey);
|
|
756
|
-
const fastPath = rotationScope.exclusive && shadowUsage?.root === rotationKey &&
|
|
757
|
-
shadowUsage?.identity === rotationScope.identity &&
|
|
758
|
-
now - lastRotation < DECISION_ROTATION_INTERVAL_MS &&
|
|
759
|
-
Number.isSafeInteger(knownUsage) && rootMtime !== null && knownMtime === rootMtime;
|
|
760
|
-
if (!fastPath) {
|
|
761
|
-
const rotation = rotateShadowLocked({
|
|
762
|
-
incomingBytes,
|
|
763
|
-
protectPath: path,
|
|
764
|
-
protectPaths,
|
|
765
|
-
sessionKey: record.sid || record.sessionId || "default",
|
|
766
|
-
cap,
|
|
767
|
-
});
|
|
768
|
-
if (!rotation.ok || rotation.oversize) return false;
|
|
769
|
-
decisionRotationAt.set(rotationKey, now);
|
|
770
|
-
knownUsage = rotation.used;
|
|
771
|
-
decisionUsageBytes.set(rotationKey, knownUsage);
|
|
772
|
-
try { decisionUsageMtime.set(rotationKey, statSync(rotationKey).mtimeMs); } catch {}
|
|
773
|
-
} else if (Number.isSafeInteger(knownUsage) && knownUsage + incomingBytes > cap) {
|
|
774
|
-
return false;
|
|
775
|
-
}
|
|
776
|
-
if (existsSync(path)) {
|
|
777
|
-
const beforeOpen = lstatSync(path, { bigint: true });
|
|
778
|
-
if (!beforeOpen.isFile() || beforeOpen.nlink !== 1n) {
|
|
779
|
-
throw coordinationError(new Error("shadow decision is not a single-link regular file"));
|
|
780
|
-
}
|
|
781
|
-
const noFollow = fsConstants.O_NOFOLLOW;
|
|
782
|
-
const fd = openSync(path, fsConstants.O_WRONLY | fsConstants.O_APPEND | (noFollow ?? 0));
|
|
783
|
-
try {
|
|
784
|
-
const opened = fstatSync(fd, { bigint: true });
|
|
785
|
-
const named = lstatSync(path, { bigint: true });
|
|
786
|
-
if (!opened.isFile() || opened.nlink !== 1n || !named.isFile() || named.nlink !== 1n ||
|
|
787
|
-
opened.dev !== named.dev || opened.ino !== named.ino) {
|
|
788
|
-
throw coordinationError(new Error("shadow decision identity changed"));
|
|
789
|
-
}
|
|
790
|
-
writeFileSync(fd, body);
|
|
791
|
-
fsyncSync(fd);
|
|
792
|
-
} finally {
|
|
793
|
-
closeSync(fd);
|
|
794
|
-
}
|
|
795
|
-
if (shadowUsage && isPluginShadowName(basename(path))) {
|
|
796
|
-
shadowUsage.bytes += Buffer.byteLength(body, "utf8");
|
|
797
|
-
}
|
|
798
|
-
decisionUsageBytes.set(rotationKey, (knownUsage ?? 0) + incomingBytes);
|
|
799
|
-
if (rootMtime !== null) decisionUsageMtime.set(rotationKey, rootMtime);
|
|
800
|
-
} else {
|
|
801
|
-
writeShadowFileLocked(path, body, {}, {
|
|
802
|
-
exclusive: false,
|
|
803
|
-
write: writeFileSync,
|
|
804
|
-
unlink: unlinkSync,
|
|
805
|
-
accessPath: file,
|
|
806
|
-
});
|
|
807
|
-
decisionUsageBytes.set(rotationKey, (knownUsage ?? 0) + incomingBytes);
|
|
808
|
-
if (rootMtime !== null) decisionUsageMtime.set(rotationKey, rootMtime);
|
|
809
|
-
}
|
|
810
|
-
return true;
|
|
749
|
+
const root = directoryIdentity(dir);
|
|
750
|
+
tightenShadow(dir, "dir");
|
|
751
|
+
const written = withCutStatsLock(dir, () => {
|
|
752
|
+
if (!root || directoryIdentity(dir) !== root) return false;
|
|
753
|
+
const line = JSON.stringify({ v: 1, ts: new Date().toISOString(), ...record, decisionWriteFailures });
|
|
754
|
+
return appendBoundedLog(join(dir, DECISIONS_NAME), `${line}\n`, DECISIONS_LOG_MAX_BYTES, true);
|
|
811
755
|
});
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
756
|
+
if (written === true) return true;
|
|
757
|
+
} catch {}
|
|
758
|
+
decisionWriteFailures++;
|
|
759
|
+
return false;
|
|
815
760
|
}
|
|
816
761
|
|
|
817
762
|
export function readCutStats(dir) {
|
|
@@ -963,11 +908,12 @@ function verifyLogFile(file, observed) {
|
|
|
963
908
|
}
|
|
964
909
|
}
|
|
965
910
|
|
|
966
|
-
function replaceLog(file, observed, retained, incoming) {
|
|
911
|
+
function replaceLog(file, observed, retained, incoming, privateFile) {
|
|
967
912
|
const tmp = `${file}.${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
|
|
968
913
|
const fd = openSync(tmp, "wx", 0o600);
|
|
969
914
|
try {
|
|
970
915
|
try {
|
|
916
|
+
if (privateFile) tightenCreatedShadow(tmp, fd);
|
|
971
917
|
writeFileSync(fd, Buffer.concat([retained, incoming]));
|
|
972
918
|
fsyncSync(fd);
|
|
973
919
|
} finally {
|
|
@@ -977,10 +923,11 @@ function replaceLog(file, observed, retained, incoming) {
|
|
|
977
923
|
renameSync(tmp, file);
|
|
978
924
|
} finally {
|
|
979
925
|
try { unlinkSync(tmp); } catch {}
|
|
926
|
+
if (privateFile) releaseLockedFile(tmp);
|
|
980
927
|
}
|
|
981
928
|
}
|
|
982
929
|
|
|
983
|
-
function appendBoundedLog(file, body, maxBytes) {
|
|
930
|
+
function appendBoundedLog(file, body, maxBytes, privateFile = false) {
|
|
984
931
|
const bytes = Buffer.from(body);
|
|
985
932
|
const incoming = bytes.length <= maxBytes
|
|
986
933
|
? bytes
|
|
@@ -990,8 +937,22 @@ function appendBoundedLog(file, body, maxBytes) {
|
|
|
990
937
|
before = lstatSync(file, { bigint: true });
|
|
991
938
|
} catch (error) {
|
|
992
939
|
if (error?.code !== "ENOENT") throw error;
|
|
993
|
-
if (incoming.length)
|
|
994
|
-
|
|
940
|
+
if (!incoming.length) return false;
|
|
941
|
+
if (!privateFile) writeFileSync(file, incoming, { flag: "wx", mode: 0o600 });
|
|
942
|
+
else {
|
|
943
|
+
const fd = openSync(file, "wx", 0o600);
|
|
944
|
+
try {
|
|
945
|
+
tightenCreatedShadow(file, fd);
|
|
946
|
+
writeFileSync(fd, incoming);
|
|
947
|
+
fsyncSync(fd);
|
|
948
|
+
} catch (error) {
|
|
949
|
+
if (shadowFileIdentity(file, fd)) try { unlinkSync(file); } catch {}
|
|
950
|
+
throw error;
|
|
951
|
+
} finally {
|
|
952
|
+
closeSync(fd);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
return true;
|
|
995
956
|
}
|
|
996
957
|
if (!before.isFile() || before.nlink !== 1n) throw new Error("spine: unsupported log target");
|
|
997
958
|
const fd = openSync(file, fsConstants.O_RDWR | fsConstants.O_APPEND | (fsConstants.O_NOFOLLOW ?? 0));
|
|
@@ -1001,19 +962,30 @@ function appendBoundedLog(file, body, maxBytes) {
|
|
|
1001
962
|
observed = fstatSync(fd, { bigint: true });
|
|
1002
963
|
verifyLogFile(file, before);
|
|
1003
964
|
verifyLogFile(file, observed);
|
|
965
|
+
if (privateFile) {
|
|
966
|
+
const windows = process.platform === "win32";
|
|
967
|
+
if (windows) tightenShadow(file, "file");
|
|
968
|
+
tightenCreatedShadow(file, fd, {}, { skipRunner: windows });
|
|
969
|
+
observed = fstatSync(fd, { bigint: true });
|
|
970
|
+
verifyLogFile(file, observed);
|
|
971
|
+
}
|
|
1004
972
|
const size = Number(observed.size);
|
|
1005
973
|
if (!Number.isSafeInteger(size)) throw new Error("spine: invalid log size");
|
|
1006
974
|
const last = Buffer.alloc(1);
|
|
1007
975
|
const complete = size === 0 || (readSync(fd, last, 0, 1, size - 1) === 1 && last[0] === 0x0a);
|
|
1008
976
|
if (complete && size + incoming.length <= maxBytes) {
|
|
1009
|
-
if (incoming.length)
|
|
1010
|
-
|
|
977
|
+
if (incoming.length) {
|
|
978
|
+
writeFileSync(fd, incoming);
|
|
979
|
+
if (privateFile) fsyncSync(fd);
|
|
980
|
+
}
|
|
981
|
+
return incoming.length > 0;
|
|
1011
982
|
}
|
|
1012
983
|
retained = logSuffix(fd, size, maxBytes - incoming.length);
|
|
1013
984
|
} finally {
|
|
1014
985
|
closeSync(fd);
|
|
1015
986
|
}
|
|
1016
|
-
replaceLog(file, observed, retained, incoming);
|
|
987
|
+
replaceLog(file, observed, retained, incoming, privateFile);
|
|
988
|
+
return incoming.length > 0;
|
|
1017
989
|
}
|
|
1018
990
|
|
|
1019
991
|
export function appendMaintenanceStatus(dir, record) {
|
|
@@ -1022,7 +994,7 @@ export function appendMaintenanceStatus(dir, record) {
|
|
|
1022
994
|
const root = ensureShadowDirIdentity(dir);
|
|
1023
995
|
return withCutStatsLock(dir, () => {
|
|
1024
996
|
if (!root || directoryIdentity(dir) !== root) return false;
|
|
1025
|
-
const line = JSON.stringify({ v: 1, ts: new Date().toISOString(), ...record });
|
|
997
|
+
const line = JSON.stringify({ v: 1, ts: new Date().toISOString(), ...record, decisionWriteFailures });
|
|
1026
998
|
appendBoundedLog(join(dir, MAINTENANCE_NAME), `${line}\n`, MAINTENANCE_LOG_MAX_BYTES);
|
|
1027
999
|
return true;
|
|
1028
1000
|
}) === true;
|
|
@@ -1430,23 +1402,32 @@ export function discardShadowFiles(files, cause, unlink = unlinkSync) {
|
|
|
1430
1402
|
}
|
|
1431
1403
|
}
|
|
1432
1404
|
|
|
1405
|
+
class ShadowWriteRevoked extends Error {}
|
|
1406
|
+
|
|
1407
|
+
function checkShadowWrite(writeEpoch) {
|
|
1408
|
+
if (writeEpoch && Atomics.load(writeEpoch, 0) !== 0) {
|
|
1409
|
+
throw new ShadowWriteRevoked("spine: shadow write revoked");
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1433
1413
|
export function writeShadowFile(
|
|
1434
1414
|
file,
|
|
1435
1415
|
body,
|
|
1436
1416
|
access = {},
|
|
1437
|
-
{ exclusive = false, root, write = writeFileSync, unlink = unlinkSync } = {},
|
|
1417
|
+
{ exclusive = false, root, write = writeFileSync, unlink = unlinkSync, writeEpoch } = {},
|
|
1438
1418
|
) {
|
|
1439
1419
|
const dir = dirname(file);
|
|
1440
1420
|
ensureShadowDir(dir, access);
|
|
1441
1421
|
return withShadowRoot(root ?? shadowRootForDir(dir), () => {
|
|
1442
1422
|
const path = scopedFile(file, rotationScope.root);
|
|
1443
1423
|
if (!path) throw coordinationError(new Error("shadow file outside root scope"));
|
|
1444
|
-
writeShadowFileLocked(path, body, access, { exclusive, write, unlink, accessPath: file });
|
|
1424
|
+
writeShadowFileLocked(path, body, access, { exclusive, write, unlink, accessPath: file, writeEpoch });
|
|
1445
1425
|
return file;
|
|
1446
1426
|
});
|
|
1447
1427
|
}
|
|
1448
1428
|
|
|
1449
|
-
function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, accessPath }) {
|
|
1429
|
+
function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, accessPath, writeEpoch }) {
|
|
1430
|
+
checkShadowWrite(writeEpoch);
|
|
1450
1431
|
const dir = dirname(file);
|
|
1451
1432
|
const parentIdentity = rememberShadowParent(dir);
|
|
1452
1433
|
|
|
@@ -1489,16 +1470,12 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1489
1470
|
error.code = "EEXIST";
|
|
1490
1471
|
throw error;
|
|
1491
1472
|
}
|
|
1473
|
+
checkShadowWrite(writeEpoch);
|
|
1492
1474
|
renameSync(target, file);
|
|
1493
1475
|
protectedPath = file;
|
|
1494
1476
|
// staging 临时名一次性且永不复用:发布后其锁表条目已成死重,随 rename 同步
|
|
1495
1477
|
// 释放,避免每次保存向 lockedFiles 残留一个永不复用的条目。
|
|
1496
1478
|
releaseLockedFile(target);
|
|
1497
|
-
if (basename(file) !== DECISIONS_NAME) {
|
|
1498
|
-
decisionRotationAt.delete(rotationScope.root);
|
|
1499
|
-
decisionUsageBytes.delete(rotationScope.root);
|
|
1500
|
-
decisionUsageMtime.delete(rotationScope.root);
|
|
1501
|
-
}
|
|
1502
1479
|
|
|
1503
1480
|
// Keep the caller's spelling for the permission cache/runner. The opened
|
|
1504
1481
|
// descriptor and the final path now refer to the same published object.
|
|
@@ -1528,12 +1505,12 @@ function writeShadowFileLocked(file, body, access, { exclusive, write, unlink, a
|
|
|
1528
1505
|
}
|
|
1529
1506
|
}
|
|
1530
1507
|
|
|
1531
|
-
export function writeShadowOwner(dir, access = {}, root) {
|
|
1508
|
+
export function writeShadowOwner(dir, access = {}, root, writeEpoch) {
|
|
1532
1509
|
return writeShadowFile(
|
|
1533
1510
|
join(dir, "owner"),
|
|
1534
1511
|
String(process.pid),
|
|
1535
1512
|
access,
|
|
1536
|
-
{ root },
|
|
1513
|
+
{ root, writeEpoch },
|
|
1537
1514
|
);
|
|
1538
1515
|
}
|
|
1539
1516
|
|
|
@@ -1664,20 +1641,26 @@ export function saveShadowTransaction({
|
|
|
1664
1641
|
cap,
|
|
1665
1642
|
access = {},
|
|
1666
1643
|
rotationIO = {},
|
|
1644
|
+
writeEpoch,
|
|
1667
1645
|
} = {}) {
|
|
1646
|
+
const revoked = () => writeEpoch && Atomics.load(writeEpoch, 0) !== 0;
|
|
1647
|
+
const skipped = { ok: false, skipped: true, reason: "stand-down" };
|
|
1648
|
+
if (revoked()) return skipped;
|
|
1668
1649
|
ensureShadowDir(shadow, access);
|
|
1669
1650
|
const dir = sessionDir(shadow, sessionKey);
|
|
1670
|
-
ensureShadowDir(dir, access);
|
|
1671
1651
|
return withShadowRoot(shadow, () => {
|
|
1652
|
+
if (revoked()) return skipped;
|
|
1653
|
+
ensureShadowDir(dir, access);
|
|
1672
1654
|
const owner = join(dir, "owner");
|
|
1673
1655
|
const ownerExisted = existsSync(owner);
|
|
1674
1656
|
let ownerWritten = false;
|
|
1675
1657
|
try {
|
|
1676
|
-
writeShadowOwner(dir, access, shadow);
|
|
1658
|
+
writeShadowOwner(dir, access, shadow, writeEpoch);
|
|
1677
1659
|
ownerWritten = true;
|
|
1678
1660
|
const incoming = Buffer.byteLength(body);
|
|
1679
1661
|
const rotation = rotateShadow({
|
|
1680
1662
|
...rotationIO,
|
|
1663
|
+
writeEpoch,
|
|
1681
1664
|
dir: shadow,
|
|
1682
1665
|
incomingBytes: incoming,
|
|
1683
1666
|
protectPath: file,
|
|
@@ -1685,6 +1668,7 @@ export function saveShadowTransaction({
|
|
|
1685
1668
|
sessionKey,
|
|
1686
1669
|
cap,
|
|
1687
1670
|
});
|
|
1671
|
+
checkShadowWrite(writeEpoch);
|
|
1688
1672
|
if (!rotation.ok) {
|
|
1689
1673
|
if (rotation.reason) {
|
|
1690
1674
|
const incomplete = rotation.reason === "scan-incomplete";
|
|
@@ -1699,11 +1683,15 @@ export function saveShadowTransaction({
|
|
|
1699
1683
|
if (required) throw new Error("spine: shadow backup is full; leaving the span");
|
|
1700
1684
|
return { ok: false, skipped: true, reason: "full", rotation };
|
|
1701
1685
|
}
|
|
1702
|
-
writeShadowFile(file, body, access, { root: shadow });
|
|
1686
|
+
writeShadowFile(file, body, access, { root: shadow, writeEpoch });
|
|
1703
1687
|
if (!existsSync(file)) throw new Error("spine: shadow backup was not written");
|
|
1704
1688
|
return { ok: true, file, rotation };
|
|
1705
1689
|
} catch (error) {
|
|
1706
1690
|
if (ownerWritten && !ownerExisted) discardShadowFiles([owner], error);
|
|
1691
|
+
if (error instanceof ShadowWriteRevoked) {
|
|
1692
|
+
shadowUsage = null;
|
|
1693
|
+
return skipped;
|
|
1694
|
+
}
|
|
1707
1695
|
throw error;
|
|
1708
1696
|
}
|
|
1709
1697
|
});
|
|
@@ -1721,7 +1709,7 @@ function rotationTime(now) {
|
|
|
1721
1709
|
function rotateShadowLocked({
|
|
1722
1710
|
incomingBytes, protectPath, protectPaths = [], sessionKey, cap,
|
|
1723
1711
|
unlink = unlinkSync, alive = processAlive, readdir = readdirSync, stat = statSync,
|
|
1724
|
-
now = () => performance.now(),
|
|
1712
|
+
now = () => performance.now(), writeEpoch,
|
|
1725
1713
|
}) {
|
|
1726
1714
|
const { root, identity, exclusive } = rotationScope;
|
|
1727
1715
|
const low = Math.floor(cap * 0.8);
|
|
@@ -1737,6 +1725,7 @@ function rotateShadowLocked({
|
|
|
1737
1725
|
}
|
|
1738
1726
|
shadowUsage = null;
|
|
1739
1727
|
let complete = true;
|
|
1728
|
+
rotationScanCount++;
|
|
1740
1729
|
const files = listShadowEntries(root, alive, { readdir, stat, onError() { complete = false; } });
|
|
1741
1730
|
const protect = new Set([protectPath, ...protectPaths].filter(Boolean).map((path) => {
|
|
1742
1731
|
try { return join(realDirectory(dirname(path)), basename(path)); } catch { return resolve(path); }
|
|
@@ -1781,6 +1770,7 @@ function rotateShadowLocked({
|
|
|
1781
1770
|
let failed = false;
|
|
1782
1771
|
for (const file of [...legacy, ...dead, ...mine]) {
|
|
1783
1772
|
if (!oversize && used + incomingBytes <= low) break;
|
|
1773
|
+
checkShadowWrite(writeEpoch);
|
|
1784
1774
|
try {
|
|
1785
1775
|
unlink(file.path);
|
|
1786
1776
|
} catch (error) {
|