pi-crew 0.9.25 → 0.9.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/NOTICE.md +14 -0
- package/assets/crew-vibes.ttf +0 -0
- package/assets/runner-spritesheet.png +0 -0
- package/dist/build-meta.json +255 -40
- package/dist/index.mjs +1564 -241
- package/dist/index.mjs.map +4 -4
- package/docs/perf/optimization-plan-2026-07-verified.md +396 -0
- package/package.json +10 -3
- package/scripts/bench-check.mjs +96 -0
- package/scripts/bench-cold-start.mjs +216 -0
- package/scripts/build-bundle.mjs +84 -0
- package/scripts/build-crew-vibes-font.py +328 -0
- package/scripts/check-all-skills.ts +294 -0
- package/scripts/check-bundle-staleness.mjs +97 -0
- package/scripts/check-conflict-markers.mjs +91 -0
- package/scripts/check-lazy-imports.mjs +28 -0
- package/scripts/install-crew-vibes-font.mjs +91 -0
- package/scripts/postinstall.mjs +47 -0
- package/scripts/profile-startup.mjs +125 -0
- package/scripts/release-smoke.mjs +74 -0
- package/scripts/run-bench.mjs +47 -0
- package/scripts/run-real-chain.ts +41 -0
- package/scripts/test-issue-29-crash.ts +111 -0
- package/scripts/test-issue-29-e2e.ts +183 -0
- package/scripts/test-issue-29-real-runtime.ts +330 -0
- package/scripts/test-issue-29-real-tasks.ts +387 -0
- package/scripts/test-issue-29-team-tool.ts +105 -0
- package/scripts/test-runner.mjs +74 -0
- package/scripts/verify-flicker-fix.ts +109 -0
- package/scripts/verify-skill.ts +550 -0
- package/scripts/watch-bundle.mjs +259 -0
- package/scripts/watchdog-harness.ts +119 -0
- package/src/agents/discover-agents.ts +6 -1
- package/src/config/defaults.ts +6 -0
- package/src/extension/crew-vibes/cat-frames.ts +18 -0
- package/src/extension/crew-vibes/config.ts +195 -0
- package/src/extension/crew-vibes/figures.ts +94 -0
- package/src/extension/crew-vibes/font-detect.ts +58 -0
- package/src/extension/crew-vibes/index.ts +396 -0
- package/src/extension/crew-vibes/provider-usage.ts +330 -0
- package/src/extension/crew-vibes/render.ts +206 -0
- package/src/extension/crew-vibes/speed.ts +286 -0
- package/src/extension/knowledge-injection.ts +12 -3
- package/src/extension/management.ts +23 -3
- package/src/extension/register.ts +7 -0
- package/src/runtime/child-pi.ts +117 -10
- package/src/runtime/crew-agent-records.ts +10 -3
- package/src/runtime/retry-executor.ts +4 -1
- package/src/runtime/task-runner/state-helpers.ts +9 -30
- package/src/runtime/team-runner.ts +5 -3
- package/src/state/atomic-write.ts +153 -49
- package/src/state/event-log.ts +28 -19
- package/src/state/locks.ts +7 -8
- package/src/state/mailbox.ts +15 -4
- package/src/state/state-store.ts +39 -10
- package/src/teams/discover-teams.ts +56 -1
- package/src/utils/safe-paths.ts +2 -1
- package/src/workflows/discover-workflows.ts +72 -1
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
# Optimization Plan — pi-crew v0.9.26 (verified, bench-first)
|
|
2
|
+
|
|
3
|
+
> Kế hoạch tối ưu hiệu năng đã **verify từng giả định trên code hiện tại** (v0.9.26).
|
|
4
|
+
> Khác với các review tĩnh trước, plan này phân loại đề xuất theo **độ chắc chắn của win**
|
|
5
|
+
> và **rủi ro correctness**, và bắt buộc **đo trước khi sửa** (bench-first) cho mọi item
|
|
6
|
+
> có nghi vấn về mức tác động.
|
|
7
|
+
>
|
|
8
|
+
> Nền tảng: `docs/perf/performance-review-2026-07.md` (F1–F21) + phần re-verify trong
|
|
9
|
+
> phiên review 2026-07-08. Mọi finding đã đối chiếu lại file:line bên dưới.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 0. Nguyên tắc & tổng quan
|
|
14
|
+
|
|
15
|
+
### Nguyên tắc thực thi
|
|
16
|
+
1. **Bench-first**: mỗi item có nghi vấn về mức win (F1, F2, F3, F4) PHẢI có micro-bench trước/sau. Repo đã có harness `test/bench/*.bench.ts` + `npm run bench` + `npm run bench:check` (so với `test/bench/baseline.json`).
|
|
17
|
+
2. **Windows là môi trường nghiệm thu chính** — `fsync`/`stat`/`spawn` đắt hơn Linux nhiều lần; win phải hiện trên Windows.
|
|
18
|
+
3. **Không đánh đổi correctness lấy tốc độ**: các item chạm state/durability chỉ merge khi `npm test` (unit + integration) xanh, không riêng typecheck.
|
|
19
|
+
4. **Từng PR nhỏ, 1 finding/PR**, có rollback rõ ràng (feature flag hoặc config override khi có thể).
|
|
20
|
+
|
|
21
|
+
### Bảng phân loại (kết luận từ phần verify)
|
|
22
|
+
|
|
23
|
+
| Item | Win thực tế | Rủi ro | Phase | Ghi chú verify |
|
|
24
|
+
|---|---|---|---|---|
|
|
25
|
+
| **F17** resolve/cache discoverWorkflows | Cao (tới 5 Hz → ~0) | Thấp | 1 | `powerbar-publisher.ts:284` gọi qua coalescer 200ms; `discover-workflows.ts` **0 cache** |
|
|
26
|
+
| **F15** TTL discovery + cache teams/workflows | TB–Cao | Thấp | 1 | `discover-agents.ts:493` TTL=500ms; teams/workflows không cache |
|
|
27
|
+
| **F4** durability `best-effort` cho write informational | TB (Cao trên Windows) | Thấp | 1 | `atomic-write.ts:384,409-411` fsync data+dir vô điều kiện |
|
|
28
|
+
| **F9** ring-buffer rawTextEvents | Thấp–TB (run dài) | Thấp | 1 | `child-pi.ts:577,636` push không cap |
|
|
29
|
+
| **F2** gộp 3 stat liên tiếp → 1 | Thấp | Thấp | 2 | `state-helpers.ts:76-113`: 3 stat sync liên tiếp, không I/O giữa chúng = rác |
|
|
30
|
+
| **F3a** fsync chỉ terminal events | TB | TB | 2 | `event-log.ts:540-548` fsync mỗi event non-terminal |
|
|
31
|
+
| **F5** cache symlink check theo dirname | Thấp | Thấp | 2 | `atomic-write.ts:323,394` gọi 2×/write, không cache |
|
|
32
|
+
| **F1** generation counter per-stateRoot | Thấp (chỉ multi-run) | Thấp | 2 | `state-store.ts:132,645` global bump |
|
|
33
|
+
| **F12** finalDrain kết thúc sớm khi stdout im lặng | TB (chỉ ca child treo) | TB (kill sớm) | 3 | `child-pi.ts:1145-1185`: timer là MAX, clear khi child tự exit |
|
|
34
|
+
| **F3b** mở rộng buffering event-log | Cao nếu chạy được | **Cao (deadlock)** | 3 | `414b973` đã revert vì deadlock |
|
|
35
|
+
| **F6** mailbox delivery append-only | Cao | Cao (refactor) | 3 | `mailbox.ts:399-411` full rewrite + fsync/message |
|
|
36
|
+
| **In-memory task state** | Cao (dài hạn) | Cao | 3 | Loại bỏ read-modify-write của F1/F2/F4 |
|
|
37
|
+
|
|
38
|
+
> **Rút lại so với bản nháp trước**: "giảm `finalDrainMs` 5000→1500" (blind) bị loại — timer là timeout an toàn, clear khi child thoát sạch; giảm cứng = rủi ro SIGTERM sớm. Thay bằng F12 (early-exit-on-silence). "Bỏ CAS trong F2" bị loại — CAS bảo vệ writer best-effort không cầm lock (`async-notifier.ts:54`, `crash-recovery.ts:98/416/464`); chỉ gộp 3 stat thừa.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Phase 0 — Baseline đo lường (bench-first)
|
|
43
|
+
|
|
44
|
+
**Mục tiêu**: có số liệu trước/sau cho các item nghi vấn, tránh tối ưu nhầm chỗ.
|
|
45
|
+
|
|
46
|
+
### 0.1 Bench mới cần thêm (`test/bench/`)
|
|
47
|
+
|
|
48
|
+
Theo pattern hiện có (mỗi file in đúng 1 dòng JSON `{ name, ... }` trên stdout; đọc `BENCH_ITERS`):
|
|
49
|
+
|
|
50
|
+
1. **`discover-workflows.bench.ts`** — đo `discoverWorkflows(cwd)` lặp N lần trong 1 project có ≥8 builtin workflow.
|
|
51
|
+
- Kịch bản A: gọi liên tiếp (đo cost thô hiện tại).
|
|
52
|
+
- Kịch bản B: sau khi wire cache (Phase 1) — kỳ vọng p50 sụt >10×.
|
|
53
|
+
2. **`persist-single-task-update.bench.ts`** — dựng manifest + tasks.json giả (20–50 task), gọi `persistSingleTaskUpdate` N lần; đếm wall-time p50/p95. Dùng để nghiệm thu F2 (gộp stat) và F4 (coalesce đã có).
|
|
54
|
+
3. **`config-load.bench.ts`** *(nếu chưa có)* — `loadConfig(cwd)` N lần, cache hit vs cold (đã fix F16, dùng làm regression guard).
|
|
55
|
+
|
|
56
|
+
`atomic-write.bench.ts` và `event-append.bench.ts` **đã tồn tại** → mở rộng thêm biến thể `durability: best-effort` (F4) và `terminal vs non-terminal fsync` (F3a).
|
|
57
|
+
|
|
58
|
+
### 0.2 Quy trình đo
|
|
59
|
+
```bash
|
|
60
|
+
# Baseline (trước mọi thay đổi) — chạy trên Windows VÀ Linux
|
|
61
|
+
BENCH_ITERS=500 npm run bench
|
|
62
|
+
copy test\bench\results.json test\bench\baseline-2026-07-pre.json # Windows
|
|
63
|
+
# Sau mỗi Phase:
|
|
64
|
+
npm run bench ; npm run bench:check # so với baseline
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 0.3 Tiêu chí "đáng làm"
|
|
68
|
+
Một item chỉ tiếp tục nếu bench cho thấy **p50 hoặc p95 giảm ≥15%** trên Windows cho hot path liên quan, HOẶC nó chặn một class lỗi (memory leak F9). Nếu không đạt → hạ ưu tiên/hoãn.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Phase 1 — High-confidence, low-risk wins
|
|
73
|
+
|
|
74
|
+
### F17 — Cache/resolve `discoverWorkflows` (win lớn nhất, rủi ro ~0)
|
|
75
|
+
|
|
76
|
+
**Vấn đề (verified)**: `src/ui/powerbar-publisher.ts:284` `buildStepsPayload` gọi `allWorkflows(discoverWorkflows(run.cwd))` mỗi lần render. Powerbar chạy qua `powerbarCoalescer` 200ms (`:342`) → tới **5 Hz** khi run active + có event. `discoverWorkflows` (`src/workflows/discover-workflows.ts:191`) **không cache**: mỗi call = `readWorkflowDir` × 3 root, mỗi root `readdirSync` **2 lần** (static `.workflow.md` + dynamic `.dwf.ts`) + `readFileSync` + regex-parse toàn bộ mỗi file `.workflow.md`.
|
|
77
|
+
|
|
78
|
+
**Fix (2 lớp, làm cả hai)**:
|
|
79
|
+
|
|
80
|
+
**(a) TTL cache trong `discover-workflows.ts`** — mirror `discover-agents.ts:493-556`:
|
|
81
|
+
```ts
|
|
82
|
+
// discover-workflows.ts
|
|
83
|
+
const WORKFLOW_DISCOVERY_TTL_MS = 5000;
|
|
84
|
+
const WORKFLOW_DISCOVERY_MAX_ENTRIES = 32;
|
|
85
|
+
interface CachedWorkflowEntry { result: WorkflowDiscoveryResult; expiresAt: number; dirStamp: string; }
|
|
86
|
+
const workflowCache = new Map<string, CachedWorkflowEntry>();
|
|
87
|
+
|
|
88
|
+
// stamp = mtime của 3 dir gốc; nếu dir đổi → invalidate sớm (rẻ hơn scan)
|
|
89
|
+
function dirStamp(cwd: string): string {
|
|
90
|
+
const dirs = [
|
|
91
|
+
path.join(packageRoot(), "workflows"),
|
|
92
|
+
path.join(userPiRoot(), "workflows"),
|
|
93
|
+
path.join(projectCrewRoot(cwd), "workflows"),
|
|
94
|
+
];
|
|
95
|
+
return dirs.map((d) => { try { return `${fs.statSync(d).mtimeMs}`; } catch { return "0"; } }).join("|");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function invalidateWorkflowDiscoveryCache(cwd?: string): void {
|
|
99
|
+
if (cwd) workflowCache.delete(cwd); else workflowCache.clear();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function discoverWorkflows(cwd: string): WorkflowDiscoveryResult {
|
|
103
|
+
if (!cwd || typeof cwd !== "string") return { builtin: [], user: [], project: [] };
|
|
104
|
+
const now = Date.now();
|
|
105
|
+
const stamp = dirStamp(cwd);
|
|
106
|
+
const cached = workflowCache.get(cwd);
|
|
107
|
+
if (cached && cached.expiresAt > now && cached.dirStamp === stamp) return cached.result;
|
|
108
|
+
const result = { /* ...readWorkflowDir × 3 như cũ... */ };
|
|
109
|
+
workflowCache.set(cwd, { result, expiresAt: now + WORKFLOW_DISCOVERY_TTL_MS, dirStamp: stamp });
|
|
110
|
+
while (workflowCache.size > WORKFLOW_DISCOVERY_MAX_ENTRIES) {
|
|
111
|
+
const oldest = workflowCache.keys().next().value; if (oldest) workflowCache.delete(oldest);
|
|
112
|
+
}
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
> `dirStamp` dùng 3 `statSync` (rẻ) thay cho ~6 `readdirSync` + N `readFileSync` + regex khi cache còn hạn.
|
|
117
|
+
|
|
118
|
+
**(b) Resolve-once trong powerbar** (bổ trợ, vì `run.workflow` bất biến trong 1 run): cache theo `run.runId → WorkflowConfig` trong module powerbar, xóa khi run vào terminal. Kể cả khi (a) đã đủ, lớp này bỏ luôn lookup `.find()` mỗi render.
|
|
119
|
+
|
|
120
|
+
**Files**: `src/workflows/discover-workflows.ts`, `src/ui/powerbar-publisher.ts`.
|
|
121
|
+
**Invalidation**: gọi `invalidateWorkflowDiscoveryCache()` tại các điểm create/update/delete workflow trong `src/extension/management.ts`.
|
|
122
|
+
**Tests**: `test/unit/discovery.test.ts` (đã có, count 9) + case mới: cache hit trả cùng ref; sửa file → `dirStamp` đổi → refetch; TTL hết → refetch.
|
|
123
|
+
**Bench**: `discover-workflows.bench.ts` p50 trước/sau (kỳ vọng >10×).
|
|
124
|
+
**Rollback**: `WORKFLOW_DISCOVERY_TTL_MS = 0` → hành vi như cũ.
|
|
125
|
+
**Acceptance**: powerbar không còn `readdirSync` workflow ở mỗi render khi run active (xác nhận qua bench + strace/Process Monitor tùy chọn); `discovery.test.ts` xanh.
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
### F15 — Nâng TTL agent + cache teams (đồng gốc F17)
|
|
130
|
+
|
|
131
|
+
**Vấn đề (verified)**: `src/agents/discover-agents.ts:493` `DISCOVERY_CACHE_TTL_MS = 500` → scheduler/recommend re-scan ~2×/s ở steady state. `discoverTeams` (`src/teams/discover-teams.ts`) không có cache.
|
|
132
|
+
|
|
133
|
+
**Fix**:
|
|
134
|
+
1. Nâng `DISCOVERY_CACHE_TTL_MS` 500 → **5000**, và bổ sung `dirStamp` (như F17) để không mất tính đúng khi user sửa agent giữa session (invalidate theo mtime dir thay vì chỉ TTL ngắn).
|
|
135
|
+
2. Thêm TTL cache + `dirStamp` cho `discoverTeams` (copy nguyên pattern F17).
|
|
136
|
+
3. Cân nhắc gom 3 discovery (agents/teams/workflows) vào 1 helper chung `src/utils/discovery-cache.ts<T>` để tránh lặp code (tùy chọn, không bắt buộc cho win).
|
|
137
|
+
|
|
138
|
+
**Files**: `src/agents/discover-agents.ts`, `src/teams/discover-teams.ts`, (tùy chọn) `src/utils/discovery-cache.ts`.
|
|
139
|
+
**Tests**: `discovery.test.ts` + case sửa file agent/team giữa TTL → cache invalidate qua dirStamp.
|
|
140
|
+
**Rủi ro**: TTL dài hơn → user sửa agent thấy hiệu lực chậm tối đa TTL nếu chỉ đổi nội dung file (mtime file đổi nhưng dir mtime KHÔNG luôn đổi trên mọi FS). → **Bắt buộc** invalidate rõ ràng ở management create/update/delete + `agents.reload` (đã có `invalidateAgentDiscoveryCache`).
|
|
141
|
+
**Rollback**: TTL về 500.
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
### F4 — Tham số `durability` cho write informational
|
|
146
|
+
|
|
147
|
+
**Vấn đề (verified)**: `src/state/atomic-write.ts:322` `atomicWriteFile` fsync data (`:384`) + parent dir (`:409-411`) **vô điều kiện**. Đắt trên Windows. Nhiều write là informational (mất ≤50ms cuối khi crash chấp nhận được vì đã có crash-recovery).
|
|
148
|
+
|
|
149
|
+
**Fix**: thêm options, mặc định giữ `full` (không đổi hành vi hiện tại):
|
|
150
|
+
```ts
|
|
151
|
+
export type WriteDurability = "full" | "best-effort";
|
|
152
|
+
export function atomicWriteFile(
|
|
153
|
+
filePath: string, content: string,
|
|
154
|
+
opts?: { expectedHash?: string; durability?: WriteDurability },
|
|
155
|
+
): void {
|
|
156
|
+
const durability = opts?.durability ?? "full";
|
|
157
|
+
// ...write temp...
|
|
158
|
+
if (durability === "full") { fs.fsyncSync(fd); } // :384
|
|
159
|
+
fs.closeSync(fd);
|
|
160
|
+
// rename...
|
|
161
|
+
if (durability === "full") { /* fsync parent dir :409-411 */ }
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
> Giữ chữ ký cũ `atomicWriteFile(path, content, expectedHash?)` tương thích ngược: nhận cả `string` (expectedHash) lẫn object. `atomicWriteJson`/`atomicWriteJsonCoalesced` thêm passthrough `durability`.
|
|
165
|
+
|
|
166
|
+
**Callers chuyển sang `best-effort`** (chỉ nơi mất 1 write cuối khi crash là an toàn, recovery tự sửa):
|
|
167
|
+
- `src/state/mailbox.ts:411` `writeDeliveryState` cho message **informational** (giữ `full` cho reply/terminal) — liên quan F6.
|
|
168
|
+
- `src/runtime/crew-agent-records.ts` — agent **progress/status** không-terminal (giữ `full` cho completed/failed/cancelled).
|
|
169
|
+
- **Xác minh trước khi đụng**: `persistSequence` (`event-log.ts:299`) — kiểm tra cơ chế ghi `.seq`; nếu qua `atomicWriteFile`, cho `best-effort` (sidecar tụt hậu được recovery-scan sửa). Nếu ghi kiểu khác thì bỏ qua ở item này (thuộc F3a).
|
|
170
|
+
|
|
171
|
+
**KHÔNG đổi (giữ `full`)**: manifest final, tasks.json terminal write, mọi terminal event.
|
|
172
|
+
**Tests**: bổ sung `atomic-write.bench.ts` biến thể best-effort; unit test đảm bảo `best-effort` vẫn tạo file atomic (rename) và không throw khi FS không hỗ trợ dir fsync.
|
|
173
|
+
**Rủi ro**: mất tối đa 1 write informational cuối khi hard-crash/power-loss — chấp nhận được (crash-recovery + event-reconstructor bù). **Không** áp cho terminal/manifest.
|
|
174
|
+
**Rollback**: đổi caller về `durability: "full"` hoặc bỏ options.
|
|
175
|
+
**Lưu ý phạm vi**: `saveRunTasksCoalesced` đã amortize fsync tasks.json (cửa sổ 50ms), nên win F4 giờ tập trung ở **mailbox + agent status + sidecar**, không phải "mọi write".
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
### F9 — Ring buffer cho `rawTextEvents` / `intermediateFindings`
|
|
180
|
+
|
|
181
|
+
**Vấn đề (verified)**: `src/runtime/child-pi.ts:577` `rawTextEvents: string[] = []`, push tại `:636` **không cap** ("RAW (uncapped)"); consumer chỉ dùng entry cuối (`getRawFinalText()` `:608`). `intermediateFindings` (`:583`) push-only, chỉ trim khi đọc (`slice(-MAX_INTERMEDIATE_DIGEST_LINES)` `:620`). Run dài/verbose × N worker song song → memory tăng tuyến tính.
|
|
182
|
+
|
|
183
|
+
**Fix**: cap ngay khi push (giữ N entry cuối).
|
|
184
|
+
```ts
|
|
185
|
+
private static readonly MAX_RAW_EVENTS = 8; // getRawFinalText chỉ cần entry cuối
|
|
186
|
+
private static readonly MAX_FINDINGS = 64; // đọc slice(-MAX_INTERMEDIATE_DIGEST_LINES)
|
|
187
|
+
|
|
188
|
+
private pushRaw(items: string[]): void {
|
|
189
|
+
this.rawTextEvents.push(...items);
|
|
190
|
+
const over = this.rawTextEvents.length - ChildPiLineObserver.MAX_RAW_EVENTS;
|
|
191
|
+
if (over > 0) this.rawTextEvents.splice(0, over);
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
Áp tương tự cho `intermediateFindings` (giữ ≥ `MAX_INTERMEDIATE_DIGEST_LINES` để không đổi output digest).
|
|
195
|
+
|
|
196
|
+
**Files**: `src/runtime/child-pi.ts`.
|
|
197
|
+
**Tests**: `test/unit/child-pi-*.test.ts` — push > cap vẫn trả đúng `getRawFinalText()` (entry cuối) và `getIntermediateFindings()` (tail không đổi).
|
|
198
|
+
**Rủi ro**: nếu có consumer nào đọc `rawTextEvents` không phải entry cuối (grep xác nhận không có) → an toàn.
|
|
199
|
+
**Bench**: không cần bench tốc độ; chứng minh bằng test bound length. Tùy chọn: đo RSS trước/sau trên run giả 10k fragment.
|
|
200
|
+
**Rollback**: nâng cap rất lớn.
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## Phase 2 — Correctness-sensitive, measured wins
|
|
205
|
+
|
|
206
|
+
### F2 — Gộp 3 `statSync` thừa trong `persistSingleTaskUpdate`
|
|
207
|
+
|
|
208
|
+
**Vấn đề (verified)**: `src/runtime/task-runner/state-helpers.ts:76-113`, trong mỗi attempt có **3 `fs.statSync` liên tiếp** (`currentMtime` :76, `recheckMtime` :92, `preWriteMtime` :107) mà **giữa chúng không có I/O/await nào** (code sync) → luôn trả cùng mtime. 2 trong 3 là rác. Gọi ~5×/task qua `checkpointTask`.
|
|
209
|
+
|
|
210
|
+
> **KHÔNG bỏ CAS**: `saveRunTasks` không tự lock; các writer best-effort (`async-notifier.ts:54`, `crash-recovery.ts:98/416/464`) ghi tasks.json **không cầm run.lock**. CAS mtime là lớp bảo vệ chống chúng. Chỉ loại bỏ stat lặp thừa.
|
|
211
|
+
|
|
212
|
+
**Fix**: 1 `statSync` sau khi merge, ngay trước `saveRunTasksCoalesced`, so với `baseMtime`:
|
|
213
|
+
```ts
|
|
214
|
+
return withRunLockSync(manifest, () => {
|
|
215
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
216
|
+
flushPendingAtomicWrites();
|
|
217
|
+
const latest = loadRunManifestById(manifest.cwd, manifest.runId)?.tasks ?? fallbackTasks;
|
|
218
|
+
merged = updateTask(latest, taskWithCheckpoint);
|
|
219
|
+
let currentMtime = 0;
|
|
220
|
+
try { currentMtime = fs.statSync(manifest.tasksPath).mtimeMs; } catch { currentMtime = 0; }
|
|
221
|
+
if (currentMtime !== baseMtime) { baseMtime = currentMtime; continue; } // 1 stat/attempt
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
if (merged === undefined) throw new Error("persistSingleTaskUpdate: failed to converge");
|
|
225
|
+
saveRunTasksCoalesced(manifest, merged);
|
|
226
|
+
return merged;
|
|
227
|
+
});
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Cân nhắc bổ sung (đo rồi mới quyết)**: `flushPendingAtomicWrites()` ở đầu mỗi attempt **triệt tiêu coalescing giữa các task** (mọi persist đều force-flush). Nếu bench cho thấy đây là chi phí lớn, xét: chỉ flush khi phát hiện mtime đã đổi (đọc lần đầu không flush; nếu miss CAS thì flush + retry). Đây là thay đổi tinh vi → chỉ làm nếu bench chứng minh, kèm integration test race.
|
|
231
|
+
|
|
232
|
+
**Files**: `src/runtime/task-runner/state-helpers.ts`.
|
|
233
|
+
**Tests**: **bắt buộc** giữ `test/unit/*persist*`/race tests xanh (2 task hoàn tất song song không clobber nhau); thêm case: unlocked writer thay đổi tasks.json giữa attempt → CAS bắt được và re-merge.
|
|
234
|
+
**Bench**: `persist-single-task-update.bench.ts` p50 trước/sau.
|
|
235
|
+
**Rủi ro**: thấp nếu chỉ gộp stat; **trung bình** nếu đụng `flushPendingAtomicWrites` (có thể mở lại stale-read window → cần race test).
|
|
236
|
+
**Rollback**: revert về 3-stat.
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
### F3a — fsync chỉ cho terminal events (tách khỏi buffering)
|
|
241
|
+
|
|
242
|
+
**Vấn đề (verified)**: `src/state/event-log.ts` — `appendEventAsync` (:540-548) và sync path (:818-832) fsync + `persistSequence` **mỗi event**, kể cả non-terminal. `appendEventBuffered` cho `task.progress` đã batch, nhưng phần lớn event khác vẫn per-fsync.
|
|
243
|
+
|
|
244
|
+
**Fix**: fsync có điều kiện — chỉ khi `TERMINAL_EVENT_TYPES.has(type)` (hoặc có `fingerprint`). Non-terminal: append + persistSequence, KHÔNG fsync.
|
|
245
|
+
```ts
|
|
246
|
+
const isTerminal = TERMINAL_EVENT_TYPES.has(fullEvent.type);
|
|
247
|
+
await fs.promises.appendFile(eventsPath, line, { encoding: "utf-8", flag: "a" });
|
|
248
|
+
if (isTerminal) {
|
|
249
|
+
const fd = await fs.promises.open(eventsPath, "r+");
|
|
250
|
+
try { await fd.sync(); } finally { await fd.close(); }
|
|
251
|
+
}
|
|
252
|
+
persistSequence(eventsPath, seq); // sidecar: nếu tụt hậu, recovery-scan tự sửa
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
**Cơ sở an toàn**: fsync ở đây đóng crash-window append↔persistSequence (chống seq reuse). Với non-terminal: nếu crash mất cả dòng append lẫn seq → nhất quán (recovery scan `event-reconstructor.ts` xử lý dòng cuối lỗi/thiếu). Chỉ mất event informational cuối — chấp nhận được. Terminal events (run/task completed/failed…) vẫn durable tuyệt đối.
|
|
256
|
+
|
|
257
|
+
**Files**: `src/state/event-log.ts` (cả `appendEvent` sync và `appendEventAsync`).
|
|
258
|
+
**Tests**: `event-log-*.test.ts` — terminal event vẫn fsync (mock `fsyncSync`/`fd.sync` đếm lời gọi: chỉ gọi cho terminal); crash-recovery test đọc lại log sau khi mất dòng non-terminal cuối vẫn reconstruct đúng trạng thái terminal.
|
|
259
|
+
**Bench**: `event-append.bench.ts` — thêm scenario terminal vs non-terminal; kỳ vọng non-terminal p50 giảm mạnh trên Windows.
|
|
260
|
+
**Rủi ro**: TB — thay đổi durability. Chạy đủ integration + crash-recovery suite.
|
|
261
|
+
**Rollback**: đổi điều kiện thành `true` (fsync mọi event).
|
|
262
|
+
|
|
263
|
+
---
|
|
264
|
+
|
|
265
|
+
### F5 — Cache kết quả `isSymlinkSafePath` theo dirname
|
|
266
|
+
|
|
267
|
+
**Vấn đề (verified)**: `src/state/atomic-write.ts:43` `isSymlinkSafePath` walk toàn ancestor chain (lstat mỗi cấp tới root); gọi **2×/write** (:323 initial, :394 retry). Thư mục cha của state root không đổi trong suốt run.
|
|
268
|
+
|
|
269
|
+
**Fix**: cache theo `path.dirname(filePath)` trong process, TTL ngắn (vd 30s) hoặc bounded LRU. Chỉ re-validate khi ghi vào dirname mới:
|
|
270
|
+
```ts
|
|
271
|
+
const symlinkSafeCache = new Map<string, { safe: boolean; at: number }>();
|
|
272
|
+
const SYMLINK_CACHE_TTL_MS = 30_000;
|
|
273
|
+
function isDirTreeSafeCached(filePath: string): boolean {
|
|
274
|
+
const dir = path.dirname(filePath);
|
|
275
|
+
const hit = symlinkSafeCache.get(dir);
|
|
276
|
+
if (hit && Date.now() - hit.at < SYMLINK_CACHE_TTL_MS) return hit.safe;
|
|
277
|
+
const safe = isSymlinkSafePath(filePath); // vẫn validate cả filePath (file có thể là symlink mới)
|
|
278
|
+
symlinkSafeCache.set(dir, { safe, at: Date.now() });
|
|
279
|
+
return safe;
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
> Lưu ý: cache theo **dir** (ancestor chain), nhưng `filePath` cuối (chính file đích) vẫn phải lstat mỗi lần vì file có thể bị thay bằng symlink giữa các write. Fix chỉ bỏ phần walk ancestor lặp lại, không bỏ check file đích. → refactor `isSymlinkSafePath` tách "check ancestor dirs" (cache-able) khỏi "check target" (luôn chạy).
|
|
283
|
+
|
|
284
|
+
**Files**: `src/state/atomic-write.ts`.
|
|
285
|
+
**Tests**: giữ security tests symlink hiện có xanh; thêm case: sau khi cache dir an toàn, đổi 1 ancestor thành symlink → trong TTL vẫn có thể miss (chấp nhận, TTL ngắn) — cân nhắc invalidate khi rename/create dir.
|
|
286
|
+
**Rủi ro**: **security-sensitive**. TTL ngắn + vẫn check target mỗi lần. Cần review bởi security-auditor droid.
|
|
287
|
+
**Rollback**: TTL = 0.
|
|
288
|
+
|
|
289
|
+
---
|
|
290
|
+
|
|
291
|
+
### F1 — Generation counter per-stateRoot (win nhỏ, chỉ multi-run)
|
|
292
|
+
|
|
293
|
+
**Vấn đề (verified)**: `src/state/state-store.ts:75` `manifestCacheGeneration` global; `invalidateRunCache` (:130-132) vừa `delete(stateRoot)` vừa `generation++`. Cache hit yêu cầu `cached.generation === manifestCacheGeneration` (:645,:761). → write của run A làm miss cache của run B.
|
|
294
|
+
|
|
295
|
+
> **Kỳ vọng thực tế**: với 1 run active, cache của chính run đó đã bị invalidate bởi mtime/size đổi mỗi lần nó tự ghi; generation global chỉ gây false-miss THÊM cho **run khác**. Win chỉ hiện khi có **nhiều run đồng thời** đọc manifest của nhau (status poll, reconcile). Không kỳ vọng win ở single-run.
|
|
296
|
+
|
|
297
|
+
**Fix**: `Map<stateRoot, number>` thay global; bump chỉ generation của stateRoot bị invalidate. Giữ generation (đừng bỏ hẳn) vì nó phòng ca **mtime granularity thô** (FS phân giải 1–2s + size trùng).
|
|
298
|
+
```ts
|
|
299
|
+
const genByRoot = new Map<string, number>();
|
|
300
|
+
function genOf(root: string): number { return genByRoot.get(root) ?? 0; }
|
|
301
|
+
function invalidateRunCache(stateRoot: string): void {
|
|
302
|
+
manifestCache.delete(stateRoot);
|
|
303
|
+
genByRoot.set(stateRoot, genOf(stateRoot) + 1);
|
|
304
|
+
}
|
|
305
|
+
// hit check: cached.generation === genOf(stateRoot)
|
|
306
|
+
// setManifestCache: entry.generation = genOf(stateRoot)
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
**Files**: `src/state/state-store.ts`.
|
|
310
|
+
**Tests**: `test/unit/state-store*.test.ts` — write run A không làm miss cache run B; write run A vẫn làm miss cache run A.
|
|
311
|
+
**Bench**: `snapshot-cache.bench.ts` / thêm scenario 2-run: hit-rate trước/sau.
|
|
312
|
+
**Rủi ro**: thấp. **Chỉ làm nếu** bench multi-run chứng minh win (nếu không, để nguyên — tránh thêm bề mặt bug cho win ~0).
|
|
313
|
+
**Rollback**: về global counter.
|
|
314
|
+
|
|
315
|
+
---
|
|
316
|
+
|
|
317
|
+
## Phase 3 — Deferred / high-risk / big refactor
|
|
318
|
+
|
|
319
|
+
### F12 — finalDrain kết thúc sớm khi stdout im lặng (KHÔNG giảm cứng)
|
|
320
|
+
|
|
321
|
+
**Vấn đề (verified)**: `src/runtime/child-pi.ts:1145-1185` — sau final assistant event, arm `finalDrainTimer(finalDrainMs=5000)`; **clear ngay khi `childExited`/`settled`**. Vậy 5s chỉ tốn khi child **treo** sau final message. Giảm cứng `finalDrainMs` = rủi ro SIGTERM child đang flush.
|
|
322
|
+
|
|
323
|
+
**Fix**: thêm "silence early-exit" — theo dõi timestamp dòng stdout cuối; nếu sau final assistant event mà stdout im lặng > `finalDrainQuietMs` (vd 800ms) VÀ đã nhận `message_end`/stopReason=stop, thì kết thúc drain sớm (SIGTERM) thay vì chờ đủ 5s. Giữ `finalDrainMs=5000` làm trần tuyệt đối.
|
|
324
|
+
```ts
|
|
325
|
+
// khi arm finalDrainTimer, đồng thời set 1 interval nhẹ (200ms, unref) kiểm tra:
|
|
326
|
+
// now - lastStdoutMonotonicMs > finalDrainQuietMs && sawMessageEndStop → drain sớm
|
|
327
|
+
```
|
|
328
|
+
> Chỉ cải thiện đúng ca child-treo-nhưng-đã-xong; không đụng ca child thoát sạch (vốn đã ~0 cost).
|
|
329
|
+
|
|
330
|
+
**Files**: `src/config/defaults.ts` (thêm `finalDrainQuietMs`), `src/runtime/child-pi.ts`.
|
|
331
|
+
**Rủi ro**: TB — nếu phát hiện "xong" sai (child còn tool trailing) → cắt sớm. Cần điều kiện chặt (`message_end` + stopReason=stop + im lặng đủ lâu).
|
|
332
|
+
**Bench/nghiệm thu**: cần đo trên workflow thật (child-process mode) — **out-of-scope cho micro-bench**; đo end-to-end `time` 1 run `fast-fix` trước/sau.
|
|
333
|
+
**Rollback**: `finalDrainQuietMs` = `finalDrainMs` (vô hiệu early-exit).
|
|
334
|
+
|
|
335
|
+
---
|
|
336
|
+
|
|
337
|
+
### F3b — Mở rộng buffering event-log (chờ RCA deadlock)
|
|
338
|
+
|
|
339
|
+
**Vấn đề**: mở rộng `appendEventBuffered` cho thêm event non-terminal sẽ giảm mạnh syscall, NHƯNG `414b973` đã **revert buffering `appendEventAsync` vì deadlock**.
|
|
340
|
+
|
|
341
|
+
**Điều kiện tiên quyết**: RCA deadlock (nghi: buffer flush timer + lock re-entrancy giữa `flushEventLogBuffer` và `withEventLogLockSync`; hoặc `beforeExit` drain tạo floating promise). Chỉ triển khai sau khi:
|
|
342
|
+
1. Có test tái hiện deadlock (`event-log-leak.test.ts` H1/H3 đang "cancelled under --test-force-exit" — điều tra trước).
|
|
343
|
+
2. Chứng minh no-lost-event khi kill process trong buffer window (integration crash test).
|
|
344
|
+
|
|
345
|
+
**Rủi ro**: Cao. **Không đụng** cho tới khi F3a đã ship (F3a cho phần lớn win mà không cần buffering).
|
|
346
|
+
|
|
347
|
+
---
|
|
348
|
+
|
|
349
|
+
### F6 — Mailbox delivery-state append-only + compaction
|
|
350
|
+
|
|
351
|
+
**Vấn đề (verified)**: `src/state/mailbox.ts:399-411` `writeDeliveryState` `atomicWriteFile` **toàn bộ** `delivery.json` pretty-printed mỗi message; nay kèm fsync data+dir (F4). Read path `updateMailboxMessageReply` quét mọi mailbox file (full read + full rewrite).
|
|
352
|
+
|
|
353
|
+
**Fix (refactor)**: chuyển delivery-state sang **append-only JSONL** (mỗi delivery/ack 1 dòng) + compaction định kỳ (giống events.jsonl). Read = tail + reconstruct; write = append 1 dòng (rẻ). Giữ `delivery.json` snapshot chỉ khi compact.
|
|
354
|
+
**Bước trung gian rẻ hơn (làm trước nếu chưa refactor)**: (a) áp F4 `best-effort` cho delivery write informational; (b) coalesce delivery write theo message-burst; (c) cache danh sách archive theo mtime dir (bỏ `readdirSync` mỗi đọc).
|
|
355
|
+
**Rủi ro**: Cao (đổi format state có consumer: `run-snapshot-cache.ts:484`, group-join). Cần migration + đọc-ngược tương thích.
|
|
356
|
+
**Phase**: sau khi Phase 1–2 ổn định.
|
|
357
|
+
|
|
358
|
+
---
|
|
359
|
+
|
|
360
|
+
### In-memory task state (write-through) — dài hạn
|
|
361
|
+
|
|
362
|
+
**Ý tưởng**: giữ task graph in-memory per active run là nguồn sự thật; disk chỉ là bản persist (coalesced/async). Loại bỏ hoàn toàn vòng read-modify-write của F1/F2/F4 cho run đang chạy.
|
|
363
|
+
**Rủi ro**: Cao (đụng mọi reader cross-process: status/cancel/reconcile phải đọc disk, còn run process dùng memory → cần cơ chế đồng bộ/invalidate rõ). Chỉ làm sau khi có in-memory reader thống nhất + integration test crash đầy đủ.
|
|
364
|
+
**Phase**: nghiên cứu riêng (ADR mới), không gộp vào đợt này.
|
|
365
|
+
|
|
366
|
+
---
|
|
367
|
+
|
|
368
|
+
## Thứ tự thực thi & phụ thuộc
|
|
369
|
+
|
|
370
|
+
```
|
|
371
|
+
Phase 0 (bench baseline) ──► Phase 1 ──► Phase 2 ──► Phase 3
|
|
372
|
+
bench mới F17, F15 F2, F3a F12
|
|
373
|
+
baseline Win+Linux F4, F9 F5, F1 F3b (sau RCA)
|
|
374
|
+
F6, in-memory
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
- **F17 trước F15** (F17 tạo pattern cache dùng lại cho F15).
|
|
378
|
+
- **F4 trước F6** (F6 dùng `best-effort` từ F4).
|
|
379
|
+
- **F3a trước F3b** (F3a lấy phần lớn win, F3b rủi ro cao chờ RCA).
|
|
380
|
+
- **F2 độc lập**, làm sớm trong Phase 2.
|
|
381
|
+
|
|
382
|
+
## Nghiệm thu tổng (mỗi PR)
|
|
383
|
+
```bash
|
|
384
|
+
npm run typecheck
|
|
385
|
+
npm run lint
|
|
386
|
+
npm test # unit + integration (bắt buộc cho item chạm state)
|
|
387
|
+
npm run check:lazy-imports
|
|
388
|
+
npm run bench ; npm run bench:check # so baseline; không regress
|
|
389
|
+
```
|
|
390
|
+
- Item chạm durability/state (F2, F3a, F4, F5, F1, F6): **bắt buộc** integration + crash-recovery suite xanh, không chỉ unit.
|
|
391
|
+
- Item security (F5): review bởi `security-auditor` droid trước merge.
|
|
392
|
+
|
|
393
|
+
## Ước lượng tác động (định tính, chờ bench xác nhận)
|
|
394
|
+
- **Phase 1**: bỏ scan discovery 5 Hz của powerbar (F17) — win rõ nhất, đo được ngay; giảm CPU nền; giảm fsync mailbox/agent (F4); chặn memory leak run dài (F9).
|
|
395
|
+
- **Phase 2**: giảm syscall trên đường ghi state/event trong run active (F2 gộp stat, F3a fsync-terminal-only); F1/F5 win nhỏ (chỉ làm nếu bench chứng minh).
|
|
396
|
+
- **Phase 3**: hết latency dư ca child-treo (F12); giảm mạnh IO mailbox (F6); nền tảng dài hạn (in-memory).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-crew",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.27",
|
|
4
4
|
"description": "Pi extension for coordinated AI teams, workflows, worktrees, and async task orchestration",
|
|
5
5
|
"author": "baphuongna",
|
|
6
6
|
"license": "MIT",
|
|
@@ -38,6 +38,11 @@
|
|
|
38
38
|
"workflows/",
|
|
39
39
|
"skills/**/SKILL.md",
|
|
40
40
|
"themes/",
|
|
41
|
+
"assets/crew-vibes.ttf",
|
|
42
|
+
"assets/runner-spritesheet.png",
|
|
43
|
+
"scripts/postinstall.mjs",
|
|
44
|
+
"scripts/install-crew-vibes-font.mjs",
|
|
45
|
+
"scripts/build-crew-vibes-font.py",
|
|
41
46
|
"README.md",
|
|
42
47
|
"AGENTS.md",
|
|
43
48
|
"docs/",
|
|
@@ -58,14 +63,16 @@
|
|
|
58
63
|
"lint": "biome check --linter-enabled=true --formatter-enabled=false --max-diagnostics=50 --diagnostic-level=error .",
|
|
59
64
|
"format:check": "biome format .",
|
|
60
65
|
"test": "npm run test:unit && npm run test:integration",
|
|
61
|
-
"test:unit": "node scripts/test-runner.mjs --test-concurrency=4 --test-timeout=
|
|
66
|
+
"test:unit": "node scripts/test-runner.mjs --test-concurrency=4 --test-timeout=180000 --test-force-exit test/unit/*.test.ts",
|
|
62
67
|
"test:watch": "tsx --watch --test --test-concurrency=4 --test-timeout=30000 --test-force-exit test/unit/*.test.ts",
|
|
63
68
|
"test:integration": "node scripts/test-runner.mjs --test-concurrency=1 --test-timeout=300000 test/integration/*.test.ts",
|
|
64
69
|
"test:smoke": "node scripts/test-runner.mjs --test-concurrency=1 --test-timeout=180000 test/smoke/*.smoke.ts",
|
|
65
70
|
"build:bundle": "node scripts/build-bundle.mjs",
|
|
66
71
|
"watch:bundle": "node scripts/watch-bundle.mjs",
|
|
67
72
|
"build:bundle:once": "node scripts/watch-bundle.mjs --once",
|
|
68
|
-
"postinstall": "node scripts/
|
|
73
|
+
"postinstall": "node scripts/postinstall.mjs",
|
|
74
|
+
"install:crew-font": "node scripts/install-crew-vibes-font.mjs",
|
|
75
|
+
"build:crew-font": "python scripts/build-crew-vibes-font.py",
|
|
69
76
|
"bench": "node scripts/run-bench.mjs",
|
|
70
77
|
"bench:check": "node scripts/bench-check.mjs",
|
|
71
78
|
"test:new": "tsx --test --test-concurrency=4 --test-timeout=30000 --test-force-exit test/unit/*.test.ts",
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Compare test/bench/results.json against test/bench/baseline.json.
|
|
4
|
+
*
|
|
5
|
+
* Fails if any p95 metric regresses by more than the allowed threshold.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* npm run bench:check # default 15% threshold
|
|
9
|
+
* THRESHOLD_PCT=10 npm run bench:check # tighter
|
|
10
|
+
* BASELINE=test/bench/baseline.json npm run bench:check
|
|
11
|
+
*/
|
|
12
|
+
import * as fs from "node:fs";
|
|
13
|
+
import * as path from "node:path";
|
|
14
|
+
|
|
15
|
+
const root = path.resolve(import.meta.dirname, "..");
|
|
16
|
+
const benchDir = path.join(root, "test", "bench");
|
|
17
|
+
const resultsPath = path.join(benchDir, "results.json");
|
|
18
|
+
const baselinePath = process.env.BASELINE ? path.resolve(process.env.BASELINE) : path.join(benchDir, "baseline.json");
|
|
19
|
+
const threshold = Number(process.env.THRESHOLD_PCT ?? 15) / 100;
|
|
20
|
+
|
|
21
|
+
if (!fs.existsSync(resultsPath)) {
|
|
22
|
+
console.error(`[bench:check] missing ${resultsPath}; run \`npm run bench\` first.`);
|
|
23
|
+
process.exit(2);
|
|
24
|
+
}
|
|
25
|
+
if (!fs.existsSync(baselinePath)) {
|
|
26
|
+
console.error(`[bench:check] missing baseline ${baselinePath}.`);
|
|
27
|
+
console.error(" Capture baseline with: npm run bench && cp test/bench/results.json test/bench/baseline.json");
|
|
28
|
+
process.exit(2);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const results = JSON.parse(fs.readFileSync(resultsPath, "utf-8"));
|
|
32
|
+
const baseline = JSON.parse(fs.readFileSync(baselinePath, "utf-8"));
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Walk each bench's nested numeric metrics and pair with baseline.
|
|
36
|
+
* Reports any p95 metric where current > baseline * (1 + threshold).
|
|
37
|
+
*/
|
|
38
|
+
const regressions = [];
|
|
39
|
+
const improvements = [];
|
|
40
|
+
for (const [benchName, current] of Object.entries(results.results)) {
|
|
41
|
+
const base = baseline.results?.[benchName];
|
|
42
|
+
if (!base) {
|
|
43
|
+
console.log(`[bench:check] no baseline for ${benchName} — skipping`);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
for (const metric of metricKeys(current)) {
|
|
47
|
+
const cur = readPath(current, metric);
|
|
48
|
+
const ref = readPath(base, metric);
|
|
49
|
+
if (typeof cur !== "number" || typeof ref !== "number" || ref === 0) continue;
|
|
50
|
+
// Sub-ms metrics are dominated by GC / OS jitter — applying a strict
|
|
51
|
+
// percentage gate causes false positives. Use absolute delta cap instead.
|
|
52
|
+
if (ref < 1.0) {
|
|
53
|
+
const absDelta = cur - ref;
|
|
54
|
+
if (absDelta > 0.5) regressions.push({ bench: benchName, metric: metric.join("."), baseline: ref, current: cur, deltaPct: round(((cur - ref) / ref) * 100), reason: "abs > 0.5ms" });
|
|
55
|
+
else if (absDelta < -0.05) improvements.push({ bench: benchName, metric: metric.join("."), baseline: ref, current: cur, deltaPct: round(((cur - ref) / ref) * 100) });
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const delta = (cur - ref) / ref;
|
|
59
|
+
if (delta > threshold) regressions.push({ bench: benchName, metric: metric.join("."), baseline: ref, current: cur, deltaPct: round(delta * 100) });
|
|
60
|
+
else if (delta < -0.05) improvements.push({ bench: benchName, metric: metric.join("."), baseline: ref, current: cur, deltaPct: round(delta * 100) });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (improvements.length) {
|
|
65
|
+
console.log("[bench:check] improvements:");
|
|
66
|
+
for (const item of improvements) console.log(` ${item.bench}.${item.metric}: ${item.baseline} → ${item.current} (${item.deltaPct}%)`);
|
|
67
|
+
}
|
|
68
|
+
if (regressions.length) {
|
|
69
|
+
console.error(`[bench:check] regressions (>${(threshold * 100).toFixed(0)}%):`);
|
|
70
|
+
for (const item of regressions) console.error(` ${item.bench}.${item.metric}: ${item.baseline} → ${item.current} (+${item.deltaPct}%)`);
|
|
71
|
+
process.exit(1);
|
|
72
|
+
}
|
|
73
|
+
console.log(`[bench:check] all benches within ${(threshold * 100).toFixed(0)}% of baseline.`);
|
|
74
|
+
|
|
75
|
+
function metricKeys(obj, prefix = []) {
|
|
76
|
+
const skip = new Set(["name", "unit", "iters", "tasks", "events", "eventsPerIter"]);
|
|
77
|
+
const keys = [];
|
|
78
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
79
|
+
if (skip.has(k)) continue;
|
|
80
|
+
if (k === "p50" || k === "p95" || k === "p99" || k === "min" || k === "max") {
|
|
81
|
+
// We only gate on p95; min/max printed but not enforced.
|
|
82
|
+
if (k === "p95") keys.push([...prefix, k]);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (v && typeof v === "object" && !Array.isArray(v)) keys.push(...metricKeys(v, [...prefix, k]));
|
|
86
|
+
}
|
|
87
|
+
return keys;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function readPath(obj, parts) {
|
|
91
|
+
let cur = obj;
|
|
92
|
+
for (const p of parts) cur = cur?.[p];
|
|
93
|
+
return cur;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function round(n) { return Math.round(n * 100) / 100; }
|