Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(memory): run at most `concurrency` AnotherMe subjects at once

LeoXingb5fc4159be50
diff --git a/apps/node-services/src/memory/README.md b/apps/node-services/src/memory/README.md
index c522aed0..0bbcf3df 100644
--- a/apps/node-services/src/memory/README.md
+++ b/apps/node-services/src/memory/README.md
@@ -160,9 +160,9 @@ Core configuration:
recording transcripts, Session fact extraction and fact recall, the nightly tracking-item pass, and the nightly
revision of a person's reminder guidelines from the day's proactive reminder feedback. Session facts need
`TEAMHUB_DATABASE_URL`.
-- Built-in constants (no longer environment variables): hourly tasks run each AnotherMe in parallel (a deployment
- has one account, usually one AnotherMe); one `weekly` handles at most 4 Subjects at once, and each person's Room
- Sessions also run 4 at a time; `weekly` always runs on Monday; Memory model requests share a 10-minute business
+- Built-in constants (no longer environment variables): calendar tasks and their retries run at most 4 AnotherMes
+ at once (a deployment has one account, usually one AnotherMe), and each person's Room Sessions also run 4 at a
+ time; `weekly` always runs on Monday; Memory model requests share a 10-minute business
cancellation, response header and body read timeout, with no streaming; the Chunk reconciliation runs hourly,
with at most 4 Sources indexed at once per Agent.
- `TEAMHUB_DATABASE_URL` is required: the Memory role keeps its scheduler state in that database
@@ -617,7 +617,8 @@ same subject's Daily → Wiki → Graph for that date runs again, and the recove
chain succeeds, without updating other subjects. Per-person lanes hold only within one process and are no
distributed multi-process lock; each data root still needs exactly one Scheduler process.
-The calendar tasks run each AnotherMe isolated and in parallel:
+The calendar tasks run each AnotherMe isolated and in parallel, at most 4 at once. A slot is taken only when the
+subject's lane is free, so a subject still busy with its own earlier work does not hold one:
- Hourly `wiki`: lists every authorized AnotherMe (a deployment usually has one) and runs each in isolation. The chain is Session Raw staging → indexing that Raw.
Only the 00:00 run that closes the previous day, and a meeting's recording, then ask TeamHub for a Wiki
diff --git a/apps/node-services/src/memory/concurrency.ts b/apps/node-services/src/memory/concurrency.ts
new file mode 100644
index 00000000..939eb061
--- /dev/null
+++ b/apps/node-services/src/memory/concurrency.ts
@@ -0,0 +1,23 @@
+/** Runs work with at most a fixed number of pieces in flight. */
+export type ConcurrencyLimit = <T>(work: () => Promise<T>) => Promise<T>;
+
+/**
+ * Starts work in submission order once fewer than `concurrency` pieces run.
+ * A finishing piece hands its slot straight to the next waiter, so work
+ * submitted in between cannot take the slot and exceed the limit.
+ */
+export function concurrencyLimit(concurrency: number): ConcurrencyLimit {
+ const waiters: Array<() => void> = [];
+ let active = 0;
+ return async (work) => {
+ if (active < concurrency) active += 1;
+ else await new Promise<void>((resolve) => waiters.push(resolve));
+ try {
+ return await work();
+ } finally {
+ const next = waiters.shift();
+ if (next) next();
+ else active -= 1;
+ }
+ };
+}
diff --git a/apps/node-services/src/memory/scheduler.ts b/apps/node-services/src/memory/scheduler.ts
index e80d11d4..a284250e 100644
--- a/apps/node-services/src/memory/scheduler.ts
+++ b/apps/node-services/src/memory/scheduler.ts
@@ -1,3 +1,4 @@
+import { concurrencyLimit } from "./concurrency.js";
import type { MemoryScheduleConfig } from "./config.js";
import {
memoryScheduleRunLevel,
@@ -822,7 +823,8 @@ export class MemoryScheduler {
return true;
}
- /** Runs the whole task, or each durable retry subject on its own lane. */
+ /** Runs the whole task, or each durable retry subject on its own lane, at
+ * most the task's `concurrency` at once. */
async #runSubjects(
due: DueTask,
carried: string[],
@@ -840,17 +842,20 @@ export class MemoryScheduler {
due.period,
);
// Successful subjects are absent from this durable retry set.
+ const limit = concurrencyLimit(due.input.concurrency);
await Promise.all(
due.retrySubjects
.filter((subject) => !carried.includes(subject))
.map(async (subject) => {
try {
await lane(subject, () =>
- this.#runTask(
- { ...due.input, memorySubjectKey: subject },
- due.reason,
- lane,
- due.period,
+ limit(() =>
+ this.#runTask(
+ { ...due.input, memorySubjectKey: subject },
+ due.reason,
+ lane,
+ due.period,
+ ),
),
);
} catch (error) {
diff --git a/apps/node-services/src/memory/sync-runners.ts b/apps/node-services/src/memory/sync-runners.ts
index a486eff6..019b91af 100644
--- a/apps/node-services/src/memory/sync-runners.ts
+++ b/apps/node-services/src/memory/sync-runners.ts
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { applyMemoryUpdate, validateMemoryUpdate } from "./apply.js";
import { collectDaily, loadAnotherMeSubjects } from "./collector.js";
+import { concurrencyLimit } from "./concurrency.js";
import { assertDateString, localTimeZone } from "./date.js";
import {
ensureDir,
@@ -696,33 +697,13 @@ async function mapWithConcurrency<T, R>(
concurrency: number,
mapper: (value: T, index: number) => Promise<R>,
): Promise<R[]> {
- const results: R[] = new Array(values.length);
- const waiters: Array<() => void> = [];
- let active = 0;
-
- const runLimited = async (run: () => Promise<void>): Promise<void> => {
- if (active >= concurrency) {
- await new Promise<void>((resolve) => waiters.push(resolve));
- }
- active += 1;
- try {
- await run();
- } finally {
- active -= 1;
- waiters.shift()?.();
- }
- };
-
- const tasks = values.map((value, index) =>
- runLimited(async () => {
- results[index] = await mapper(value, index);
- }),
+ const limit = concurrencyLimit(concurrency);
+ const settled = await Promise.allSettled(
+ values.map((value, index) => limit(() => mapper(value, index))),
);
-
- const settled = await Promise.allSettled(tasks);
const failed = settled.find(
(result): result is PromiseRejectedResult => result.status === "rejected",
);
if (failed) throw failed.reason;
- return results;
+ return settled.map((result) => (result as PromiseFulfilledResult<R>).value);
}
diff --git a/apps/node-services/src/memory/tasks.ts b/apps/node-services/src/memory/tasks.ts
index 28fb17e4..ef68ec74 100644
--- a/apps/node-services/src/memory/tasks.ts
+++ b/apps/node-services/src/memory/tasks.ts
@@ -1,4 +1,5 @@
import { loadAnotherMeSubjects } from "./collector.js";
+import { concurrencyLimit } from "./concurrency.js";
import { runDailyCli } from "./daily-cli.js";
import { localDate } from "./date.js";
import { recordSubjectFailure, recordWikiRefresh } from "./run-telemetry.js";
@@ -55,14 +56,19 @@ export async function runMemoryTask(
const subjectKeys = allSubjectKeys.filter((key) => !held?.includes(key));
if (subjectKeys.length === 0) return;
const lane: SubjectLane = runtime.subjectLane ?? ((_, work) => work());
+ // A slot is taken inside the lane, so a subject waiting behind its own
+ // earlier work does not hold one of the `concurrency` slots.
+ const limit = concurrencyLimit(input.concurrency);
const runOne = (memorySubjectKey: string) =>
lane(memorySubjectKey, () =>
- runMemoryTask(
- memoryRoot,
- scopedTask(input, memorySubjectKey),
- steps,
- taskState,
- runtime,
+ limit(() =>
+ runMemoryTask(
+ memoryRoot,
+ scopedTask(input, memorySubjectKey),
+ steps,
+ taskState,
+ runtime,
+ ),
),
);
// A deployment has one account and so normally one subject.
@@ -210,7 +216,8 @@ function scopedTask(
return { ...input, memorySubjectKey };
}
-/** Each subject runs on its own lane; one failure does not stop the others. */
+/** Each subject runs on its own lane, at most `concurrency` at once; one
+ * failure does not stop the others. */
async function runIsolatedSubjects(
subjectKeys: string[],
runOne: (memorySubjectKey: string) => Promise<void>,
diff --git a/apps/node-services/tests/memory/concurrency.test.ts b/apps/node-services/tests/memory/concurrency.test.ts
new file mode 100644
index 00000000..893ceb65
--- /dev/null
+++ b/apps/node-services/tests/memory/concurrency.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+
+import { concurrencyLimit } from "../../src/memory/concurrency.js";
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => (resolve = done));
+ return { promise, resolve };
+}
+
+describe("concurrencyLimit", () => {
+ it("never runs more than the limit, even for work submitted during a handoff", async () => {
+ const limit = concurrencyLimit(2);
+ let active = 0;
+ let peak = 0;
+ const gates = Array.from({ length: 5 }, deferred);
+ const run = (index: number) =>
+ limit(async () => {
+ active += 1;
+ peak = Math.max(peak, active);
+ await gates[index]!.promise;
+ active -= 1;
+ return index;
+ });
+ const first = [0, 1, 2].map(run);
+ gates[0]!.resolve();
+ // Submitted while slot 0 passes to the waiting work 2.
+ const late = [3, 4].map(run);
+ for (const gate of gates) gate.resolve();
+ await expect(Promise.all([...first, ...late])).resolves.toEqual([
+ 0, 1, 2, 3, 4,
+ ]);
+ expect(peak).toBe(2);
+ });
+
+ it("starts waiting work in submission order", async () => {
+ const limit = concurrencyLimit(1);
+ const started: number[] = [];
+ await Promise.all(
+ [0, 1, 2].map((index) =>
+ limit(async () => {
+ started.push(index);
+ }),
+ ),
+ );
+ expect(started).toEqual([0, 1, 2]);
+ });
+
+ it("frees the slot of work that fails", async () => {
+ const limit = concurrencyLimit(1);
+ await expect(
+ limit(async () => {
+ throw new Error("failed");
+ }),
+ ).rejects.toThrow("failed");
+ await expect(limit(async () => "next")).resolves.toBe("next");
+ });
+});
diff --git a/apps/node-services/tests/memory/scheduler-recovery.test.ts b/apps/node-services/tests/memory/scheduler-recovery.test.ts
index 78f4ba48..fe5ea774 100644
--- a/apps/node-services/tests/memory/scheduler-recovery.test.ts
+++ b/apps/node-services/tests/memory/scheduler-recovery.test.ts
@@ -217,6 +217,43 @@ describe("bounded per-subject calendar recovery", () => {
);
expect(row(file).pending).toEqual([]);
});
+ it("retries failing subjects at most `concurrency` at once", async () => {
+ const file = await checkpoint();
+ const subjects = ["agent_1", "agent_2", "agent_3", "agent_4"];
+ let retrying = false;
+ let active = 0;
+ let peak = 0;
+ const retried: string[] = [];
+ const scheduler = new MemoryScheduler(
+ { ...config, concurrency: 2 },
+ daily(async (task) => {
+ if (!retrying) {
+ for (const subject of subjects) {
+ recordSubjectFailure({
+ memory_subject_key: subject,
+ error: "provider offline",
+ });
+ }
+ return;
+ }
+ active += 1;
+ peak = Math.max(peak, active);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ active -= 1;
+ retried.push(task.memorySubjectKey!);
+ }),
+ undefined,
+ file,
+ );
+ scheduler.runDueTasks(start);
+ await scheduler.idle();
+ expect(row(file).pending[0]).toMatchObject({ retrySubjects: subjects });
+ retrying = true;
+ scheduler.runDueTasks(new Date(start.getTime() + 15_000));
+ await scheduler.idle();
+ expect(retried.sort()).toEqual(subjects);
+ expect(peak).toBe(2);
+ });
it("retries within the hour at 15s, 1m, 3m, 10m and 1h, then preserves the terminal receipt", async () => {
const file = await checkpoint();
const calls = vi.fn(async () => {
diff --git a/apps/node-services/tests/memory/tasks.test.ts b/apps/node-services/tests/memory/tasks.test.ts
index be3c1fad..583e48eb 100644
--- a/apps/node-services/tests/memory/tasks.test.ts
+++ b/apps/node-services/tests/memory/tasks.test.ts
@@ -581,6 +581,58 @@ describe("runMemoryTask", () => {
expect(taskSteps.wikiSync).toHaveBeenCalledTimes(2);
});
+ it("runs at most `concurrency` AnotherMe subjects at once", async () => {
+ const taskSteps = steps();
+ let active = 0;
+ let peak = 0;
+ taskSteps.daily.mockImplementation(async () => {
+ active += 1;
+ peak = Math.max(peak, active);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ active -= 1;
+ return { processedSubjectCount: 1 };
+ });
+ await runMemoryTask(
+ memoryRoot,
+ { task: "daily", date: "2026-08-31", concurrency: 2 },
+ taskSteps,
+ taskState(),
+ subjects("agent_1", "agent_2", "agent_3", "agent_4", "agent_5"),
+ );
+ expect(taskSteps.daily).toHaveBeenCalledTimes(5);
+ expect(peak).toBe(2);
+ });
+
+ it("does not hold a slot for a subject waiting behind its own lane", async () => {
+ const taskSteps = steps();
+ let releaseBusy: () => void = () => undefined;
+ const busyLane = new Promise<void>((resolve) => {
+ releaseBusy = resolve;
+ });
+ const running = runMemoryTask(
+ memoryRoot,
+ { task: "daily", date: "2026-08-31", concurrency: 1 },
+ taskSteps,
+ taskState(),
+ {
+ ...subjects("agent_busy", "agent_free"),
+ subjectLane: async (subject, work) => {
+ if (subject === "agent_busy") await busyLane;
+ return work();
+ },
+ },
+ );
+ await vi.waitFor(() => {
+ expect(taskSteps.daily).toHaveBeenCalledTimes(1);
+ });
+ expect(taskSteps.daily.mock.calls[0]![0]).toEqual(
+ expect.arrayContaining(["--memory-subject-key", "agent_free"]),
+ );
+ releaseBusy();
+ await running;
+ expect(taskSteps.daily).toHaveBeenCalledTimes(2);
+ });
+
it("fails the calendar run only when every AnotherMe refresh fails", async () => {
const taskSteps = steps();
taskSteps.wiki.mockRejectedValue(new Error("graph failed"));