Personal Telegram developer console for GitHub
fix: bound exact workspace diff memory and computation
Codex committed
Oct 25, 2026 at 07:26 UTC
77c78940e0a9212bfabaac4d3a7dd93806c1cbba
2 files changed
+351
-1
src/core/workspace-policy.js
+146
-1
@@ -93,7 +93,7 @@ function linesOf(value) {
93
return String(value ?? '').split('\n');
94
}
95
96
-function diffOperations(beforeLines, afterLines) {
96
+function smallDiffOperations(beforeLines, afterLines) {
97
const rows = beforeLines.length + 1;
98
const cols = afterLines.length + 1;
99
const table = new Uint16Array(rows * cols);
@@ -136,6 +136,151 @@ function diffOperations(beforeLines, afterLines) {
136
return operations;
137
}
138
139
+function diffOperations(beforeLines, afterLines) {
140
+ // Ordinary edits retain the original insertion-first LCS reconstruction.
141
+ // Larger edits use a fixed-distance band: memory is linear in line count,
142
+ // with explicit storage/work limits rather than a quadratic allocation.
143
+ const maxTableCells = 65536;
144
+ const maxDistance = 64;
145
+ const maxBandCells = 1000000;
146
+ let workRemaining = 2000000;
147
+ const tooComplex = () => {
148
+ const error = new Error(
149
+ 'This edit is too complex to preview safely. Split it into smaller changes and try again.'
150
+ );
151
+ error.code = 'DIFF_COMPLEXITY_LIMIT';
152
+ return error;
153
+ };
154
+ const spend = (work = 1) => {
155
+ workRemaining -= work;
156
+ if (workRemaining < 0) throw tooComplex();
157
+ };
158
+ if (beforeLines.length > MAX_CHARS + 1 || afterLines.length > MAX_CHARS + 1) {
159
+ throw tooComplex();
160
+ }
161
+ if ((beforeLines.length + 1) * (afterLines.length + 1) <= maxTableCells) {
162
+ return smallDiffOperations(beforeLines, afterLines);
163
+ }
164
+
165
+ const operations = [];
166
+ let prefix = 0;
167
+ while (
168
+ prefix < beforeLines.length &&
169
+ prefix < afterLines.length &&
170
+ beforeLines[prefix] === afterLines[prefix]
171
+ ) {
172
+ spend();
173
+ operations.push({ kind: ' ', line: beforeLines[prefix++] });
174
+ }
175
+ const n = beforeLines.length - prefix;
176
+ const m = afterLines.length - prefix;
177
+ if (n === 0 || m === 0) {
178
+ for (let i = 0; i < n; i += 1) {
179
+ operations.push({ kind: '-', line: beforeLines[prefix + i] });
180
+ }
181
+ for (let j = 0; j < m; j += 1) {
182
+ operations.push({ kind: '+', line: afterLines[prefix + j] });
183
+ }
184
+ return operations;
185
+ }
186
+
187
+ // Trim suffixes only while measuring distance. Reconstructing against the
188
+ // full suffix preserves legacy ties when the suffix contains repeated lines.
189
+ let suffix = 0;
190
+ while (
191
+ suffix < n &&
192
+ suffix < m &&
193
+ beforeLines[beforeLines.length - suffix - 1] ===
194
+ afterLines[afterLines.length - suffix - 1]
195
+ ) {
196
+ spend();
197
+ suffix += 1;
198
+ }
199
+ const distanceN = n - suffix;
200
+ const distanceM = m - suffix;
201
+ if (Math.abs(distanceN - distanceM) > maxDistance) throw tooComplex();
202
+ const offset = maxDistance + 1;
203
+ const frontier = new Int32Array(2 * maxDistance + 3);
204
+ frontier.fill(-1);
205
+ frontier[offset + 1] = 0;
206
+ let distance = -1;
207
+ search: for (let d = 0; d <= maxDistance; d += 1) {
208
+ for (let k = -d; k <= d; k += 2) {
209
+ spend();
210
+ const slot = offset + k;
211
+ let x =
212
+ k === -d || (k !== d && frontier[slot - 1] < frontier[slot + 1])
213
+ ? frontier[slot + 1]
214
+ : frontier[slot - 1] + 1;
215
+ let y = x - k;
216
+ while (
217
+ x < distanceN &&
218
+ y < distanceM &&
219
+ beforeLines[prefix + x] === afterLines[prefix + y]
220
+ ) {
221
+ spend();
222
+ x += 1;
223
+ y += 1;
224
+ }
225
+ frontier[slot] = x;
226
+ if (x >= distanceN && y >= distanceM) {
227
+ distance = d;
228
+ break search;
229
+ }
230
+ }
231
+ }
232
+ if (distance < 0) throw tooComplex();
233
+
234
+ // Every optimal path of edit distance D stays inside |i - j| <= D.
235
+ // Capped suffix distances in this band reconstruct the exact legacy path,
236
+ // including its preference for insertion when both choices are optimal.
237
+ const width = 2 * distance + 1;
238
+ const cells = (n + 1) * width;
239
+ if (cells > maxBandCells) throw tooComplex();
240
+ spend(cells);
241
+ const unreachable = maxDistance + 1;
242
+ const table = new Uint8Array(cells);
243
+ table.fill(unreachable);
244
+ const at = (i, j) => i * width + j - i + distance;
245
+ const score = (i, j) =>
246
+ i > n || j > m || Math.abs(i - j) > distance
247
+ ? unreachable
248
+ : table[at(i, j)];
249
+ for (let i = n; i >= 0; i -= 1) {
250
+ for (
251
+ let j = Math.min(m, i + distance);
252
+ j >= Math.max(0, i - distance);
253
+ j -= 1
254
+ ) {
255
+ spend();
256
+ const value =
257
+ i === n
258
+ ? m - j
259
+ : j === m
260
+ ? n - i
261
+ : beforeLines[prefix + i] === afterLines[prefix + j]
262
+ ? score(i + 1, j + 1)
263
+ : Math.min(score(i + 1, j), score(i, j + 1)) + 1;
264
+ table[at(i, j)] = Math.min(unreachable, value);
265
+ }
266
+ }
267
+ if (score(0, 0) !== distance) throw tooComplex();
268
+ let i = 0;
269
+ let j = 0;
270
+ while (i < n || j < m) {
271
+ spend();
272
+ if (i < n && j < m && beforeLines[prefix + i] === afterLines[prefix + j]) {
273
+ operations.push({ kind: ' ', line: beforeLines[prefix + i++] });
274
+ j += 1;
275
+ } else if (j < m && (i === n || score(i, j + 1) <= score(i + 1, j))) {
276
+ operations.push({ kind: '+', line: afterLines[prefix + j++] });
277
+ } else {
278
+ operations.push({ kind: '-', line: beforeLines[prefix + i++] });
279
+ }
280
+ }
281
+ return operations;
282
+}
283
+
284
export function buildUnifiedDiff({
285
path,
286
before,
test/bounded-diff.test.js
new
+205
@@ -0,0 +1,205 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { spawnSync } from 'node:child_process';
4
+import { buildUnifiedDiff } from '../src/core/workspace-policy.js';
5
+
6
+// Independent legacy oracle: small fixtures only, never editor-sized matrices.
7
+function legacyDiff(before, after, maxChars = 10000) {
8
+ const a = before.split('\n');
9
+ const b = after.split('\n');
10
+ const table = Array.from({ length: a.length + 1 }, () =>
11
+ Array(b.length + 1).fill(0)
12
+ );
13
+ for (let i = a.length - 1; i >= 0; i -= 1) {
14
+ for (let j = b.length - 1; j >= 0; j -= 1) {
15
+ table[i][j] =
16
+ a[i] === b[j]
17
+ ? table[i + 1][j + 1] + 1
18
+ : Math.max(table[i + 1][j], table[i][j + 1]);
19
+ }
20
+ }
21
+ const output = ['--- a/file', '+++ b/file', '@@'];
22
+ let additions = 0;
23
+ let deletions = 0;
24
+ let i = 0;
25
+ let j = 0;
26
+ while (i < a.length || j < b.length) {
27
+ if (i < a.length && j < b.length && a[i] === b[j]) {
28
+ output.push(` ${a[i++]}`);
29
+ j += 1;
30
+ } else if (
31
+ j < b.length &&
32
+ (i === a.length || table[i][j + 1] >= table[i + 1][j])
33
+ ) {
34
+ output.push(`+${b[j++]}`);
35
+ additions += 1;
36
+ } else {
37
+ output.push(`-${a[i++]}`);
38
+ deletions += 1;
39
+ }
40
+ }
41
+ const raw = output.join('\n');
42
+ const truncated = raw.length > maxChars;
43
+ return {
44
+ text: truncated ? `${raw.slice(0, maxChars - 2)}\n…` : raw,
45
+ additions,
46
+ deletions,
47
+ truncated
48
+ };
49
+}
50
+
51
+function runIsolated(body) {
52
+ const moduleUrl = new URL('../src/core/workspace-policy.js', import.meta.url);
53
+ const script = `
54
+ import assert from 'node:assert/strict';
55
+ import { buildUnifiedDiff, validateEditableFile } from ${JSON.stringify(moduleUrl.href)};
56
+ // Reject dangerous allocations before allocating, so the RED regression
57
+ // cannot reserve the old ~800 MiB matrix in either process.
58
+ let allocatedBytes = 0;
59
+ for (const name of ['Uint8Array', 'Uint16Array', 'Uint32Array', 'Int32Array']) {
60
+ const Original = globalThis[name];
61
+ globalThis[name] = new Proxy(Original, {
62
+ construct(target, args) {
63
+ const bytes = Number(args[0]) * Original.BYTES_PER_ELEMENT;
64
+ allocatedBytes += bytes;
65
+ assert.ok(bytes <= 2 * 1024 * 1024, 'oversized diff allocation: ' + bytes);
66
+ assert.ok(allocatedBytes <= 4 * 1024 * 1024, 'excessive diff allocations');
67
+ return Reflect.construct(target, args);
68
+ }
69
+ });
70
+ }
71
+ ${body}
72
+ `;
73
+ const child = spawnSync(
74
+ process.execPath,
75
+ ['--input-type=module', '--eval', script],
76
+ {
77
+ timeout: 5000,
78
+ maxBuffer: 16384,
79
+ encoding: 'utf8'
80
+ }
81
+ );
82
+ assert.ifError(child.error);
83
+ assert.equal(child.status, 0, child.stderr);
84
+}
85
+
86
+test('editor-sized identical newline and separated sparse changes stay within a small memory budget', () => {
87
+ runIsolated(`
88
+ const identical = '\\n'.repeat(20000);
89
+ assert.equal(validateEditableFile({ path: 'file', text: identical }).editable, true);
90
+ const same = buildUnifiedDiff({ before: identical, after: identical, maxChars: 120 });
91
+ assert.equal(same.additions, 0);
92
+ assert.equal(same.deletions, 0);
93
+ assert.equal(same.truncated, true);
94
+ const lines = Array(19999).fill('');
95
+ const before = lines.join('\\n');
96
+ lines[5000] = 'x';
97
+ lines[15000] = 'y';
98
+ const after = lines.join('\\n');
99
+ assert.equal(after.length, 20000);
100
+ assert.equal(validateEditableFile({ path: 'file', text: after }).editable, true);
101
+ const sparse = buildUnifiedDiff({ before, after, maxChars: 120 });
102
+ assert.equal(sparse.additions, 2);
103
+ assert.equal(sparse.deletions, 2);
104
+ assert.equal(sparse.truncated, true);
105
+ assert.ok(sparse.text.length <= 120);
106
+ `);
107
+});
108
+
109
+test('large disjoint and repetitive edits fail explicitly before exhausting memory or work', () => {
110
+ runIsolated(`
111
+ const cases = [
112
+ ['a\\n'.repeat(10000), 'b\\n'.repeat(10000)],
113
+ ['a\\n'.repeat(5000) + 'b\\n'.repeat(5000), 'b\\n'.repeat(5000) + 'a\\n'.repeat(5000)]
114
+ ];
115
+ for (const [before, after] of cases) {
116
+ assert.throws(() => buildUnifiedDiff({ before, after }), (error) => {
117
+ assert.equal(error.code, 'DIFF_COMPLEXITY_LIMIT');
118
+ assert.match(error.message, /smaller/i);
119
+ return true;
120
+ });
121
+ }
122
+ `);
123
+});
124
+
125
+test('large sparse edits exceeding the reconstruction budget fail without approximate counts', () => {
126
+ runIsolated(`
127
+ const lines = Array(19988).fill('');
128
+ const before = lines.join('\\n');
129
+ for (let i = 0; i < 13; i += 1) lines[1 + 1500 * i] = 'x';
130
+ const after = lines.join('\\n');
131
+ assert.equal(after.length, 20000);
132
+ assert.throws(() => buildUnifiedDiff({ before, after }), {
133
+ code: 'DIFF_COMPLEXITY_LIMIT'
134
+ });
135
+ `);
136
+});
137
+
138
+test('ordinary diffs preserve legacy insertion-first ties, exact counts and truncation', () => {
139
+ let seed = 0x6e657861;
140
+ const random = (limit) => {
141
+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
142
+ return seed % limit;
143
+ };
144
+ const alphabet = ['', 'a', 'b', 'c', '😀', '\r'];
145
+ for (let fixture = 0; fixture < 500; fixture += 1) {
146
+ const makeText = () =>
147
+ Array.from(
148
+ { length: random(24) + 1 },
149
+ () => alphabet[random(alphabet.length)]
150
+ ).join('\n');
151
+ const before = makeText();
152
+ const after = makeText();
153
+ const maxChars = fixture % 2 ? 10000 : 32;
154
+ assert.deepEqual(
155
+ buildUnifiedDiff({ before, after, maxChars }),
156
+ legacyDiff(before, after, maxChars),
157
+ `fixture ${fixture}`
158
+ );
159
+ }
160
+});
161
+
162
+test('large sparse diffs retain canonical ties even in repeated common suffixes', () => {
163
+ const cases = [
164
+ [`a\n${Array(500).fill('b').join('\n')}`, Array(499).fill('b').join('\n')],
165
+ [Array(500).fill('b').join('\n'), `a\n${Array(499).fill('b').join('\n')}`],
166
+ [
167
+ Array.from({ length: 500 }, (_, i) => `${i % 7}`).join('\n'),
168
+ Array.from({ length: 500 }, (_, i) =>
169
+ i === 100 || i === 400 ? 'x' : `${i % 7}`
170
+ ).join('\n')
171
+ ]
172
+ ];
173
+ for (const [before, after] of cases) {
174
+ assert.deepEqual(
175
+ buildUnifiedDiff({ before, after, maxChars: 10000 }),
176
+ legacyDiff(before, after)
177
+ );
178
+ }
179
+});
180
+
181
+test('randomized large sparse diffs match the legacy oracle through band reconstruction', () => {
182
+ let seed = 0xabcdef;
183
+ const random = (limit) => {
184
+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
185
+ return seed % limit;
186
+ };
187
+ for (let fixture = 0; fixture < 40; fixture += 1) {
188
+ const beforeLines = Array.from({ length: 300 }, () => `${random(7)}`);
189
+ const afterLines = [...beforeLines];
190
+ for (let edit = 0; edit < 8; edit += 1) {
191
+ const position = random(afterLines.length);
192
+ const kind = random(3);
193
+ if (kind === 0) afterLines.splice(position, 1);
194
+ else if (kind === 1) afterLines.splice(position, 0, 'x');
195
+ else afterLines[position] = 'x';
196
+ }
197
+ const before = beforeLines.join('\n');
198
+ const after = afterLines.join('\n');
199
+ assert.deepEqual(
200
+ buildUnifiedDiff({ before, after, maxChars: 10000 }),
201
+ legacyDiff(before, after),
202
+ `band fixture ${fixture}`
203
+ );
204
+ }
205
+});