Skip to content

An open-source, faster Devin alternative

TypeScript

Work index: linear parsing, size caps, and re-parsing in batches outside the constructor

Igor Zalutski via Computer537b93c0f960
diff --git a/services/managed-agents/src/computer/work/index.ts b/services/managed-agents/src/computer/work/index.ts
index a4c0a6d2..a88d7cc6 100644
--- a/services/managed-agents/src/computer/work/index.ts
+++ b/services/managed-agents/src/computer/work/index.ts
@@ -67,6 +67,8 @@ const HISTORY_PAGE = 30;
const CLOSED_LIMIT_DEFAULT = 50;
const CLOSED_LIMIT_MAX = 100;
const FETCH_PARALLEL = 6;
+/** Stored bodies re-parsed per step after PARSER_VERSION changes. */
+export const REPARSE_BATCH = 100;
const SCHEMA = `
CREATE TABLE IF NOT EXISTS items (
@@ -136,7 +138,6 @@ export class WorkIndex {
constructor(private readonly deps: WorkIndexDeps) {
this.now = deps.now ?? Date.now;
deps.sql.exec(SCHEMA);
- this.reparse();
}
// ------------------------------------------------------------------ meta
@@ -226,7 +227,7 @@ export class WorkIndex {
this.setMeta("read_at", now);
if (!this.repo()) return;
const seen = Math.max(this.metaNumber("as_of"), this.metaNumber("tried_at"));
- if (now - seen > LOOK_AFTER_MS) this.deps.waitUntil(this.kick());
+ if (now - seen > LOOK_AFTER_MS || this.reparsing()) this.deps.waitUntil(this.kick());
this.deps.waitUntil(this.deps.arm(now + ALARM_EVERY_MS));
}
@@ -373,6 +374,7 @@ export class WorkIndex {
if (!this.repo()) return null;
await this.exclusive(async () => {
const now = this.now();
+ this.reparseBatch();
if (this.meta("build") !== null) {
if (now - this.metaNumber("as_of") >= ALARM_EVERY_MS) await this.look();
else await this.guard(() => this.fillOpen());
@@ -384,7 +386,7 @@ export class WorkIndex {
const now = this.now();
const pausedUntil = this.metaNumber("pause_until");
let next: number | null = null;
- if (this.meta("build") !== null) next = now + BUILD_STEP_MS;
+ if (this.meta("build") !== null || this.reparsing()) next = now + BUILD_STEP_MS;
else if (now - this.metaNumber("read_at") < READS_WINDOW_MS || this.meta("walk") !== null) next = now + ALARM_EVERY_MS;
if (next !== null && this.meta("problem") !== null && now - this.metaNumber("read_at") >= READS_WINDOW_MS) next = null;
if (next !== null && pausedUntil > next) next = pausedUntil;
@@ -410,6 +412,7 @@ export class WorkIndex {
/** Checks the head and moves the projection to it; then one step of background work. */
private async look(): Promise<void> {
+ this.reparseBatch();
const gh = this.client();
if (!gh) return;
if (this.metaNumber("pause_until") > this.now()) return;
@@ -480,7 +483,7 @@ export class WorkIndex {
sql.exec(
"UPDATE items SET path = ?, parsed = ?, closed_at = ?, closed_by = ? WHERE number = ?",
w.path,
- prev.parser > 0 ? JSON.stringify(parseItem(ip, prev.body)) : JSON.stringify(pendingParse(ip)),
+ prev.parser > 0 ? JSON.stringify(safeParse(ip, prev.body)) : JSON.stringify(pendingParse(ip)),
moved ? null : prev.closed_at,
moved ? null : prev.closed_by,
number,
@@ -538,7 +541,7 @@ export class WorkIndex {
this.deps.sql.exec(
"UPDATE items SET body = ?, parsed = ?, parser = ?, updated_at = COALESCE(updated_at, ?) WHERE number = ? AND blob = ? AND path = ?",
body,
- JSON.stringify(parseItem(ip, body)),
+ JSON.stringify(safeParse(ip, body)),
PARSER_VERSION,
updatedAt,
row.number,
@@ -676,7 +679,7 @@ export class WorkIndex {
const t = touch.get(w.path) ?? {};
const changed = !prev || prev.blob !== w.blob || prev.path !== w.path;
const body = bodies.get(w.blob) ?? (prev && prev.blob === w.blob && prev.parser > 0 ? prev.body : null);
- const parsed = body !== null ? parseItem(ip, body) : pendingParse(ip);
+ const parsed = body !== null ? safeParse(ip, body) : pendingParse(ip);
const last = t.last ?? (complete ? undefined : newest);
const updatedAt = changed ? (last?.at ?? prev?.updated_at ?? null) : (prev?.updated_at ?? null);
let authorName = prev?.author_name ?? null;
@@ -824,15 +827,26 @@ export class WorkIndex {
// ------------------------------------------------------------------ parser version
- /** A new parser version re-parses every stored body, with no GitHub call. */
- private reparse(): void {
- if (this.meta("parser_version") === String(PARSER_VERSION)) return;
+ private reparsing(): boolean {
+ return this.meta("parser_version") !== String(PARSER_VERSION);
+ }
+
+ /**
+ * After a new parser version, one batch of stored bodies re-parsed, with no GitHub call. Run by
+ * the look and the alarm, never while the object starts: a parser fault cannot stop it starting,
+ * and reads show the earlier fields until the batch reaches them.
+ */
+ private reparseBatch(): void {
+ if (!this.reparsing()) return;
+ const rows = this.deps.sql
+ .exec<{ number: number; path: string; body: string } & Row>("SELECT number, path, body FROM items WHERE parser > 0 AND parser <> ? LIMIT ?", PARSER_VERSION, REPARSE_BATCH)
+ .toArray();
this.deps.transaction(() => {
- for (const r of this.deps.sql.exec<{ number: number; path: string; body: string } & Row>("SELECT number, path, body FROM items WHERE parser > 0").toArray()) {
+ for (const r of rows) {
const ip = itemPath(r.path);
- if (ip) this.deps.sql.exec("UPDATE items SET parsed = ?, parser = ? WHERE number = ?", JSON.stringify(parseItem(ip, r.body)), PARSER_VERSION, r.number);
+ if (ip) this.deps.sql.exec("UPDATE items SET parsed = ?, parser = ? WHERE number = ?", JSON.stringify(safeParse(ip, r.body)), PARSER_VERSION, r.number);
}
- this.setMeta("parser_version", PARSER_VERSION);
+ if (rows.length < REPARSE_BATCH) this.setMeta("parser_version", PARSER_VERSION);
});
}
@@ -913,10 +927,22 @@ function pendingParse(ip: ItemPath): ParsedItem {
return { title: slugTitle(ip.slug), stateLine: null, tags: [], owner: null, left: null, boxes: 0, pullRequests: [], warnings: [] };
}
+/** The parser never throws by design; if it does, the row keeps its slug and says so. */
+function safeParse(ip: ItemPath, body: string): ParsedItem {
+ try {
+ return parseItem(ip, body);
+ } catch {
+ return { ...pendingParse(ip), warnings: ["The file could not be read."] };
+ }
+}
+
/** Who closed: the commit's author, or null when a session made the commit (it says "closed in a session"). */
function closerName(c: CommitInfo): string | null {
if (sessionTrailers(c.message).length) return null;
- return c.authorName.replace(/\s+via Computer$/i, "").trim() || null;
+ // By hand, not `/\s+via Computer$/`: an unanchored `\s+` backtracks on a run of spaces.
+ const name = c.authorName.slice(0, 200).trim();
+ const suffix = " via computer";
+ return (name.toLowerCase().endsWith(suffix) ? name.slice(0, -suffix.length) : name).trim() || null;
}
function refusal(problem: RepositoryProblem): string {
diff --git a/services/managed-agents/src/computer/work/item.ts b/services/managed-agents/src/computer/work/item.ts
index dde3418f..6d240f87 100644
--- a/services/managed-agents/src/computer/work/item.ts
+++ b/services/managed-agents/src/computer/work/item.ts
@@ -12,6 +12,12 @@ export const PARSER_VERSION = 1;
/** Characters kept of the state line. */
export const STATE_LINE_MAX = 200;
+/** Characters of a body that are read; the rest is ignored with a warning. */
+export const BODY_MAX = 1_000_000;
+
+/** Characters of one line that are read. */
+export const LINE_MAX = 10_000;
+
export type Stage = "open" | "closed";
/** An item's place in the repository: only `NN-slug.md` directly under `work/` or `done/`. */
@@ -52,7 +58,9 @@ export function slugTitle(slug: string): string {
return slug;
}
-const EMAIL = /^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/;
+// Every pattern below is anchored and has no nested or adjacent overlapping repetition, so it runs
+// in time linear in the line; lines are cut to LINE_MAX first. What a pattern could not do in
+// linear time (headings, emails, trailing punctuation) is done by hand.
const CHECKBOX = /^\s*[-*+]\s+\[([ xX])\]/;
const KEY_VALUE = /^[A-Za-z][A-Za-z0-9 _-]{0,40}:(\s|$)/;
const URL_IN_TEXT = /https?:\/\/[^\s<>()[\]"'`]+/g;
@@ -60,7 +68,19 @@ const URL_IN_TEXT = /https?:\/\/[^\s<>()[\]"'`]+/g;
/** One file's fields. `path` gives the stage and the slug (the title when there is no heading). */
export function parseItem(path: ItemPath, body: string): ParsedItem {
const warnings: string[] = [];
+ if (body.length > BODY_MAX) {
+ warnings.push(`The file is longer than ${BODY_MAX} characters; only the start is read.`);
+ body = body.slice(0, BODY_MAX);
+ }
const lines = body.replace(/^/, "").split(/\r?\n/);
+ let long = false;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i]!.length > LINE_MAX) {
+ lines[i] = lines[i]!.slice(0, LINE_MAX);
+ long = true;
+ }
+ }
+ if (long) warnings.push(`A line is longer than ${LINE_MAX} characters; only its start is read.`);
// Frontmatter: `---` on the first line, closed by the next `---`.
let start = 0;
@@ -79,7 +99,7 @@ export function parseItem(path: ItemPath, body: string): ParsedItem {
const value = unquote(kv[2]!.trim());
if (key === "owner") {
if (!value) continue;
- if (EMAIL.test(value)) owner = value.toLowerCase();
+ if (isEmail(value)) owner = value.toLowerCase();
else warnings.push(`owner is not one email: ${value.slice(0, 80)}`);
} else if (key === "tags") {
tags = [...new Set(value.replace(/^\[|\]$/g, "").split(",").map((t) => unquote(t.trim()).toLowerCase()).filter(Boolean))];
@@ -113,10 +133,9 @@ export function parseItem(path: ItemPath, body: string): ParsedItem {
if (inLeft) leftContent = true;
continue;
}
- const heading = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(trimmed);
- if (heading && /^\s{0,3}#/.test(line)) {
- const level = heading[1]!.length;
- const text = heading[2]!;
+ const heading = headingOf(line);
+ if (heading) {
+ const { level, text } = heading;
if (inLeft && level <= 2) inLeft = false;
if (level === 1 && title === null) {
title = text.replace(/^\d+\s*[.:)\-–—]?\s*/, "").trim() || text;
@@ -140,7 +159,7 @@ export function parseItem(path: ItemPath, body: string): ParsedItem {
}
if (/^PR:/i.test(trimmed)) {
for (const url of trimmed.slice(3).match(URL_IN_TEXT) ?? []) {
- const clean = url.replace(/[.,;:!?]+$/, "");
+ const clean = trimEnd(url, ".,;:!?");
if (!pullRequests.includes(clean)) pullRequests.push(clean);
}
}
@@ -176,7 +195,44 @@ function cut(text: string): string {
}
function unquote(value: string): string {
- return /^(["']).*\1$/.test(value) && value.length >= 2 ? value.slice(1, -1) : value;
+ const q = value[0];
+ return value.length >= 2 && (q === '"' || q === "'") && value[value.length - 1] === q ? value.slice(1, -1) : value;
+}
+
+/**
+ * An ATX heading (up to three spaces, one to six `#`, then a space or the end), its closing `#`s
+ * removed. By hand: a pattern for the optional closing sequence backtracks on long lines.
+ */
+export function headingOf(line: string): { level: number; text: string } | null {
+ let i = 0;
+ while (i < 3 && line[i] === " ") i++;
+ let level = 0;
+ while (line[i + level] === "#") level++;
+ if (level < 1 || level > 6) return null;
+ const after = line[i + level];
+ if (after !== undefined && after !== " " && after !== "\t") return null;
+ let text = line.slice(i + level).trim();
+ let end = text.length;
+ while (end > 0 && text[end - 1] === "#") end--;
+ // A closing run counts only when it is the whole text or follows a space.
+ if (end < text.length && (end === 0 || text[end - 1] === " " || text[end - 1] === "\t")) text = text.slice(0, end).trim();
+ return { level, text };
+}
+
+/** One address: no spaces or separators, one `@`, a dot inside the domain. */
+function isEmail(value: string): boolean {
+ if (value.length > 254 || /[\s,;<>]/.test(value)) return false;
+ const at = value.indexOf("@");
+ if (at < 1 || at !== value.lastIndexOf("@")) return false;
+ const domain = value.slice(at + 1);
+ const dot = domain.indexOf(".");
+ return dot > 0 && !domain.endsWith(".");
+}
+
+function trimEnd(text: string, chars: string): string {
+ let end = text.length;
+ while (end > 0 && chars.includes(text[end - 1]!)) end--;
+ return text.slice(0, end);
}
/** The `Session:` trailers of a commit message (the knowledge clone's hook writes one; 3.4). */
diff --git a/services/managed-agents/test/work-index.test.ts b/services/managed-agents/test/work-index.test.ts
index 45565e49..89a7cfcf 100644
--- a/services/managed-agents/test/work-index.test.ts
+++ b/services/managed-agents/test/work-index.test.ts
@@ -1,8 +1,9 @@
import { describe, expect, it } from "vitest";
import type { TokenMinter } from "../src/computer/work/github.js";
-import { ALARM_EVERY_MS, FILL_BATCH, LOOK_AFTER_MS, PULLS_EVERY_MS, WorkIndex } from "../src/computer/work/index.js";
+import { ALARM_EVERY_MS, FILL_BATCH, LOOK_AFTER_MS, PULLS_EVERY_MS, REPARSE_BATCH, WorkIndex } from "../src/computer/work/index.js";
import type { IndexedItem, ItemsResult } from "../src/computer/work/index-contract.js";
+import { PARSER_VERSION } from "../src/computer/work/item.js";
import { sqlStorage } from "./fixtures/computer-sql.js";
import { FakeRepo } from "./fixtures/fake-github-repo.js";
@@ -445,16 +446,29 @@ describe("setRepository", () => {
});
describe("parser version", () => {
- it("re-parses stored bodies with no GitHub call", async () => {
- const repo = new FakeRepo({ "work/1-a.md": item(1, "A") });
+ it("re-parses stored bodies in batches behind the reads, never while the object starts, with no GitHub call", async () => {
+ const files: Record<string, string> = {};
+ for (let n = 1; n <= REPARSE_BATCH + 20; n++) files[`work/${n}-item.md`] = item(n, `Item ${n}`);
+ const repo = new FakeRepo(files);
const s = await connect(repo);
- s.sql.exec("UPDATE items SET parsed = ?", JSON.stringify({ title: "stale", stateLine: null, tags: [], owner: null, left: null, boxes: 0, pullRequests: [], warnings: [] }));
+ s.tick(11 * 60_000);
+ await s.drain();
+ const stale = JSON.stringify({ title: "stale", stateLine: null, tags: [], owner: null, left: null, boxes: 0, pullRequests: [], warnings: [] });
+ // Rows of another parser version.
+ s.sql.exec("UPDATE items SET parsed = ?, parser = ?", stale, PARSER_VERSION + 1);
s.sql.exec("UPDATE meta SET v = '0' WHERE k = 'parser_version'");
repo.take();
const again = setup(repo, { sql: s.sql });
- const r = await again.index.items(ORG, { stage: "open" });
- expect(r.ok && r.items[0]!.title).toBe("A");
- expect(repo.take()).toEqual([]);
+ // Starting parses nothing: the read answers the stored fields, and the batch runs behind it.
+ const first = await again.index.items(ORG, { stage: "open" });
+ expect(first.ok && first.items[0]!.title).toBe("stale");
+ await again.settle();
+ let titles = (await open(again)).items.map((i) => i.title);
+ expect(titles.filter((t) => t === "stale")).toHaveLength(20);
+ await again.index.alarm();
+ titles = (await open(again)).items.map((i) => i.title);
+ expect(titles.filter((t) => t === "stale")).toHaveLength(0);
+ expect(repo.take().filter((l) => !l.endsWith("/git/ref/heads/main"))).toEqual([]);
});
});
diff --git a/services/managed-agents/test/work-item.test.ts b/services/managed-agents/test/work-item.test.ts
index 42415882..92aeaf32 100644
--- a/services/managed-agents/test/work-item.test.ts
+++ b/services/managed-agents/test/work-item.test.ts
@@ -1,6 +1,16 @@
import { describe, expect, it } from "vitest";
-import { itemPath, parseItem, readyToClose, sessionTrailers, STATE_LINE_MAX, type ItemPath } from "../src/computer/work/item.js";
+import {
+ BODY_MAX,
+ headingOf,
+ itemPath,
+ LINE_MAX,
+ parseItem,
+ readyToClose,
+ sessionTrailers,
+ STATE_LINE_MAX,
+ type ItemPath,
+} from "../src/computer/work/item.js";
/** Work tracking 3.2: an item file read by hand, never rejected. */
@@ -123,6 +133,57 @@ describe("parseItem", () => {
});
});
+describe("parseItem on adversarial input", () => {
+ const SIZE = 200 * 1024;
+ const fill = (unit: string) => unit.repeat(Math.ceil(SIZE / unit.length)).slice(0, SIZE);
+ // Each is one 200 KB line (or a body of them) shaped against a pattern the parser could use.
+ const bodies: Record<string, string> = {
+ "a heading padded with spaces": `# a${" ".repeat(SIZE / 2)}#${" ".repeat(SIZE / 2)}x`,
+ "a heading of hashes and spaces": `# ${fill("# ")}x`,
+ "an owner of dots": `---\nowner: a@${fill("b.")}!\n---\n# T\n`,
+ "a PR line of dots": `# T\nPR: https://x${fill(".")}a\n`,
+ "a Key: value prefix": `# T\n${fill("a ")}`,
+ "brackets": `# T\n${fill("[")}`,
+ "brackets and parens": `# T\n${fill("[a](")}`,
+ "backticks and stars": `# T\n${fill("`*_")}`,
+ "a title of digits": `# ${fill("1 ")}`,
+ "many short lines": fill("# a #\n- [ ] b\nPR: https://c.d/e.\n| f |\n> g\nKey: h\n"),
+ "a frontmatter of keys": `---\n${fill("a: b\n")}`,
+ "an unclosed comment": `# T\n<!--${fill(" x")}`,
+ };
+
+ for (const [name, body] of Object.entries(bodies)) {
+ it(`parses ${name} in under 50 ms`, () => {
+ parse(body);
+ const started = performance.now();
+ parse(body);
+ expect(performance.now() - started).toBeLessThan(50);
+ });
+ }
+
+ it("cuts a body and a line that are too long, with a warning", () => {
+ const p = parse(`# T\n${"x".repeat(LINE_MAX + 10)}\n${"y\n".repeat(BODY_MAX / 2)}`);
+ expect(p.warnings).toContain(`The file is longer than ${BODY_MAX} characters; only the start is read.`);
+ expect(p.warnings).toContain(`A line is longer than ${LINE_MAX} characters; only its start is read.`);
+ });
+
+ it("reads headings by hand as before", () => {
+ expect(headingOf("# T")).toEqual({ level: 1, text: "T" });
+ expect(headingOf(" ## Left ## ")).toEqual({ level: 2, text: "Left" });
+ expect(headingOf("## C# ")).toEqual({ level: 2, text: "C#" });
+ expect(headingOf("#hashtag")).toBeNull();
+ expect(headingOf(" # indented code")).toBeNull();
+ expect(headingOf("####### seven")).toBeNull();
+ });
+
+ it("still reads one owner email and refuses others", () => {
+ expect(parse("---\nowner: [email protected]\n---\n# T\n").owner).toBe("[email protected]");
+ for (const bad of ["a@b", "a@b.", "@b.co", "a@[email protected]", "a [email protected]"]) {
+ expect(parse(`---\nowner: ${bad}\n---\n# T\n`).owner).toBeNull();
+ }
+ });
+});
+
describe("readyToClose", () => {
it("is open, with boxes under ## Left and none unchecked", () => {
expect(readyToClose("open", { left: 0, boxes: 2 })).toBe(true);