Skip to content

Commit f472b77

Browse files
author
hzq
committed
Bound scheduler occupancy history
Retain recent execution profiles, not polled ones, and reread durable run timings when an observed profile is evicted.
1 parent cf61a42 commit f472b77

4 files changed

Lines changed: 113 additions & 2 deletions

File tree

‎docs/stability.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,9 @@ An overview shares that read across its queued rows. Estimates include the globa
338338
positions count only this owner, and a missing or no-longer-queued row does not block inspection.
339339
The fallback uses the same lower median, weighting shared sample arrays by occurrence instead
340340
of expanding them. A bounded rank scan covers large sets of distinct durations.
341+
The kernel keeps up to 1,024 observed owner/agent profiles with 50 timings each.
342+
Recent executions renew a profile, not status polling. Eviction falls back to recent
343+
durable run durations.
341344
`node dist/bench/queue-view.js` measures the status and overview routes with two fixture owners
342345
and a blocked slot, without a live model. Use
343346
`node --expose-gc dist/bench/queue-estimate-scale.js --mode distinct` to measure the pure

‎docs/zh-CN/stability.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
142142

143143
排队估时每批最多读取 256 个待运行任务的 ID、所有者和智能体标识,不读取输入输出。概览里的多条任务共享一次前缀查询;估时仍考虑全局顺序,但位置只计本所有者,缺失或已不排队的记录会被跳过。`node dist/bench/queue-view.js` 用两个夹具所有者和一个被占用的执行槽压测状态与概览接口,不调用真实模型。
144144
全局后备中位数仍取下中位数;共享的耗时样本按出现次数计权,不展开成副本。不同耗时值很多时用有界排名扫描。`node --expose-gc dist/bench/queue-estimate-scale.js --mode distinct` 测纯估时算法下的大量不同样本;`--mode shared` 测共享样本。
145+
内核最多保留 1,024 组所有者和智能体的实测耗时,每组 50 条。实际执行才续新,不靠状态轮询保留;淘汰后重新从持久化记录取近期耗时。
145146

146147
通过 HTTP 创建运行时(包括媒体任务和工作流草稿),网关异步等写锁,不让整个事件循环停下来。等待时间不超过连接超时和 5 秒中的较短者。
147148
等待队列先进先出,每个 owner 最多 8 个请求,全网关最多 64 个;请求体另按每个 owner 32 MiB、全网关 64 MiB 限制。

‎src/kernel/admission.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import type { KernelLimits, QueueInsight } from './types.js';
1818

1919
type AgentIdentity = Pick<Run, 'owner' | 'agentId'>;
2020
const sampleKey = ({ owner, agentId }: AgentIdentity) => JSON.stringify([owner, agentId]);
21+
const MAX_TIMING_PROFILES = 1024;
2122

2223
/** 准入需要的内核能力。 */
2324
export interface AdmissionRuntime {
@@ -52,7 +53,7 @@ export class Admission {
5253
slotBreaches = 0;
5354
/** Runs holding a slot now: when they were admitted and whose occupancy sample they feed. */
5455
private admitted = new Map<string, { at: number; agent: AgentIdentity }>();
55-
/** Observed slot occupancy (ms) per owner+agent, newest last, at most 50 each. */
56+
/** Recent executions, newest profile last; at most 50 observations per profile. */
5657
private occupancy = new Map<string, number[]>();
5758
/** Stored-duration fallback per owner+agent, refreshed at most every 5 s. */
5859
private storedDurations = new Map<string, { at: number; sample: number[] }>();
@@ -138,7 +139,14 @@ export class Admission {
138139
const sample = this.occupancy.get(key) ?? [];
139140
sample.push(Date.now() - held.at);
140141
if (sample.length > 50) sample.shift();
142+
this.occupancy.delete(key);
141143
this.occupancy.set(key, sample);
144+
if (this.occupancy.size > MAX_TIMING_PROFILES) {
145+
const oldest = this.occupancy.keys().next().value!;
146+
this.occupancy.delete(oldest);
147+
// A prior fallback may predate the observations that just aged out.
148+
this.storedDurations.delete(oldest);
149+
}
142150
}
143151
/** Observed occupancy when there is enough of it; otherwise recent stored durations. */
144152
private sampleFor(agent: AgentIdentity, key: string): Sample {
@@ -149,7 +157,7 @@ export class Admission {
149157
return cached.sample.length ? cached.sample : observed;
150158
const stored = this.rt.store.recentDurations(agent.owner, agent.agentId);
151159
this.storedDurations.set(key, { at: Date.now(), sample: stored });
152-
if (this.storedDurations.size > 1024)
160+
if (this.storedDurations.size > MAX_TIMING_PROFILES)
153161
this.storedDurations.delete(this.storedDurations.keys().next().value!);
154162
return stored.length ? stored : observed;
155163
}

‎test/admission-occupancy.test.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import assert from 'node:assert/strict';
2+
import { setImmediate as nextTurn } from 'node:timers/promises';
3+
import test from 'node:test';
4+
import type { NodeHub } from '../src/fabric/network.js';
5+
import { Admission } from '../src/kernel/admission.js';
6+
import { makeBundle } from '../src/lang/bundle.js';
7+
import type { Store } from '../src/store/store.js';
8+
import { agent, setup } from './helpers.js';
9+
10+
test('occupancy keeps recent executions and reloads durable timing after eviction', async () => {
11+
const s = await setup();
12+
try {
13+
s.store.publish('owner', makeBundle(agent()));
14+
const completed = await s.request('POST', '/v1/responses', {
15+
model: 'agent/test',
16+
input: 'fixture',
17+
});
18+
assert.equal(completed.statusCode, 200, completed.body);
19+
assert.equal(completed.json().status, 'completed');
20+
const runId = String(completed.json().id);
21+
const setDuration = s.store.prepare(
22+
"UPDATE run_summaries SET payload=json_set(payload,'$.created_at',0,'$.updated_at',?) WHERE run_id=?",
23+
);
24+
setDuration.run(700, runId);
25+
const cold = 'agent/test';
26+
const hot = 'agent/hot';
27+
const agentOf = (id: string) => id.split(':', 1)[0]!;
28+
const reads: string[] = [];
29+
const lane = new Admission({
30+
store: {
31+
actionWrites: new Set(),
32+
queuedRun: (id: string) => ({
33+
id,
34+
owner: 'owner',
35+
agentId: agentOf(id),
36+
digest: 'fixture',
37+
}),
38+
bundle: (_owner: string, id: string) => ({ digest: 'fixture', agent: { id } }),
39+
queuedRunIdentities: (ids: string[]) =>
40+
new Map(ids.map((id) => [id, { owner: 'owner', agentId: agentOf(id) }])),
41+
queueReason: () => 'admission',
42+
recentDurations(owner: string, id: string) {
43+
reads.push(id);
44+
return s.store.recentDurations(owner, id);
45+
},
46+
} as unknown as Store,
47+
hub: {} as NodeHub,
48+
limits: { maxActiveRuns: 1, approvalTimeoutMs: 1000 },
49+
closing: () => false,
50+
releaseRun: () => {},
51+
execute: async () => {},
52+
});
53+
let sequence = 0;
54+
const execute = async (ids: string[]) => {
55+
lane.queue = ids.map((id) => id + ':' + sequence++);
56+
lane.pump();
57+
for (let i = 0; i < 5 && lane.tasks.size; i++) await nextTurn();
58+
assert.equal(lane.tasks.size, 0);
59+
assert.equal(lane.queue.length, 0);
60+
assert.equal(lane.active, 0);
61+
};
62+
const estimate = () => {
63+
lane.queue = [cold + ':probe', 'target'];
64+
try {
65+
return lane.queueInsight('target', 'owner', 'queued')?.estimated_start_ms;
66+
} finally {
67+
lane.queue = [];
68+
}
69+
};
70+
await execute([cold]);
71+
assert.equal(estimate(), 700);
72+
await execute([cold, cold, cold, cold, cold, hot]);
73+
await execute(Array.from({ length: 1022 }, (_, i) => 'agent/filler-' + i));
74+
const profiles = (lane as unknown as { occupancy: Map<string, number[]> }).occupancy;
75+
const key = (id: string) => JSON.stringify(['owner', id]);
76+
assert.equal(profiles.size, 1024);
77+
assert.equal(profiles.get(key(cold))?.length, 6);
78+
estimate();
79+
assert.deepEqual(reads, [cold], 'polling uses observed samples without renewing recency');
80+
setDuration.run(27_000, runId);
81+
await execute([
82+
...Array.from({ length: 52 }, () => hot),
83+
'agent/overflow-1',
84+
'agent/overflow-2',
85+
]);
86+
assert.equal(profiles.size, 1024);
87+
assert.equal(profiles.has(key(cold)), false);
88+
assert.equal(
89+
profiles.get(key(hot))?.length,
90+
50,
91+
'recent executions renew and bound the profile',
92+
);
93+
assert.equal(estimate(), 27_000, 'eviction discards the old cached database sample too');
94+
assert.deepEqual(reads, [cold, cold]);
95+
assert.equal(lane.slotBreaches, 0);
96+
} finally {
97+
await s.cleanup();
98+
}
99+
});

0 commit comments

Comments
 (0)