Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(goal): fill every free concurrency slot in one advance (#21798)

Arvin Xucfecc7bc67a2
diff --git a/apps/server/src/services/goal/advanceGoal.test.ts b/apps/server/src/services/goal/advanceGoal.test.ts
index ea335b07034..6dcfa58b094 100644
--- a/apps/server/src/services/goal/advanceGoal.test.ts
+++ b/apps/server/src/services/goal/advanceGoal.test.ts
@@ -70,6 +70,44 @@ describe('advanceGoal', () => {
expect(mocks.tick).toHaveBeenCalledTimes(2);
});
+ it('keeps filling free slots after a tick that started a run', async () => {
+ // A released wave of five started one Task per advance: dispatching reports
+ // `waiting_external`, which ended the advance with two slots still free.
+ const started = (taskId: string) => async (_goalId: string, options: any) => {
+ options?.onDecision?.({ effects: [{ targetId: taskId, type: 'started_run' }] });
+ return { goalId: 'goal-1', message: `Started task ${taskId}`, outcome: 'waiting_external' };
+ };
+ mocks.tick
+ .mockImplementationOnce(started('T-1'))
+ .mockImplementationOnce(started('T-2'))
+ .mockImplementationOnce(started('T-3'))
+ .mockImplementationOnce(async (_goalId: string, options: any) => {
+ options?.onDecision?.({ effects: [] });
+ return tickResult('waiting_external');
+ });
+
+ const { result, ticks } = await advance();
+
+ expect(ticks).toBe(4);
+ expect(mocks.tick).toHaveBeenCalledTimes(4);
+ // The cap-reached tick says nothing new; the caller learns what was started.
+ expect(result).toMatchObject({ message: 'Started task T-3', outcome: 'waiting_external' });
+ });
+
+ it('reports a person-facing stop over the runs it started', async () => {
+ mocks.tick
+ .mockImplementationOnce(async (_goalId: string, options: any) => {
+ options?.onDecision?.({ effects: [{ type: 'started_run' }] });
+ return tickResult('waiting_external');
+ })
+ .mockResolvedValueOnce(tickResult('waiting_human'));
+
+ const { result, ticks } = await advance();
+
+ expect(ticks).toBe(2);
+ expect(result.outcome).toBe('waiting_human');
+ });
+
it.each(['achieved', 'failed', 'no_progress', 'waiting_human'] as const)(
'stops on %s without another tick',
async (outcome) => {
@@ -119,6 +157,20 @@ describe('advanceGoal trajectory recording', () => {
outcome,
});
+ /** Starts a run on the first tick, then finds no free slot, as a capped goal does. */
+ const startsOneRun = () => {
+ let started = false;
+ return async (_goalId: string, options: any) => {
+ if (started) {
+ options?.onDecision?.({ ...observation('waiting_external'), effects: [] });
+ } else {
+ started = true;
+ options?.onDecision?.(observation('waiting_external'));
+ }
+ return tickResult('waiting_external');
+ };
+ };
+
/** Minimal store that only has to remember what was written. */
const memoryStore = () => {
const state: { partial?: any; saved?: any } = {};
@@ -154,10 +206,7 @@ describe('advanceGoal trajectory recording', () => {
const { state, store } = memoryStore();
mocks.createStore.mockReturnValue(store);
mocks.status.mockResolvedValue('running');
- mocks.tick.mockImplementation(async (_goalId: string, options: any) => {
- options?.onDecision?.(observation('waiting_external'));
- return tickResult('waiting_external');
- });
+ mocks.tick.mockImplementation(startsOneRun());
await advanceGoal({ goalId: 'goal-1', trigger: 'sweep', userId: 'user-1' });
@@ -175,10 +224,7 @@ describe('advanceGoal trajectory recording', () => {
const { store } = memoryStore();
mocks.createStore.mockReturnValue(store);
mocks.status.mockResolvedValue('running');
- mocks.tick.mockImplementation(async (_goalId: string, options: any) => {
- options?.onDecision?.(observation('waiting_external'));
- return tickResult('waiting_external');
- });
+ mocks.tick.mockImplementation(startsOneRun());
await advanceGoal({ goalId: 'goal-1', trigger: 'sweep', userId: 'user-1' });
@@ -193,10 +239,7 @@ describe('advanceGoal trajectory recording', () => {
const { store } = memoryStore();
mocks.createStore.mockReturnValue(store);
mocks.status.mockResolvedValue('running');
- mocks.tick.mockImplementation(async (_goalId: string, options: any) => {
- options?.onDecision?.(observation('waiting_external'));
- return tickResult('waiting_external');
- });
+ mocks.tick.mockImplementation(startsOneRun());
await advanceGoal({ goalId: 'goal-1', trigger: 'sweep', userId: 'user-1' });
@@ -206,7 +249,8 @@ describe('advanceGoal trajectory recording', () => {
advancesTotal: 1,
finalStatus: null,
goalId: 'goal-1',
- ticksTotal: 1,
+ // The dispatch, then the tick that finds no free slot left.
+ ticksTotal: 2,
// The partial, because that is the object that exists while the goal
// runs. Pointing at the finalized key here made `hasTrace` a lie and
// had the server sign a URL that 404s until the goal was over.
diff --git a/apps/server/src/services/goal/advanceGoal.ts b/apps/server/src/services/goal/advanceGoal.ts
index 711f54e1220..8661679619e 100644
--- a/apps/server/src/services/goal/advanceGoal.ts
+++ b/apps/server/src/services/goal/advanceGoal.ts
@@ -6,6 +6,7 @@ import { getServerDB } from '@/database/server';
import { GoalAdvanceRecorder, TERMINAL_GOAL_STATUSES } from './goalTraceRecorder';
import { GoalService } from './index';
+import type { GoalTickOptions } from './traceObservation';
const log = debug('lobe-server:goal-advance');
@@ -15,6 +16,8 @@ const log = debug('lobe-server:goal-advance');
* `waiting_external` is one of them here, and that is the whole point of the
* event-driven design: it means a graph Task is now executing, so the next move
* belongs to that task's completion, not to a poll loop holding a worker open.
+ * The one exception is a tick that just started a run itself: another slot may
+ * still be free, so the advance ticks again (see `startedRun`).
*/
const STOP_OUTCOMES = new Set<GoalTickOutcome>([
'achieved',
@@ -26,7 +29,7 @@ const STOP_OUTCOMES = new Set<GoalTickOutcome>([
/**
* Safety limit for one advance. Dispatching a Task takes two ticks and an
- * advance now fills every free concurrency slot, so a healthy run is a
+ * advance fills every free concurrency slot, so a healthy run is a
* handful; anything near this is a loop that is not converging, and the sweep
* will come back to it.
*/
@@ -63,14 +66,36 @@ export const advanceGoal = async ({
const service = new GoalService(db, userId, workspaceId);
const recorder = new GoalAdvanceRecorder(db, goalId, trigger);
+ // A tick that starts a run reports `waiting_external` β€” that Task is now
+ // executing β€” but the other free concurrency slots are not. Stopping there
+ // started one Task per advance: a released wave of five ran one unit and left
+ // the rest in backlog until the stalled-goal sweep (15 minutes) came back.
+ // So a tick that started a run is followed by another, until a tick starts
+ // nothing (the cap is reached, or nothing else is ready).
+ let startedRun: boolean;
+ const record = recorder.onDecision;
+ const onDecision: GoalTickOptions['onDecision'] = (observation) => {
+ if (observation.effects.some((effect) => effect.type === 'started_run')) startedRun = true;
+ record?.(observation);
+ };
+
let result: GoalTickResult | undefined;
+ // The run this advance last started. Reported in place of the tick that only
+ // found the cap reached, so a caller still learns which Task it started.
+ let lastStart: GoalTickResult | undefined;
try {
for (let ticks = 1; ticks <= MAX_TICKS_PER_ADVANCE; ticks++) {
- result = await service.tick(goalId, { onDecision: recorder.onDecision });
+ startedRun = false;
+ result = await service.tick(goalId, { onDecision });
log('goal %s tick %d β†’ %s (%s)', goalId, ticks, result.outcome, result.message);
+ if (startedRun && result.outcome === 'waiting_external') {
+ lastStart = result;
+ continue;
+ }
if (STOP_OUTCOMES.has(result.outcome)) {
await settleTrace(recorder, service, goalId);
- return { goalId, result, ticks };
+ const reported = result.outcome === 'waiting_external' && lastStart ? lastStart : result;
+ return { goalId, result: reported, ticks };
}
}
} catch (error) {