Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(ingest): lower the learned bulk size only on a 413 that states a size
KageBinaryc9a7d610f02a
diff --git a/ix-cli/src/cli/__tests__/helpers/fake-backend.ts b/ix-cli/src/cli/__tests__/helpers/fake-backend.tsindex 681a867c..e3445b3b 100644--- a/ix-cli/src/cli/__tests__/helpers/fake-backend.ts+++ b/ix-cli/src/cli/__tests__/helpers/fake-backend.ts@@ -33,6 +33,14 @@ export class FakeBackend {maxBulkOps: number | undefined = undefined;/** Put `suggestedMaxPatches` in that 413, as the bulk writer's estimate does. */suggestMaxPatches = false;+ /**+ * Answer a bulk whose body is over this many bytes (over two or more+ * patches) with a 413, as Ix-memory's body cap (`IX_BULK_MAX_BODY_MB`) does:+ * no patch count, since bytes are not ops.+ */+ maxBulkBytes: number | undefined = undefined;+ /** Body bytes of each `/v1/patches/bulk` request, in order. */+ readonly bulkBodyBytes: number[] = [];/** Refuse re-sends of patches a 409 already confirmed. */refuseReplays = false;/**@@ -385,6 +393,17 @@ export class FakeBackend {this.aborter.abort();}+ if (path === "/v1/patches/bulk") this.bulkBodyBytes.push(Buffer.byteLength(body));+ if (path === "/v1/patches/bulk" && this.maxBulkBytes !== undefined && patches.length > 1 &&+ Buffer.byteLength(body) > this.maxBulkBytes) {+ // The OSS backend's strict error policy answers the body cap with this+ // fixed text (ErrorHandler.payloadTooLargeJson without a suggestion).+ return send(413, {+ error: "payload_too_large",+ message: "the write exceeds the maximal transaction size; send fewer patches per request",+ correlation_id: "fake",+ });+ }if (path === "/v1/patches/bulk" && this.maxBulkOps !== undefined && patches.length > 1) {const ops = patches.reduce((sum, p) => sum + (p.ops?.length ?? 0), 0);if (ops > this.maxBulkOps) {diff --git a/ix-cli/src/cli/__tests__/ingest-files.test.ts b/ix-cli/src/cli/__tests__/ingest-files.test.tsindex 37248988..a3f49421 100644--- a/ix-cli/src/cli/__tests__/ingest-files.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-files.test.ts@@ -1337,7 +1337,7 @@ describe("ingestFiles against a fake backend", () => {expect(backend.singleCount, "no per-file fallback").toBe(0);});- it("halves by ops on a 413 that suggests nothing, and later batches start at the learned size", async () => {+ it("halves on a 413 that suggests nothing, and later batches start at the learned size", async () => {fixture(1100);backend.maxBulkOps = 300;@@ -1351,6 +1351,32 @@ describe("ingestFiles against a fake backend", () => {expect(summary.patchesApplied).toBe(1100);});+ it("keeps its op budget after a 413 for bytes: one large file does not shrink the requests after it", async () => {+ // 60 ordinary files and one whose patch is large for its op count (a+ // 60,000-character identifier). The body cap fits that one file alone,+ // and all 60 others together, but not all 61. Learning an op budget from+ // that 413 halved it on every bisection that still held the large file,+ // until the files after it went a few per request.+ fixture(60);+ writeFileSync(+ join(repo, "src", "big.ts"),+ `export function ${"n".repeat(60_000)}(): number { return 1; }\n`,+ "utf8",+ );+ execFileSync("git", ["add", "-A"], { cwd: repo, stdio: "ignore" });+ backend.maxBulkBytes = 255_000;++ const summary = await run();++ const bulks = backend.requests.filter(r => r.path === "/v1/patches/bulk");+ expect(tooLarge()).toBe(1);+ expect(bulks.length, "the refused request, then the large file and the rest").toBe(3);+ expect(Math.max(...bulks.filter(r => r.code !== 413).map(r => r.patches))).toBe(60);+ expect(summary.commitErrors).toBe(0);+ expect(summary.patchesApplied).toBe(61);+ expect(backend.singleCount, "no per-file fallback").toBe(0);+ });+it("is never refused when IX_COMMIT_MAX_OPS keeps every request under the cap", async () => {fixture(1100);backend.maxBulkOps = 300;diff --git a/ix-cli/src/cli/__tests__/ingest-retry.test.ts b/ix-cli/src/cli/__tests__/ingest-retry.test.tsindex 3fa08759..328d01a6 100644--- a/ix-cli/src/cli/__tests__/ingest-retry.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-retry.test.ts@@ -542,4 +542,29 @@ describe('bulk request bounds (IN-05)', () => {expect(parseSuggestedMaxPatches(ARANGO_TRANSACTION_LIMIT_ERROR)).toBeUndefined();expect(parseSuggestedMaxPatches(new Error('413: request rejected'))).toBeUndefined();});++ it('reads the count from the estimate\'s message when the body is not JSON, and none from a byte refusal', () => {+ // Ix-memory BulkWriteApi.overBudget, as its message reads.+ expect(parseSuggestedMaxPatches(new Error(+ '413: bulk commit of 900 patches is estimated at 520 MB, over the 409 MB transaction budget; send at most 700 patches per request',+ ))).toBe(700);+ // The body cap, in each error policy: bytes, not a patch count.+ expect(parseSuggestedMaxPatches(new Error(+ '413: {"error":"payload_too_large","message":"the write exceeds the maximal transaction size; send fewer patches per request","correlation_id":"c"}',+ ))).toBeUndefined();+ expect(parseSuggestedMaxPatches(new Error(+ '413: {"error":"payload_too_large","message":"the request body exceeds 67108864 bytes; send fewer patches per request"}',+ ))).toBeUndefined();+ expect(parseSuggestedMaxPatches(new Error('413: <html><body>413 Request Entity Too Large</body></html>'))).toBeUndefined();+ });++ it('cuts by bytes too once a byte bound is set, and only then', () => {+ const items = [100, 100, 500, 100, 100, 100].map((b, i) => ({ i, b }));+ const bytesOf = vi.fn((item: { b: number }) => item.b);+ const unbounded = cutBulkChunks(items, () => 1, { maxFiles: 10, maxOps: 100 }, bytesOf);+ expect(unbounded.map(c => c.map(item => item.i))).toEqual([[0, 1, 2, 3, 4, 5]]);+ expect(bytesOf, 'not measured while no byte bound is set').not.toHaveBeenCalled();+ const cut = cutBulkChunks(items, () => 1, { maxFiles: 10, maxOps: 100, maxBytes: 250 }, bytesOf);+ expect(cut.map(c => c.map(item => item.i))).toEqual([[0, 1], [2], [3, 4], [5]]);+ });});diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex 976171a5..3408f82e 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -766,20 +766,30 @@ export function isPayloadTooLargeError(err: unknown): boolean {/*** What a 413 from the bulk writer's own estimate says one request should hold- * (Ix-memory#232: `suggestedMaxPatches` in the body). Absent from a 413 that- * ArangoDB raised mid-write, or a proxy's.+ * (Ix-memory#232: `suggestedMaxPatches` in the body, and "send at most N+ * patches per request" in its message). Absent from a 413 that ArangoDB raised+ * mid-write, from the backend's body cap, or from a proxy's.+ *+ * This is the only 413 that says the request held too many OPS. The others+ * are about bytes, or say nothing, and a run must not learn an op count from+ * them -- see `learnBulkLimits` in ingestFiles.*/export function parseSuggestedMaxPatches(err: unknown): number | undefined {+ const valid = (n: unknown): number | undefined =>+ typeof n === 'number' && Number.isInteger(n) && n >= 1 ? n : undefined;const text = String(err);const start = text.indexOf('{');const end = text.lastIndexOf('}');- if (start === -1 || end <= start) return undefined;- try {- const n = (JSON.parse(text.slice(start, end + 1)) as { suggestedMaxPatches?: unknown }).suggestedMaxPatches;- return typeof n === 'number' && Number.isInteger(n) && n >= 1 ? n : undefined;- } catch {- return undefined;+ if (start !== -1 && end > start) {+ try {+ const n = valid((JSON.parse(text.slice(start, end + 1)) as { suggestedMaxPatches?: unknown }).suggestedMaxPatches);+ if (n !== undefined) return n;+ } catch {+ /* not JSON: fall through to the message */+ }}+ const stated = /send at most (\d+) patches per request/i.exec(text);+ return stated ? valid(Number(stated[1])) : undefined;}/**@@ -801,25 +811,46 @@ export interface BulkLimits {maxFiles: number;/** Ops across the request's patches: the backend's transaction grows with them. */maxOps: number;+ /**+ * Serialized bytes across the request's patches, once a 413 that did not+ * blame the op count has been seen: a body cap (Ix-memory's+ * `IX_BULK_MAX_BODY_MB`), a proxy's limit, or one that gave no reason.+ * Absent until then.+ */+ maxBytes?: number;}/*** Cut `items` into bulk requests in order, each within `limits`. An item over- * `maxOps` on its own still goes, alone: one patch cannot be split.+ * `maxOps` (or `maxBytes`) on its own still goes, alone: one patch cannot be+ * split. `bytesOf` is consulted only while `limits.maxBytes` is set.*/-export function cutBulkChunks<T>(items: T[], opsOf: (item: T) => number, limits: BulkLimits): T[][] {+export function cutBulkChunks<T>(+ items: T[],+ opsOf: (item: T) => number,+ limits: BulkLimits,+ bytesOf?: (item: T) => number,+): T[][] {+ const byteBound = limits.maxBytes !== undefined && bytesOf !== undefined ? limits.maxBytes : undefined;const chunks: T[][] = [];let current: T[] = [];let ops = 0;+ let bytes = 0;for (const item of items) {const n = opsOf(item);- if (current.length > 0 && (current.length >= limits.maxFiles || ops + n > limits.maxOps)) {+ const b = byteBound !== undefined && bytesOf ? bytesOf(item) : 0;+ if (+ current.length > 0 &&+ (current.length >= limits.maxFiles || ops + n > limits.maxOps || (byteBound !== undefined && bytes + b > byteBound))+ ) {chunks.push(current);current = [];ops = 0;+ bytes = 0;}current.push(item);ops += n;+ bytes += b;}if (current.length > 0) chunks.push(current);return chunks;@@ -2627,25 +2658,60 @@ export async function ingestFiles(const bulkLimits: BulkLimits = { maxFiles: COMMIT_HTTP_MAX_FILES, maxOps: COMMIT_MAX_OPS };const opsOf = (item: { patch: GraphPatchPayload }): number => item.patch.ops.length;/**- * Learn from a group the backend found too large, as an op budget: the- * patch count its 413 suggests, at this group's ops per patch, or else- * half the group's ops. Then cut the group to the new bounds.+ * A patch's size on the wire, measured only once a byte bound is in play+ * (on a 413 that did not blame the op count, and in the cuts after it).+ */+ const patchBytes = new WeakMap<GraphPatchPayload, number>();+ const bytesOf = (item: { patch: GraphPatchPayload }): number => {+ let n = patchBytes.get(item.patch);+ if (n === undefined) {+ n = Buffer.byteLength(JSON.stringify(item.patch));+ patchBytes.set(item.patch, n);+ }+ return n;+ };+ const cutToLimits = <T extends { patch: GraphPatchPayload }>(items: T[]): T[][] =>+ cutBulkChunks(items, opsOf, bulkLimits, bytesOf);+ /**+ * Learn from a group the backend found too large, then cut the group to+ * the new bounds.+ *+ * Only a 413 that names a patch count (the bulk writer's estimate,+ * Ix-memory#232) says the group held too many ops. That one lowers the op+ * budget: the suggested count at this group's ops per patch, or half the+ * group's ops if the suggestion is no smaller than the group.+ *+ * Any other 413 -- the backend's body cap, a proxy's limit, or one with no+ * reason -- is about bytes, or may be, and the op budget is left alone.+ * Halving ops on it let one file with a large body but few ops drag the+ * run's op budget down with every bisection, until later requests carried+ * about one patch each. It lowers a separate byte budget instead, to half+ * the refused group's bytes. A group that was refused for its bytes is+ * over the cap, so that budget stays above half the cap however many+ * times it is lowered.** Ops, not the suggested count itself: the backend sizes its suggestion* from the group's average patch, and a count cut lets a run of larger* files through over the budget, to be refused again.*/const learnBulkLimits = <T extends { patch: GraphPatchPayload }>(items: T[], err: unknown): T[][] => {- const ops = items.reduce((sum, item) => sum + opsOf(item), 0);const suggested = parseSuggestedMaxPatches(err);- const budget = suggested !== undefined && suggested < items.length- ? Math.floor((ops * suggested) / items.length)- : Math.floor(ops / 2);- bulkLimits.maxOps = Math.max(1, Math.min(bulkLimits.maxOps, budget));+ if (suggested !== undefined) {+ const ops = items.reduce((sum, item) => sum + opsOf(item), 0);+ const budget = suggested < items.length+ ? Math.floor((ops * suggested) / items.length)+ : Math.floor(ops / 2);+ bulkLimits.maxOps = Math.max(1, Math.min(bulkLimits.maxOps, budget));+ } else {+ const bytes = items.reduce((sum, item) => sum + bytesOf(item), 0);+ const budget = Math.max(1, Math.floor(bytes / 2));+ bulkLimits.maxBytes = Math.min(bulkLimits.maxBytes ?? Number.POSITIVE_INFINITY, budget);+ }if (debug) {- process.stderr.write(`\n [bulk limits] now ${bulkLimits.maxFiles} files / ${bulkLimits.maxOps} ops per request\n`);+ const byteNote = bulkLimits.maxBytes !== undefined ? ` / ${bulkLimits.maxBytes} bytes` : '';+ process.stderr.write(`\n [bulk limits] now ${bulkLimits.maxFiles} files / ${bulkLimits.maxOps} ops${byteNote} per request\n`);}- return cutBulkChunks(items, opsOf, bulkLimits);+ return cutToLimits(items);};const COMMIT_CONCURRENCY = parsePositiveIntEnv('IX_COMMIT_CONCURRENCY', 8); // parallel HTTP save requestsconst COMMIT_CONFLICT_RETRIES = parsePositiveIntEnv('IX_COMMIT_CONFLICT_RETRIES', 6); // retry transient Arango lock conflicts@@ -2746,7 +2812,7 @@ export async function ingestFiles(let bulkRun: PreparedPatch[] = [];const flushBulkRun = (): void => {if (bulkRun.length === 0) return;- chunks.push(...cutBulkChunks(bulkRun, opsOf, bulkLimits));+ chunks.push(...cutToLimits(bulkRun));bulkRun = [];};for (const item of preparedPatches) {@@ -3044,7 +3110,7 @@ export async function ingestFiles(let probeQueue = items.filter(item => !needsPerFile(item));while (probeQueue.length > 1) {- const chunk = cutBulkChunks(probeQueue, opsOf, bulkLimits)[0];+ const chunk = cutToLimits(probeQueue)[0];const rest = probeQueue.slice(chunk.length);const bulkStart = performance.now();try {@@ -3313,7 +3379,7 @@ export async function ingestFiles();},splitTooLarge: learnBulkLimits,- recut: items => cutBulkChunks(items, opsOf, bulkLimits),+ recut: cutToLimits,onSplit: (items, err) => {if (!debug) return;const first = items[0];