Public: anyone can read this; the crew can change it.

Sentinel: memory-growth was degraded 564 minutes today: The forge's own memory is 4867 MiB, over twice its first-hour 2287 MiB and past the 2176 MiB more its database caches m… #16535

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/16193-sentinel-memory-growth-was-degraded-564 → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/16193-sentinel-memory-growth-was-degraded-564 was merged into main as b6a253b.

Review

Sign in to review this change.
6 files changed +242 −36
docs/SENTINEL.md +8
@@ -25,6 +25,14 @@ issue, and only when its evidence changed; one whose issue was closed and
2525 returned is filed again. It files in `FORGE_SENTINEL_REPO` (default
2626 `trevato/forge`) as the `sentinel` agent, else the first admin.
2727
28 **How it closes** (#16193, `src/crew/sentinel_close.ts`). Every rule that
29 closes its own issue (held two days, quiet for 24 hours, production caught
30 up, a shared red settled) says why in a comment, then closes. It does this
31 only where it can write. An agent on the crew with no write access may
32 comment but not close, so there it says nothing and logs `sentinel may not
33 close issues here` once per repository and rule. The issue stays open for a person to close, or until the
34 sentinel is given write access.
35
2836 **One issue per cause** (#14655, `src/crew/sentinel_causes.ts`). A finding is keyed by its
2937 cause, not its instance: a run killed for its budget files under
3038 `degraded:budget:<run kind>:<what ran out>` (e.g. `degraded:budget:review:time`), and a new
src/crew/sentinel.ts +12 −24
@@ -17,7 +17,7 @@
1717
1818 import { Database } from "bun:sqlite";
1919 import type { App } from "../app.ts";
20 import { addComment, openIssue, setIssueState } from "../actions/issues.ts";
20 import { addComment, openIssue } from "../actions/issues.ts";
2121 import { decisionsSince } from "../core/decisions.ts";
2222 import { getAgentByName } from "../core/agents.ts";
2323 import {
@@ -25,7 +25,7 @@ import {
2525 getLabel,
2626 type Issue,
2727 } from "../core/issues.ts";
28 import { canWrite, getRepo, type Repo } from "../core/repos.ts";
28 import { getRepo, type Repo } from "../core/repos.ts";
2929 import { ownRepoPath } from "../kernel/own_repo.ts";
3030 import { leaseLapsed, listRunning } from "../core/runs.ts";
3131 import { migrations } from "../core/schema.ts";
@@ -50,6 +50,7 @@ import { clip } from "../text/clip.ts";
5050 import { forgeCeiling } from "../flow/ceiling.ts";
5151 import { personSpoke } from "./person_spoke.ts";
5252 import { closeCaughtUp, mainAhead } from "./sentinel_main_ahead.ts";
53 import { mayClose, sayAndClose } from "./sentinel_close.ts";
5354 import { closeLaneMoving, laneStopped } from "./sentinel_lane.ts";
5455 import { type LaneAlarm, laneAlarm } from "../flow/alarm_lane.ts";
5556 import type { FindingKind } from "../hunt/finding.ts";
@@ -1035,10 +1036,7 @@ function settleShared(app: App, repo: Repo, actor: User, now: number): void {
10351036 )
10361037 .all();
10371038 if (open.length === 0) return;
1038 if (!canWrite(app.db, repo, actor)) {
1039 log.warn("sentinel may not close issues here; a settled shared red stays open", { repo: repo.id });
1040 return;
1041 }
1039 if (!mayClose(app, repo, actor, "settled shared red")) return;
10421040 const causes = new Map(spans(app.db, now - DAY_MS, now).map((s) => [`degraded:${keyPart(s.cause)}`, s.cause]));
10431041 for (const t of open) {
10441042 try {
@@ -1052,7 +1050,7 @@ function settleShared(app: App, repo: Repo, actor: User, now: number): void {
10521050 if ((owned === undefined && done === undefined) || personSpoke(app.db, t.issue_id)) continue;
10531051 const issue = getIssueById(app.db, t.issue_id);
10541052 if (issue === undefined || issue.repoId !== repo.id) continue;
1055 const said = addComment(
1053 const closed = sayAndClose(
10561054 app,
10571055 actor,
10581056 repo,
@@ -1070,16 +1068,10 @@ function settleShared(app: App, repo: Repo, actor: User, now: number): void {
10701068 "",
10711069 "Closing as dropped: there is nothing to fix. If it opens again it is filed fresh, quoting this.",
10721070 ].join("\n"),
1071 "dropped",
1072 t.key,
10731073 );
1074 if (!said.ok) {
1075 log.warn("sentinel could not comment", { key: t.key, error: String(said.error) });
1076 continue;
1077 }
1078 const closed = setIssueState(app, actor, repo, issue, "closed", { reason: "dropped", system: true });
1079 if (!closed.ok) {
1080 log.warn("sentinel could not close", { key: t.key, error: String(closed.error) });
1081 continue;
1082 }
1074 if (!closed) continue;
10831075 // When it settled, on the forge's clock: the repeat rule reads this, never the comment's words.
10841076 app.db
10851077 .query("UPDATE sentinel_finding SET commented_at = ?1 WHERE key = ?2 AND issue_id = ?3")
@@ -1138,7 +1130,7 @@ function closeHeld(app: App, repo: Repo, actor: User, active: ReadonlySet<string
11381130 WHERE i.state = 'open' AND t.key LIKE 'degraded:%'`,
11391131 )
11401132 .all();
1141 if (open.length === 0) return;
1133 if (open.length === 0 || !mayClose(app, repo, actor, "held")) return;
11421134 const history = spans(app.db, now - 30 * DAY_MS, now);
11431135 for (const t of open) {
11441136 try {
@@ -1154,19 +1146,15 @@ function closeHeld(app: App, repo: Repo, actor: User, active: ReadonlySet<string
11541146 if (personSpoke(app.db, t.issue_id)) continue;
11551147 const issue = getIssueById(app.db, t.issue_id);
11561148 if (issue === undefined || issue.repoId !== repo.id) continue;
1157 const said = addComment(
1149 sayAndClose(
11581150 app,
11591151 actor,
11601152 repo,
11611153 issue,
11621154 `Held since ${new Date(since).toISOString()}: no new incident on this cause for ${HEALTHY_DAYS} days running. ${causeLine(issue.body)}Closing as done; if it comes back it is filed again.`,
1155 "done",
1156 t.key,
11631157 );
1164 if (!said.ok) {
1165 log.warn("sentinel could not comment", { key: t.key, error: String(said.error) });
1166 continue;
1167 }
1168 const closed = setIssueState(app, actor, repo, issue, "closed", { reason: "done", system: true });
1169 if (!closed.ok) log.warn("sentinel could not close", { key: t.key, error: String(closed.error) });
11701158 } catch (error) {
11711159 log.error("sentinel close failed", { key: t.key, error: String(error) });
11721160 }
src/crew/sentinel_causes.ts +5 −8
@@ -9,13 +9,13 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import type { App } from "../app.ts";
12 import { addComment, setIssueState } from "../actions/issues.ts";
1312 import { getIssueById } from "../core/issues.ts";
1413 import type { Repo } from "../core/repos.ts";
1514 import type { User } from "../core/users.ts";
1615 import { createLog } from "../kernel/log.ts";
1716 import { cloneBreaker } from "./clone_breaker.ts";
1817 import { personSpoke } from "./person_spoke.ts";
18 import { mayClose, sayAndClose } from "./sentinel_close.ts";
1919 import type { Finding } from "./sentinel.ts";
2020
2121 const log = createLog("sentinel");
@@ -183,25 +183,22 @@ export function closeQuiet(app: App, repo: Repo, actor: User, active: ReadonlySe
183183 `SELECT t.key, t.issue_id, t.evidence, t.last_seen FROM sentinel_finding t JOIN issue i ON i.id = t.issue_id WHERE i.state = 'open'`,
184184 )
185185 .all();
186 if (open.length === 0 || !mayClose(app, repo, actor, "quiet")) return;
186187 for (const t of open) {
187188 try {
188189 if (active.has(t.key) || !CAUSE_KEY_PREFIXES.some((p) => t.key.startsWith(p))) continue;
189190 if (!(now - Date.parse(t.last_seen) >= QUIET_CLOSE_MS) || personSpoke(app.db, t.issue_id)) continue;
190191 const issue = getIssueById(app.db, t.issue_id);
191192 if (issue === undefined || issue.repoId !== repo.id) continue;
192 const said = addComment(
193 sayAndClose(
193194 app,
194195 actor,
195196 repo,
196197 issue,
197198 `Not seen since ${t.last_seen}: this cause has not recurred for 24 hours. Last evidence:\n${t.evidence.split("\n").map((e) => `- ${e}`).join("\n")}\nClosing as done; if it comes back it is filed again.`,
199 "done",
200 t.key,
198201 );
199 if (!said.ok) {
200 log.warn("sentinel could not comment", { key: t.key, error: String(said.error) });
201 continue;
202 }
203 const closed = setIssueState(app, actor, repo, issue, "closed", { reason: "done", system: true });
204 if (!closed.ok) log.warn("sentinel could not close", { key: t.key, error: String(closed.error) });
205202 } catch (error) {
206203 log.error("sentinel close failed", { key: t.key, error: String(error) });
207204 }
src/crew/sentinel_close.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * How the sentinel closes an issue it filed: it says why, then closes. Every
3 * closing rule (held, quiet, caught up, settled) goes through here, so each
4 * one checks the same thing first: whether the sentinel may close issues in
5 * this repository. When it may not (an agent on the crew with no write
6 * access), it says nothing. Saying "Closing as done" and then being refused
7 * left the issue open, and the next hourly hunt said it again (#16193: 38 times
8 * on one issue).
9 */
10
11 import type { App } from "../app.ts";
12 import { addComment, setIssueState } from "../actions/issues.ts";
13 import type { CloseReason, Issue } from "../core/issues.ts";
14 import { canWrite, type Repo } from "../core/repos.ts";
15 import type { User } from "../core/users.ts";
16 import { createLog } from "../kernel/log.ts";
17
18 const log = createLog("sentinel");
19
20 /**
21 * The repo and rule pairs already logged as refused, per forge, so an hourly
22 * hunt says it once. Keyed by the app, not the process (#12569).
23 */
outdated

The comment says 'logs it once', but this warns on every call: hourly, per rule. Log once per repo and rule, or reword the comment.

24 const refusedOf = new WeakMap<App, Set<string>>();
25
26 function refusedLogged(app: App): Set<string> {
27 let seen = refusedOf.get(app);
28 if (!seen) {
29 seen = new Set();
30 refusedOf.set(app, seen);
31 }
32 return seen;
33 }
34
35 /**
36 * Whether the sentinel may close issues in `repo`. When it may not, logs it
37 * once per repo and the rule named by `what` (again only after it could and
38 * then lost access), and the caller leaves its issues open without a word. A
39 * person closes them, or gives the sentinel write access.
40 */
41 export function mayClose(app: App, repo: Repo, actor: User, what: string): boolean {
42 const said = `${repo.id}\0${what}`;
43 const logged = refusedLogged(app);
44 if (canWrite(app.db, repo, actor)) {
45 logged.delete(said);
46 return true;
47 }
48 if (!logged.has(said)) {
49 logged.add(said);
50 log.warn("sentinel may not close issues here; they stay open", { repo: repo.id, rule: what });
51 }
52 return false;
53 }
54
55 /**
56 * Say `body` on `issue`, then close it for `reason`. True when it closed;
57 * false when the comment or the close was refused, which is logged under `key`.
58 */
59 export function sayAndClose(
60 app: App,
61 actor: User,
62 repo: Repo,
63 issue: Issue,
64 body: string,
65 reason: CloseReason,
66 key: string,
67 ): boolean {
68 const said = addComment(app, actor, repo, issue, body);
69 if (!said.ok) {
70 log.warn("sentinel could not comment", { key, error: String(said.error) });
71 return false;
72 }
73 const closed = setIssueState(app, actor, repo, issue, "closed", { reason, system: true });
74 if (!closed.ok) {
75 log.warn("sentinel could not close", { key, error: String(closed.error) });
76 return false;
77 }
78 return true;
79 }
src/crew/sentinel_main_ahead.ts +3 −4
@@ -8,13 +8,13 @@
88
99 import type { Database } from "bun:sqlite";
1010 import type { App } from "../app.ts";
11 import { addComment, setIssueState } from "../actions/issues.ts";
1211 import { getIssueById } from "../core/issues.ts";
1312 import type { Repo } from "../core/repos.ts";
1413 import type { User } from "../core/users.ts";
1514 import { mainAheadAlarm } from "../flow/alarm_main_ahead.ts";
1615 import { createLog } from "../kernel/log.ts";
1716 import { personSpoke } from "./person_spoke.ts";
17 import { mayClose, sayAndClose } from "./sentinel_close.ts";
1818 import type { Finding } from "./sentinel.ts";
1919
2020 const log = createLog("sentinel");
@@ -57,14 +57,13 @@ export function closeCaughtUp(
5757 `SELECT t.issue_id FROM sentinel_finding t JOIN issue i ON i.id = t.issue_id WHERE i.state = 'open' AND t.key = ?1`,
5858 )
5959 .all(key);
60 if (open.length === 0 || !mayClose(app, repo, actor, key)) return;
6061 for (const t of open) {
6162 try {
6263 if (personSpoke(app.db, t.issue_id)) continue;
6364 const issue = getIssueById(app.db, t.issue_id);
6465 if (issue === undefined || issue.repoId !== repo.id) continue;
65 const said = addComment(app, actor, repo, issue, `${cleared} at ${new Date(now).toISOString()}. Closing as done; if it falls behind again it is filed again.`);
66 if (!said.ok) continue;
67 setIssueState(app, actor, repo, issue, "closed", { reason: "done", system: true });
66 sayAndClose(app, actor, repo, issue, `${cleared} at ${new Date(now).toISOString()}. Closing as done; if it falls behind again it is filed again.`, "done", key);
6867 } catch (error) {
6968 log.error("sentinel close failed", { key, error: String(error) });
7069 }
test/sentinel-close-access.test.ts added +135
@@ -0,0 +1,135 @@
1 /**
2 * A sentinel that may not close issues says nothing about closing them
3 * (#16193). The forge's sentinel is an agent on the crew, and it can
4 * comment without write access. Each hourly hunt used to say "Held since …
5 * Closing as done" on a held finding, then have its close refused, and say
6 * it again the next hour: 38 times on one issue. Now it says nothing until it
7 * may close. Once it may, it says it once and closes.
8 */
9 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { quietLogs } from "./helpers/globals.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { createRepo } from "../src/actions/repos.ts";
16 import { addCrew, createAgentRow } from "../src/core/agents.ts";
17 import { createIssue, getIssueById, listComments, listIssues } from "../src/core/issues.ts";
18 import type { Repo } from "../src/core/repos.ts";
19 import { createUser, getUserById, type User } from "../src/core/users.ts";
20 import { logLevel, setLogLevel } from "../src/kernel/log.ts";
21 import { hunt } from "../src/crew/sentinel.ts";
22 import { closeQuiet } from "../src/crew/sentinel_causes.ts";
23 import { closeCaughtUp, MAIN_AHEAD_KEY } from "../src/crew/sentinel_main_ahead.ts";
24
25 quietLogs();
26
27 const MIN = 60_000;
28 const HOUR = 60 * MIN;
29 const T0 = Date.parse("2026-11-23T20:53:15.700Z");
30
31 let dir: string;
32 let app: App;
33 let repo: Repo;
34 let sentinelId: string;
35 const held = () => listIssues(app.db, repo.id, { state: "all" }).find((i) => i.title.includes("memory-growth"))!;
36 const heldSaid = () => listComments(app.db, held().id).filter((c) => c.body.startsWith("Held since "));
37 // A cause quiet for a day (`closeQuiet`) and main caught up (`closeCaughtUp`, which also
38 // serves the lane): each filed by the sentinel, driven directly so each guard is its own.
39 const QUIET_KEY = "degraded:stuck:sentinel-test";
40 let quietId: string;
41 let caughtUpId: string;
42 const sentinel = (): User => getUserById(app.db, sentinelId)!;
43 const said = (issueId: string, lead: string) => listComments(app.db, issueId).filter((c) => c.body.startsWith(lead));
44 const stateOf = (issueId: string) => getIssueById(app.db, issueId)!.state;
45 function fileAs(key: string, title: string, lastSeen: number): string {
46 const made = createIssue(app.db, { repoId: repo.id, authorId: sentinelId, title });
47 if (!made.ok) throw new Error(String(made.error));
48 const at = new Date(lastSeen).toISOString();
49 app.db
50 .query("INSERT INTO sentinel_finding (key, issue_id, evidence, first_seen, last_seen) VALUES (?1, ?2, 'seen', ?3, ?3)")
51 .run(key, made.value.id, at);
52 return made.value.id;
53 }
54 function closeBoth(now: number): void {
55 closeQuiet(app, repo, sentinel(), new Set(), now);
56 closeCaughtUp(app, repo, sentinel(), new Set(), now);
57 }
58
59 beforeAll(async () => {
60 dir = await mkdtemp(join(tmpdir(), "forge-sentinel-access-"));
61 app = createApp({ dataDir: dir, port: 0 });
62 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
outdated

Only the held rule is covered. Add tests for closeQuiet and closeCaughtUp with the same no-write-access setup. Each must fail if its mayClose guard is removed.

63 if (!a.ok) throw new Error(a.error);
64 const made = await createRepo(app, a.value, { name: "forge", visibility: "private" });
65 if (!made.ok) throw new Error(String(made.error));
66 repo = made.value;
67 // The sentinel as production has it: an agent on the crew, no write access.
68 const s = await createUser(app.db, { origin: "seed", username: "sentinel", email: "[email protected]", agent: true });
69 if (!s.ok) throw new Error("agent");
70 createAgentRow(app.db, { userId: s.value.id, brief: "hunt", createdBy: a.value.id });
71 addCrew(app.db, repo.id, s.value.id, a.value.id);
72 sentinelId = s.value.id;
73 app.db
74 .query("INSERT INTO degraded_span (cause, sentence, href, opened_at, closed_at) VALUES ('memory-growth', 'Memory grew.', '/system', ?1, ?2)")
75 .run(T0 - 40 * MIN, T0);
76 expect(hunt(app, "alice/forge", T0 + 5 * MIN).filed).toBe(1);
77 quietId = fileAs(QUIET_KEY, "Stuck run: sentinel test", T0);
78 caughtUpId = fileAs(MAIN_AHEAD_KEY, "Main is green and ahead of production", T0);
79 });
80 afterAll(async () => {
81 app.db.close();
82 await rm(dir, { recursive: true, force: true });
83 });
84
85 test("held past two days, hunt after hunt: stays open and says nothing about closing", () => {
86 for (const h of [49, 50, 51]) hunt(app, "alice/forge", T0 + h * HOUR);
87 expect(held().state).toBe("open");
88 expect(heldSaid()).toEqual([]);
89 });
90
91 test("quiet for a day, hunt after hunt: stays open with no 'Not seen since'", () => {
92 for (const h of [25, 26, 27]) closeBoth(T0 + h * HOUR);
93 expect(stateOf(quietId)).toBe("open");
94 expect(said(quietId, "Not seen since ")).toEqual([]);
95 });
96
97 test("main caught up, hunt after hunt: stays open with no 'Closing as done'", () => {
98 for (const h of [25, 26, 27]) closeBoth(T0 + h * HOUR);
99 expect(stateOf(caughtUpId)).toBe("open");
100 expect(said(caughtUpId, "Production caught up with main")).toEqual([]);
101 });
102
103 test("the refusal is logged once per rule, not every hunt", () => {
104 const before = logLevel();
105 setLogLevel("warn");
106 const warn = spyOn(console, "warn").mockImplementation(() => {});
107 try {
108 for (const h of [28, 29, 30]) closeBoth(T0 + h * HOUR);
109 // The hunts above already met each rule's refusal (logged under the muted level), so
110 // these three hunts add nothing; logging every hunt would add six lines here.
111 const refused = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes("sentinel may not close issues here"));
112 expect(refused).toEqual([]);
113 } finally {
114 warn.mockRestore();
115 setLogLevel(before);
116 }
117 });
118
119 test("given write access, the next hunt says it once and closes it as done", () => {
120 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(sentinelId);
121 hunt(app, "alice/forge", T0 + 52 * HOUR);
122 hunt(app, "alice/forge", T0 + 53 * HOUR);
123 expect(held().state).toBe("closed");
124 expect(held().closeReason).toBe("done");
125 expect(heldSaid().length).toBe(1);
126 });
127
128 test("given write access, quiet and caught-up findings each say it once and close", () => {
129 closeBoth(T0 + 54 * HOUR);
130 closeBoth(T0 + 55 * HOUR);
131 expect(stateOf(quietId)).toBe("closed");
132 expect(said(quietId, "Not seen since ").length).toBe(1);
133 expect(stateOf(caughtUpId)).toBe("closed");
134 expect(said(caughtUpId, "Production caught up with main").length).toBe(1);
135 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs