Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

feat(brain): log event-loop stalls in the brain with the last phase marks

leen.zhou23ae30e69852
diff --git a/packages/agent/src/core/types.ts b/packages/agent/src/core/types.ts
index 8926da4..3adb3e5 100644
--- a/packages/agent/src/core/types.ts
+++ b/packages/agent/src/core/types.ts
@@ -48,6 +48,11 @@ export interface OpenSessionOptions {
signal?: AbortSignal;
unattended?: boolean;
onCompaction?(event: CompactionActivity): void;
+ /**
+ * Diagnostics only: called as each opening step starts, so a brain stall can be pinned to the
+ * step that held the thread. Names are fixed; nothing about the session is passed.
+ */
+ phase?(name: "runtime" | "model" | "session_load" | "extensions" | "create" | "bind"): void;
/** The Bot's enabled skills, listed after the system prompt. */
skills?: { entries: SkillPromptEntry[]; language: "zh" | "en" };
/**
diff --git a/packages/agent/src/runtime/runtime-parts/runtime-session.ts b/packages/agent/src/runtime/runtime-parts/runtime-session.ts
index ef5f951..e73fad8 100644
--- a/packages/agent/src/runtime/runtime-parts/runtime-session.ts
+++ b/packages/agent/src/runtime/runtime-parts/runtime-session.ts
@@ -39,7 +39,9 @@ export function createSessionOperations({
throw new AgentError("chatgpt_reconnect_required");
try {
opts.signal?.throwIfAborted();
+ opts.phase?.("runtime");
const { pi, runtime, custom } = await buildRuntime();
+ opts.phase?.("model");
opts.signal?.throwIfAborted();
// A workflow's `cheap` tier runs on the auxiliary model when one is usable.
const model =
@@ -58,6 +60,8 @@ export function createSessionOperations({
opts.signal?.throwIfAborted();
const sessionFile = await sessionPaths(dataDir, opts);
opts.signal?.throwIfAborted();
+ // pi reads and parses the whole JSONL synchronously here; it grows with the session.
+ opts.phase?.("session_load");
const manager = sessionFile
? pi.SessionManager.open(sessionFile, opts.sessionDir, opts.homeDir)
: pi.SessionManager.create(opts.homeDir, opts.sessionDir);
@@ -249,6 +253,7 @@ export function createSessionOperations({
entries: () => manager.getEntries(),
};
if (opts.context && !opts.localTools) throw new AgentError("internal");
+ opts.phase?.("extensions");
const extensions = await loadLocalExtensions(
opts.homeDir,
join(dataDir, "pi"),
@@ -270,6 +275,7 @@ export function createSessionOperations({
if (compaction)
compaction.estimateHistory = (messages) =>
historyTokens(messages, extensions.loadout?.synchronize());
+ opts.phase?.("create");
const { session } = await pi.createAgentSession({
cwd: opts.homeDir,
agentDir: join(dataDir, "pi"),
@@ -293,6 +299,7 @@ export function createSessionOperations({
// A restored JSONL can name another model. Explicit caller selection wins.
try {
opts.signal?.throwIfAborted();
+ opts.phase?.("bind");
if (opts.localTools) await session.bindExtensions({});
// Tool groups the transcript still declares stay loaded when still allowed.
extensions.loadout?.reset(session.messages);
diff --git a/packages/brain/src/index.ts b/packages/brain/src/index.ts
index 3893643..3aba904 100644
--- a/packages/brain/src/index.ts
+++ b/packages/brain/src/index.ts
@@ -96,6 +96,7 @@ import { createBrainController } from "./runtime/startup/create-brain-controller
import { createKernelStorage } from "./runtime/startup/create-kernel-storage.ts";
import { deferredMaintenance } from "./runtime/startup/deferred-maintenance.ts";
import { firstRpcDiagnostics } from "./runtime/startup/first-rpcs.ts";
+import { watchBrainLoop } from "./runtime/startup/loop-stall-watch.ts";
import { registerAcpRpc } from "./runtime/startup/register-acp-rpc.ts";
import { registerAppRpc } from "./runtime/startup/register-app-rpc.ts";
import { registerCapabilities } from "./runtime/startup/register-capabilities.ts";
@@ -309,6 +310,7 @@ export async function startBrain(opts: {
let modelPort: ModelProvidersPort | undefined;
let runRetention: RunRetention | undefined;
let startupDiagnostics: ReturnType<typeof firstRpcDiagnostics> | undefined;
+ let loopWatch: ReturnType<typeof watchBrainLoop> | undefined;
let maintenance: ReturnType<typeof deferredMaintenance> | undefined;
const sessionTailController = new AbortController();
let sessionTailReconciliation: Promise<void> | undefined;
@@ -376,6 +378,9 @@ export async function startBrain(opts: {
interactiveAttached = value;
},
stopSessionRecovery,
+ get loopWatch() {
+ return loopWatch;
+ },
get startupDiagnostics() {
return startupDiagnostics;
},
@@ -529,6 +534,7 @@ export async function startBrain(opts: {
};
const { settings, bots, redactor, logger, secrets } = createKernelStorage(startup);
startupDiagnostics = firstRpcDiagnostics(logger);
+ loopWatch = watchBrainLoop(logger);
const recoveryEvents = new RunEventsRepo(db);
const recoveryRunRowId = recoveryEvents.latestRunRowId();
timing.mark("kernel_storage");
@@ -655,8 +661,14 @@ export async function startBrain(opts: {
const agent: AgentRuntime = {
...contentRuntime,
async openSession(input) {
+ loopWatch?.mark("open.start");
await waitForSessionRecovery(input.signal);
- return contentRuntime.openSession(input);
+ const session = await contentRuntime.openSession({
+ ...input,
+ phase: (name) => loopWatch?.mark(`open.${name}`),
+ });
+ loopWatch?.mark("open.done");
+ return session;
},
...(compactHistory && {
async compactHistory(input) {
@@ -1020,6 +1032,7 @@ export async function startBrain(opts: {
} catch (error) {
progress?.stop();
startupDiagnostics?.stop();
+ loopWatch?.stop();
await maintenance?.stop();
await stopSessionRecovery();
let drained = false;
diff --git a/packages/brain/src/runtime/startup/business-rpc.ts b/packages/brain/src/runtime/startup/business-rpc.ts
index d63b54b..ce6f0f4 100644
--- a/packages/brain/src/runtime/startup/business-rpc.ts
+++ b/packages/brain/src/runtime/startup/business-rpc.ts
@@ -15,6 +15,7 @@ import type { BrainSleep } from "../queue/brain-sleep.ts";
interface StartupContext {
startupDiagnostics?: ReturnType<typeof import("./first-rpcs.ts").firstRpcDiagnostics>;
+ loopWatch?: { mark(phase: string): void };
stopping: boolean;
waitForContent(signal: AbortSignal): Promise<void>;
opts?: { requestSource?: () => "acp" | undefined };
@@ -82,6 +83,8 @@ export function registerBusinessRpc<K extends keyof typeof KernelMethods>(
if (ctx.stopping) throw new RpcError(-32001, "Brain stopping");
ctx.sleep?.assertAdmission();
const finishTiming = ctx.startupDiagnostics?.begin(method);
+ // Method names are fixed protocol identifiers; parameters never reach the stall log.
+ ctx.loopWatch?.mark(method);
const request = Promise.resolve().then(async () => {
context.signal.throwIfAborted();
if (!ctx.interactiveAttached && !ctx.offlineAllowed.has(method))
diff --git a/packages/brain/src/runtime/startup/create-brain-controller.ts b/packages/brain/src/runtime/startup/create-brain-controller.ts
index b805c2a..b936121 100644
--- a/packages/brain/src/runtime/startup/create-brain-controller.ts
+++ b/packages/brain/src/runtime/startup/create-brain-controller.ts
@@ -35,6 +35,7 @@ interface StartupContext {
interactiveAttached: boolean;
stopSessionRecovery(): Promise<void>;
stopStartupMaintenance(): Promise<void>;
+ loopWatch?: { stop(): void };
chat: ChatService;
groups: GroupOrchestrationPort;
clientChange: Promise<void>;
@@ -232,6 +233,7 @@ export function createBrainController(ctx: StartupContext): Awaited<ReturnType<t
const steps = [
() => ctx.peer.dispose(),
() => ctx.logger.info("Brain stopped"),
+ () => ctx.loopWatch?.stop(),
() => ctx.db.close(),
];
for (const step of steps) {
diff --git a/packages/brain/src/runtime/startup/loop-stall-watch.ts b/packages/brain/src/runtime/startup/loop-stall-watch.ts
new file mode 100644
index 0000000..e77feee
--- /dev/null
+++ b/packages/brain/src/runtime/startup/loop-stall-watch.ts
@@ -0,0 +1,43 @@
+import type { Logger } from "@pibot/observability";
+
+const RECENT_MARKS = 12;
+
+/**
+ * The brain runs every chat, group step and Git read on one thread. In the v0.0.3 Windows
+ * acceptance it stalled for about 9 s and the only trace was other timers firing late, so a long
+ * gap between ticks is logged with the last few phase marks. Marks are fixed identifiers (RPC
+ * method names, session-open steps); `agoMs` is how long before the stall was noticed each one
+ * was set, so the mark that precedes the gap names the work that held the thread.
+ */
+export function watchBrainLoop(
+ logger: Pick<Logger, "warn">,
+ intervalMs = 250,
+ thresholdMs = 1_000,
+) {
+ const marks: { phase: string; at: number }[] = [];
+ let last = performance.now();
+ const timer = setInterval(() => {
+ const now = performance.now();
+ const lag = now - last - intervalMs;
+ last = now;
+ if (lag < thresholdMs) return;
+ logger.warn(
+ JSON.stringify({
+ module: "brain",
+ event: "event_loop_stall",
+ ms: Math.round(lag),
+ recent: marks.map((mark) => ({ phase: mark.phase, agoMs: Math.round(now - mark.at) })),
+ }),
+ );
+ }, intervalMs);
+ timer.unref();
+ return {
+ mark(phase: string) {
+ marks.push({ phase, at: performance.now() });
+ if (marks.length > RECENT_MARKS) marks.shift();
+ },
+ stop() {
+ clearInterval(timer);
+ },
+ };
+}