@jive-sh/workflow-platform 0.7.0 → 1.1.0

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.
Files changed (195) hide show
  1. package/README.md +70 -435
  2. package/component/_generated/api.ts +72 -0
  3. package/component/_generated/component.ts +629 -0
  4. package/component/_generated/dataModel.ts +60 -0
  5. package/component/_generated/server.ts +169 -0
  6. package/component/convex.config.ts +3 -0
  7. package/component/engine.ts +756 -0
  8. package/component/errors.ts +66 -0
  9. package/component/events.ts +17 -0
  10. package/component/notes.ts +19 -0
  11. package/component/places.ts +136 -0
  12. package/component/retention.ts +205 -0
  13. package/component/runEngine.ts +25 -0
  14. package/component/schema.ts +135 -0
  15. package/component/steps.ts +188 -0
  16. package/component/store.ts +513 -0
  17. package/component/tasks.ts +290 -0
  18. package/component/worker.ts +109 -0
  19. package/component/workflows.ts +83 -0
  20. package/dist/definition/agent-runner.js +9 -0
  21. package/dist/definition/agent-runner.js.map +1 -0
  22. package/dist/definition/file-store.js +9 -0
  23. package/dist/definition/file-store.js.map +1 -0
  24. package/dist/definition/program-build.js +10 -0
  25. package/dist/definition/program-build.js.map +1 -0
  26. package/dist/definition/step.js +1 -0
  27. package/dist/definition/step.js.map +1 -0
  28. package/dist/definition/task-schema.js +5 -0
  29. package/dist/definition/task-schema.js.map +1 -0
  30. package/dist/definition/tasks.js +9 -0
  31. package/dist/definition/tasks.js.map +1 -0
  32. package/dist/definition/workflow.js +117 -0
  33. package/dist/definition/workflow.js.map +1 -0
  34. package/dist/graph.js +310 -9
  35. package/dist/graph.js.map +1 -1
  36. package/dist/index.js +7 -196
  37. package/dist/index.js.map +1 -1
  38. package/package.json +9 -4
  39. package/src/definition/agent-runner.ts +59 -0
  40. package/src/definition/file-store.ts +20 -0
  41. package/src/definition/program-build.ts +30 -0
  42. package/src/definition/step.ts +106 -0
  43. package/src/definition/task-schema.ts +15 -0
  44. package/src/definition/tasks.ts +43 -0
  45. package/src/definition/workflow.ts +262 -0
  46. package/src/graph.ts +352 -19
  47. package/src/index.ts +8 -238
  48. package/worker/directory-file-store.ts +42 -0
  49. package/worker/index.ts +12 -0
  50. package/worker/platform-client.ts +144 -0
  51. package/worker/step-meter.ts +80 -0
  52. package/worker/worker-tasks.ts +27 -0
  53. package/worker/worker.test.ts +200 -0
  54. package/worker/worker.ts +240 -0
  55. package/dist/budget-states.js +0 -30
  56. package/dist/budget-states.js.map +0 -1
  57. package/dist/cpu-limit/limiter.js +0 -839
  58. package/dist/cpu-limit/limiter.js.map +0 -1
  59. package/dist/cpu-limit/use.js +0 -139
  60. package/dist/cpu-limit/use.js.map +0 -1
  61. package/dist/dashboard/agent-usage.js +0 -25
  62. package/dist/dashboard/agent-usage.js.map +0 -1
  63. package/dist/dashboard/dashboard.css +0 -148
  64. package/dist/dashboard/drilldown.js +0 -47
  65. package/dist/dashboard/drilldown.js.map +0 -1
  66. package/dist/dashboard/queue-lines.js +0 -44
  67. package/dist/dashboard/queue-lines.js.map +0 -1
  68. package/dist/dashboard/queue-table.js +0 -16
  69. package/dist/dashboard/queue-table.js.map +0 -1
  70. package/dist/dashboard/run-doing-words.js +0 -29
  71. package/dist/dashboard/run-doing-words.js.map +0 -1
  72. package/dist/dashboard/setting-words.js +0 -18
  73. package/dist/dashboard/setting-words.js.map +0 -1
  74. package/dist/dashboard/spending-words.js +0 -24
  75. package/dist/dashboard/spending-words.js.map +0 -1
  76. package/dist/failure.js +0 -35
  77. package/dist/failure.js.map +0 -1
  78. package/dist/keep-running.js +0 -79
  79. package/dist/keep-running.js.map +0 -1
  80. package/dist/outside-failure.js +0 -31
  81. package/dist/outside-failure.js.map +0 -1
  82. package/dist/pick-wakes.js +0 -125
  83. package/dist/pick-wakes.js.map +0 -1
  84. package/dist/project.js +0 -1
  85. package/dist/project.js.map +0 -1
  86. package/dist/queue-counts.js +0 -51
  87. package/dist/queue-counts.js.map +0 -1
  88. package/dist/reasons.js +0 -33
  89. package/dist/reasons.js.map +0 -1
  90. package/dist/retention.js +0 -59
  91. package/dist/retention.js.map +0 -1
  92. package/dist/settings.js +0 -88
  93. package/dist/settings.js.map +0 -1
  94. package/dist/spending-limit.js +0 -82
  95. package/dist/spending-limit.js.map +0 -1
  96. package/dist/step-files.js +0 -200
  97. package/dist/step-files.js.map +0 -1
  98. package/dist/step-meter.js +0 -97
  99. package/dist/step-meter.js.map +0 -1
  100. package/dist/step-times.js +0 -114
  101. package/dist/step-times.js.map +0 -1
  102. package/dist/step-usage.js +0 -19
  103. package/dist/step-usage.js.map +0 -1
  104. package/dist/steps.js +0 -1205
  105. package/dist/steps.js.map +0 -1
  106. package/dist/storage/agent-claims.js +0 -3
  107. package/dist/storage/agent-claims.js.map +0 -1
  108. package/dist/storage/budgets.js +0 -121
  109. package/dist/storage/budgets.js.map +0 -1
  110. package/dist/storage/engine-records.js +0 -91
  111. package/dist/storage/engine-records.js.map +0 -1
  112. package/dist/storage/engine-storage.js +0 -67
  113. package/dist/storage/engine-storage.js.map +0 -1
  114. package/dist/storage/input-records.js +0 -12
  115. package/dist/storage/input-records.js.map +0 -1
  116. package/dist/storage/move-store.js +0 -251
  117. package/dist/storage/move-store.js.map +0 -1
  118. package/dist/storage/sqlite-store.js +0 -901
  119. package/dist/storage/sqlite-store.js.map +0 -1
  120. package/dist/storage/step-records.js +0 -11
  121. package/dist/storage/step-records.js.map +0 -1
  122. package/dist/storage/storage-error.js +0 -19
  123. package/dist/storage/storage-error.js.map +0 -1
  124. package/dist/storage/task-store.js +0 -30
  125. package/dist/storage/task-store.js.map +0 -1
  126. package/dist/system-workflows.js +0 -54
  127. package/dist/system-workflows.js.map +0 -1
  128. package/dist/tasks.js +0 -500
  129. package/dist/tasks.js.map +0 -1
  130. package/dist/views/format.js +0 -37
  131. package/dist/views/format.js.map +0 -1
  132. package/dist/views/runs-now.js +0 -117
  133. package/dist/views/runs-now.js.map +0 -1
  134. package/dist/views/step-funnel.js +0 -98
  135. package/dist/views/step-funnel.js.map +0 -1
  136. package/dist/views/step-graph.js +0 -39
  137. package/dist/views/step-graph.js.map +0 -1
  138. package/dist/views/workflows-view.js +0 -236
  139. package/dist/views/workflows-view.js.map +0 -1
  140. package/src/budget-states.ts +0 -54
  141. package/src/cpu-limit/limiter.ts +0 -935
  142. package/src/cpu-limit/use.ts +0 -166
  143. package/src/dashboard/agent-usage-line.tsx +0 -28
  144. package/src/dashboard/agent-usage.ts +0 -48
  145. package/src/dashboard/dashboard.css +0 -148
  146. package/src/dashboard/drilldown.ts +0 -70
  147. package/src/dashboard/index.tsx +0 -4
  148. package/src/dashboard/limits-and-runs.tsx +0 -191
  149. package/src/dashboard/machine-controls.tsx +0 -53
  150. package/src/dashboard/queue-bar.tsx +0 -62
  151. package/src/dashboard/queue-chart.tsx +0 -149
  152. package/src/dashboard/queue-lines.ts +0 -87
  153. package/src/dashboard/queue-table.ts +0 -37
  154. package/src/dashboard/run-doing-words.ts +0 -41
  155. package/src/dashboard/setting-words.ts +0 -30
  156. package/src/dashboard/spending-limit-control.tsx +0 -47
  157. package/src/dashboard/spending-words.ts +0 -32
  158. package/src/dashboard/time-distribution.tsx +0 -61
  159. package/src/dashboard/workflow-dag.tsx +0 -322
  160. package/src/dashboard/workflow-drilldown.tsx +0 -31
  161. package/src/dashboard/workflows-dashboard.tsx +0 -532
  162. package/src/failure.ts +0 -36
  163. package/src/keep-running.ts +0 -85
  164. package/src/outside-failure.ts +0 -39
  165. package/src/pick-wakes.ts +0 -182
  166. package/src/project.ts +0 -127
  167. package/src/queue-counts.ts +0 -64
  168. package/src/reasons.ts +0 -30
  169. package/src/retention.ts +0 -90
  170. package/src/settings.ts +0 -171
  171. package/src/spending-limit.ts +0 -139
  172. package/src/step-files.ts +0 -208
  173. package/src/step-meter.ts +0 -120
  174. package/src/step-times.ts +0 -151
  175. package/src/step-usage.ts +0 -23
  176. package/src/steps.ts +0 -1616
  177. package/src/storage/agent-claims.ts +0 -63
  178. package/src/storage/budgets.ts +0 -152
  179. package/src/storage/engine-records.ts +0 -119
  180. package/src/storage/engine-storage.ts +0 -82
  181. package/src/storage/input-records.ts +0 -43
  182. package/src/storage/move-store.ts +0 -265
  183. package/src/storage/sqlite-store.ts +0 -1022
  184. package/src/storage/step-records.ts +0 -358
  185. package/src/storage/storage-error.ts +0 -35
  186. package/src/storage/task-store.ts +0 -235
  187. package/src/system-workflows.ts +0 -70
  188. package/src/tasks.ts +0 -586
  189. package/src/views/format.ts +0 -40
  190. package/src/views/runs-now.ts +0 -188
  191. package/src/views/step-funnel.ts +0 -163
  192. package/src/views/step-graph.ts +0 -77
  193. package/src/views/workflows-view.ts +0 -484
  194. package/src/workflow-dag.test.tsx +0 -89
  195. package/src/workflow-page.test.tsx +0 -170
@@ -1,839 +0,0 @@
1
- /**
2
- * ONE CPU LIMIT FOR A WHOLE PROJECT, AND THE ONE WAY TO START A PROCESS UNDER IT.
3
- *
4
- * A pool of slots in one SQLite file every process of the project shares, whose size is the limit. Every CPU-heavy process
5
- * holds a slot from before it starts until it exits; more work waits in one line, first come first served, across every
6
- * process. What project work uses is read from the system, so work started with no slot counts against the limit too, and
7
- * running work is paused while project work is over it (`holdToTheLimit`). A slot belongs to its process: one that dies
8
- * gives its slots back, to the next process to look. Lowering the limit stops nothing at once: running work finishes, or is
9
- * paused, and the line waits.
10
- *
11
- * The project says what only it knows (`CpuLimiterFacts`): where its pool lives, which commands are light enough to take no
12
- * slot, which processes are its own, the names of the variables its processes pass on, and whether it is stopped. Its first
13
- * project wrote this as `aoe2-in-browser/install/cpu-slots.ts`, where every incident below happened.
14
- *
15
- * No dependencies beyond Bun and Node: a project runs it on a fresh machine before anything is installed.
16
- */
17
- import { Database } from 'bun:sqlite';
18
- import { spawn as spawnNode } from 'node:child_process';
19
- import fs from 'node:fs';
20
- import os from 'node:os';
21
- import path from 'node:path';
22
- import { cpuSeconds, cpuTimeSeconds, HOLD_EVERY_MS, pauseOrResume, processTree, readUse, roomInThreads, stuckSlots, usedSince } from './use';
23
- /**
24
- * BUN'S OWN THREADS, FEW. Left alone, one bun process starts compiler threads for its JavaScript and WebAssembly and a
25
- * collector marker per core: 24 threads for a script that compiles one module, against 3 with these. Compiling and
26
- * collecting in the thread that runs the code makes a process one thread, as a slot counts it: a typecheck used 23.6 s in
27
- * 23.2 s against 26.4 s in 12.3 s, twice the time and a tenth less CPU (2026-11-07). JavaScriptCore's own options, which
28
- * Bun reads from `BUN_JSC_*`; Node ignores them.
29
- */
30
- export const FEW_THREADS_ENV = {
31
- BUN_JSC_numberOfGCMarkers: '1',
32
- BUN_JSC_numberOfBaselineCompilerThreads: '1',
33
- BUN_JSC_numberOfDFGCompilerThreads: '1',
34
- BUN_JSC_numberOfFTLCompilerThreads: '1',
35
- BUN_JSC_numberOfWasmCompilerThreads: '1',
36
- BUN_JSC_useConcurrentJIT: '0',
37
- BUN_JSC_useConcurrentGC: '0',
38
- };
39
- /** How much lower than what started it a child runs. */
40
- export const LOW_PRIORITY = 10;
41
- const SCHEMA = `
42
- CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
43
- CREATE TABLE IF NOT EXISTS slots (
44
- id INTEGER PRIMARY KEY AUTOINCREMENT, holder INTEGER NOT NULL, holder_started TEXT, child INTEGER, label TEXT NOT NULL, taken REAL NOT NULL
45
- );
46
- CREATE TABLE IF NOT EXISTS slot_line (
47
- id INTEGER PRIMARY KEY AUTOINCREMENT, holder INTEGER NOT NULL, label TEXT NOT NULL, since REAL NOT NULL, even_when_stopped INTEGER NOT NULL DEFAULT 0
48
- );
49
- CREATE TABLE IF NOT EXISTS use_samples (
50
- at REAL PRIMARY KEY, machine_cores REAL NOT NULL, service_cores REAL NOT NULL, cpu_limit INTEGER NOT NULL, top TEXT NOT NULL
51
- );
52
- CREATE TABLE IF NOT EXISTS outside_steps (
53
- hour REAL NOT NULL, label TEXT NOT NULL, source TEXT NOT NULL, starts INTEGER NOT NULL, last REAL NOT NULL,
54
- PRIMARY KEY (hour, label, source)
55
- );`;
56
- /**
57
- * THE POOL'S TABLES, as every process opens them and as a database rebuilt from a project's records gets them, with the
58
- * columns added since. Needs nothing but Bun: a project's setup opens the pool before anything is installed.
59
- */
60
- export const applyPoolSchema = (db) => {
61
- db.exec(SCHEMA);
62
- // Project work, which the limit is for: the service and every command run in the project's folders.
63
- const columns = db.query('PRAGMA table_info(use_samples)').all().map((c) => c.name);
64
- if (!columns.includes('project_cores'))
65
- db.exec('ALTER TABLE use_samples ADD COLUMN project_cores REAL');
66
- // What the line held and kept waiting at each reading, so a reading over the limit shows whether work was let through.
67
- if (!columns.includes('held'))
68
- db.exec('ALTER TABLE use_samples ADD COLUMN held INTEGER');
69
- if (!columns.includes('waiting'))
70
- db.exec('ALTER TABLE use_samples ADD COLUMN waiting INTEGER');
71
- // A slot paused while project work is over the limit (`holdToTheLimit`): since when, the pids stopped, and what it used.
72
- const slotColumns = db.query('PRAGMA table_info(slots)').all().map((c) => c.name);
73
- if (!slotColumns.includes('paused'))
74
- db.exec('ALTER TABLE slots ADD COLUMN paused REAL; ALTER TABLE slots ADD COLUMN paused_pids TEXT; ALTER TABLE slots ADD COLUMN paused_use REAL');
75
- // Batch work waits while anything else waits (`env.batch`).
76
- const lineColumns = db.query('PRAGMA table_info(slot_line)').all().map((c) => c.name);
77
- if (!lineColumns.includes('batch'))
78
- db.exec('ALTER TABLE slot_line ADD COLUMN batch INTEGER NOT NULL DEFAULT 0');
79
- // Urgent work starts at once and is never paused.
80
- if (!lineColumns.includes('urgent'))
81
- db.exec('ALTER TABLE slot_line ADD COLUMN urgent INTEGER NOT NULL DEFAULT 0');
82
- if (!slotColumns.includes('urgent'))
83
- db.exec('ALTER TABLE slots ADD COLUMN urgent INTEGER NOT NULL DEFAULT 0');
84
- };
85
- const RECLAIM_EVERY_MS = 5_000;
86
- /** A slot taken this recently may not show in the reading yet, so it counts as a whole thread on top of it. */
87
- const JUST_TAKEN_SECONDS = 15;
88
- const KEEP_SAMPLES_SECONDS = 24 * 3600;
89
- const KEEP_OUTSIDE_SECONDS = 7 * 24 * 3600;
90
- /** How often an agent's process is read: it is reaped by its SDK, so its figures stop at the last reading. */
91
- const AGENT_READ_EVERY_MS = 10_000;
92
- /** Below this a process is not worth asking the system where it runs. */
93
- const WORTH_ASKING_PERCENT = 1;
94
- /** Readings closer than this are measured from the one before, since `ps`'s times are in hundredths. */
95
- const SHORTEST_WINDOW_SECONDS = 2;
96
- /** Older than this, a reading is too old to say what is happening now: `%cpu` is used instead. */
97
- const LONGEST_WINDOW_SECONDS = 120;
98
- /** How old a reading of project work may be for the line to go by it. */
99
- const READ_USE_EVERY_SECONDS = 5;
100
- /** How long one reading may take (`readLight`'s cap): a process waits this long before it starts one beside another's. */
101
- const READING_TAKES_AT_MOST_SECONDS = 30;
102
- const PS_USE = ['ps', '-Ao', 'pid=,pgid=,%cpu=,time=,command='];
103
- /** Whether `folder` is `root` or below it. Pure. */
104
- const runsUnder = (folder, root) => folder === root || folder.startsWith(`${root}/`);
105
- /**
106
- * Which of `pids` have their working directory in `root` or below it, from the link Linux serves for each (`<proc>/<pid>/cwd`).
107
- * A process that ended since it was listed, or another user's, has no link this process can read, and is not counted.
108
- */
109
- export const pidsRunningUnder = (pids, root, proc = '/proc') => new Set(pids.filter((pid) => {
110
- try {
111
- return runsUnder(fs.readlinkSync(path.join(proc, String(pid), 'cwd')), root);
112
- }
113
- catch {
114
- return false;
115
- }
116
- }));
117
- const alive = (pid) => {
118
- try {
119
- process.kill(pid, 0);
120
- return true;
121
- }
122
- catch (e) {
123
- return e.code === 'EPERM';
124
- }
125
- };
126
- const processStarted = (pid) => {
127
- const r = Bun.spawnSync(['ps', '-o', 'lstart=', '-p', String(pid)], { stdout: 'pipe', stderr: 'ignore' });
128
- const started = r.stdout.toString().trim();
129
- return started === '' ? null : started;
130
- };
131
- const signal = (pids, sig) => {
132
- for (const pid of pids) {
133
- try {
134
- process.kill(pid, sig);
135
- }
136
- catch { /* Gone. */ }
137
- }
138
- };
139
- /** A held lock: what a connection that never waits inside SQLite throws when another holds it. */
140
- const isHeldLock = (e) => /database is locked|SQLITE_BUSY/i.test(e instanceof Error ? e.message : String(e));
141
- /** A project's CPU limit on its facts. Make one per project and process: its state is the pool's and its process's. */
142
- export const makeCpuLimiter = (facts) => {
143
- const connections = new Map();
144
- const pool = () => {
145
- const file = facts.poolFile();
146
- const open = connections.get(file);
147
- if (open !== undefined)
148
- return open;
149
- fs.mkdirSync(path.dirname(file), { recursive: true });
150
- const db = new Database(file, { create: true });
151
- // The wait first: six processes opening the file at once had the journal setting fail as busy, and a holder that fails
152
- // lets its command run with no slot (2026-11-06).
153
- try {
154
- db.exec('PRAGMA busy_timeout = 5000;');
155
- db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;');
156
- applyPoolSchema(db);
157
- takeOldSettings(db);
158
- }
159
- catch (e) {
160
- db.close();
161
- throw e;
162
- }
163
- // NO WAIT INSIDE SQLITE after the open: the pool shares the project's one database, and a wait there holds this thread,
164
- // which may hold a transaction on another connection of the file (2026-11-01, `STORAGE.md`). A write that meets the
165
- // lock is tried again from a timer (`soon`), a look in the line skips a tick, and taking a slot tries again.
166
- db.exec('PRAGMA busy_timeout = 0;');
167
- connections.set(file, db);
168
- return db;
169
- };
170
- /** The old pool's settings (the limit, what a stop set aside), taken where this pool has none yet. */
171
- const takeOldSettings = (db) => {
172
- const from = facts.movedFrom?.() ?? null;
173
- if (from === null || !fs.existsSync(from))
174
- return;
175
- const old = new Database(from, { readonly: true });
176
- try {
177
- if (old.query(`SELECT 1 FROM sqlite_master WHERE name = 'settings'`).get() === null)
178
- return;
179
- const insert = db.query('INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)');
180
- for (const s of old.query('SELECT key, value FROM settings').all())
181
- insert.run(s.key, s.value);
182
- }
183
- finally {
184
- old.close();
185
- }
186
- };
187
- /** The old pool's slots whose holders are alive, read at most once a second: they count toward the limit until gone. */
188
- let oldHeld = { at: 0, n: 0, waiting: 0 };
189
- const heldInOldPool = () => {
190
- const from = facts.movedFrom?.() ?? null;
191
- if (from === null || !fs.existsSync(from))
192
- return { n: 0, waiting: 0 };
193
- if (Date.now() - oldHeld.at < 1_000)
194
- return oldHeld;
195
- const old = new Database(from, { readonly: true });
196
- try {
197
- const slots = old.query(`SELECT 1 FROM sqlite_master WHERE name = 'slots'`).get() === null ? [] : old.query('SELECT holder, child FROM slots').all();
198
- const line = old.query(`SELECT 1 FROM sqlite_master WHERE name = 'slot_line'`).get() === null ? [] : old.query('SELECT holder FROM slot_line').all();
199
- oldHeld = { at: Date.now(), n: slots.filter((s) => alive(s.child ?? s.holder)).length, waiting: line.filter((w) => alive(w.holder)).length };
200
- return oldHeld;
201
- }
202
- finally {
203
- old.close();
204
- }
205
- };
206
- /**
207
- * THE OLD POOL RETIRES once no live process holds a slot or waits there: its history copied (`INSERT OR IGNORE`), then
208
- * the file renamed `.moved`, never deleted. Run from the reclaim; a held lock leaves it for the next.
209
- */
210
- const retireOldPool = (db) => {
211
- const from = facts.movedFrom?.() ?? null;
212
- if (from === null || !fs.existsSync(from))
213
- return;
214
- const held = heldInOldPool();
215
- if (held.n > 0 || held.waiting > 0)
216
- return;
217
- const old = new Database(from, { readonly: true });
218
- try {
219
- const samples = old.query(`SELECT 1 FROM sqlite_master WHERE name = 'use_samples'`).get() === null ? [] : old.query('SELECT at, machine_cores, service_cores, project_cores, cpu_limit, top, held, waiting FROM use_samples').all();
220
- const outside = old.query(`SELECT 1 FROM sqlite_master WHERE name = 'outside_steps'`).get() === null ? [] : old.query('SELECT hour, label, source, starts, last FROM outside_steps').all();
221
- db.transaction(() => {
222
- const s = db.query('INSERT OR IGNORE INTO use_samples (at, machine_cores, service_cores, project_cores, cpu_limit, top, held, waiting) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
223
- for (const r of samples)
224
- s.run(r["at"], r["machine_cores"], r["service_cores"], r["project_cores"] ?? null, r["cpu_limit"], r["top"] ?? '', r["held"] ?? null, r["waiting"] ?? null);
225
- const o = db.query('INSERT OR IGNORE INTO outside_steps (hour, label, source, starts, last) VALUES (?, ?, ?, ?, ?)');
226
- for (const r of outside)
227
- o.run(r["hour"], r["label"], r["source"], r["starts"], r["last"]);
228
- }).immediate();
229
- }
230
- finally {
231
- old.close();
232
- }
233
- for (const f of [from, `${from}-wal`, `${from}-shm`])
234
- if (fs.existsSync(f))
235
- fs.renameSync(f, `${f}.moved`);
236
- console.log(`[cpu slots] the pool moved into ${facts.poolFile()}; ${from} renamed .moved`);
237
- };
238
- /** A write nothing waits on: now, or on a held lock again from a timer every 20 ms, never waiting inside SQLite. */
239
- const soon = (what, write, triesLeft = 500) => {
240
- try {
241
- write();
242
- }
243
- catch (e) {
244
- if (!isHeldLock(e))
245
- throw e;
246
- if (triesLeft <= 0) {
247
- console.error(`[cpu slots] ${what}: the pool stayed locked for 10 s; not written`);
248
- return;
249
- }
250
- setTimeout(() => soon(what, write, triesLeft - 1), 20).unref?.();
251
- }
252
- };
253
- /** A setting stored in the pool, the project's own included (what its stop set aside). */
254
- const setting = (key) => pool().query('SELECT value FROM settings WHERE key = ?').get(key)?.value ?? null;
255
- const setSetting = (key, value) => soon(`the setting ${key}`, () => {
256
- if (value === null)
257
- pool().query('DELETE FROM settings WHERE key = ?').run(key);
258
- else
259
- pool().query('INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)').run(key, value);
260
- });
261
- /** The processor threads this machine has. */
262
- const machineThreads = () => os.cpus().length;
263
- /** How many slots there are now. */
264
- const cpuLimit = () => {
265
- const stored = Number(setting('cpu_limit'));
266
- return Number.isInteger(stored) && stored >= 1 ? stored : facts.defaultLimit;
267
- };
268
- /** Changes the limit, for new work at once. Between 1 and the machine's threads. */
269
- const setCpuLimit = (limit) => {
270
- const kept = Math.max(1, Math.min(machineThreads(), Math.trunc(limit)));
271
- setSetting('cpu_limit', String(kept));
272
- return kept;
273
- };
274
- let thisProcessStarted;
275
- let reclaimedAt = 0;
276
- /** Gives back slots whose process is gone, and takes dead processes out of the line. A reused pid is told by its start time. */
277
- const reclaimSlots = (now = Date.now()) => {
278
- if (now - reclaimedAt < RECLAIM_EVERY_MS)
279
- return 0;
280
- reclaimedAt = now;
281
- const db = pool();
282
- let freed = 0;
283
- try {
284
- for (const s of db.query('SELECT id, holder, holder_started, child FROM slots').all()) {
285
- const running = s.child !== null ? alive(s.child) : alive(s.holder) && (s.holder === process.pid || processStarted(s.holder) === s.holder_started);
286
- if (running)
287
- continue;
288
- db.query('DELETE FROM slots WHERE id = ?').run(s.id);
289
- freed += 1;
290
- }
291
- for (const w of db.query('SELECT id, holder FROM slot_line').all()) {
292
- if (!alive(w.holder))
293
- db.query('DELETE FROM slot_line WHERE id = ?').run(w.id);
294
- }
295
- retireOldPool(db);
296
- }
297
- catch (e) {
298
- // A held lock leaves the rest for the next reclaim, a second away.
299
- if (!isHeldLock(e))
300
- throw e;
301
- }
302
- return freed;
303
- };
304
- const NO_SLOT = { heldBy: () => undefined, release: () => undefined };
305
- /**
306
- * A thread is started under its caller's slot, and a heavy child under the one it was started with (`env.slotHeld`). What
307
- * they start shares it: waiting for another slot while holding one is how a limit of 1 would never finish.
308
- */
309
- const alreadyUnderASlot = () => !Bun.isMainThread || process.env[facts.env.slotHeld] === '1';
310
- /**
311
- * BATCH WORK GOES TO THE BACK OF THE LINE: a process started with `env.batch` set to `1` (and what it starts) waits while
312
- * anything else waits, and so does one start a caller marks `batch` (a re-check's compiles, started by a process whose
313
- * other work is not batch). The first project's full byte check recompiles every function, thousands of compiles over hours; in
314
- * the same first-come line its other compiles waited behind them.
315
- */
316
- const isBatchWork = () => process.env[facts.env.batch] === '1';
317
- /**
318
- * ONE LINE OF WAITERS PER PROCESS, whatever copies of this module it has evaluated. `bun --hot` evaluates a module again on
319
- * every reload, in the same process. With a map of its own, each copy took the line rows of this process it could not see
320
- * as waiters a reload had lost and deleted them: on 2026-11-11 at 06:02 UTC a version of the first project's service waited
321
- * for the slot to prepare it, its row was deleted by an older copy, and no version went live for 9 hours.
322
- */
323
- const shared = (globalThis[Symbol.for(`${facts.name}.cpu-slots.line`)] ??= {
324
- waiting: new Map(),
325
- ticker: null,
326
- look: () => undefined,
327
- });
328
- const waiting = shared.waiting;
329
- /** Bound to the pool it came from: a test run's slot is in the live pool while its tests use their own. */
330
- const slotOf = (id, db = pool()) => ({
331
- heldBy: (child) => soon('a slot\'s process', () => {
332
- db.query('UPDATE slots SET child = ? WHERE id = ?').run(child, id);
333
- }),
334
- release: () => soon('a slot given back', () => {
335
- db.query('DELETE FROM slots WHERE id = ?').run(id);
336
- }),
337
- });
338
- /** Asks `lsof` for the working directories of `pids`. */
339
- const cwdOf = (pids) => ['lsof', '-a', '-p', pids.join(','), '-d', 'cwd', '-Fpn'];
340
- /** Which pids of `lsof`'s answer (`cwdOf`) run in the project's folders. Pure. */
341
- const inProjectFrom = (lsof) => {
342
- const found = new Set();
343
- let pid = 0;
344
- for (const line of lsof.split('\n')) {
345
- if (line.startsWith('p'))
346
- pid = Number(line.slice(1));
347
- if (line.startsWith('n') && runsUnder(line.slice(1), facts.projectRoot))
348
- found.add(pid);
349
- }
350
- return found;
351
- };
352
- /** A light command run to its end, for the few callers that have to have the answer now. Refuses anything else. */
353
- const runLightNow = (cmd, options) => {
354
- if (!facts.isLight(cmd))
355
- throw new Error(`${cmd[0]} is not light, so it takes a slot: use startProcess`);
356
- const r = Bun.spawnSync([...cmd], { stdout: 'pipe', stderr: 'pipe', timeout: 30_000, ...(options?.env === undefined ? {} : { env: options.env }) });
357
- return { code: r.exitCode, stdout: r.stdout.toString(), stdoutBytes: new Uint8Array(r.stdout), stderr: r.stderr.toString() };
358
- };
359
- /**
360
- * A light command's output, read without holding this thread: for the readings taken on a timer, in the process that
361
- * answers requests. Run with `runLightNow` every 2 s, `ps` and `lsof` held its event loop 1.0 to 1.5 s at a time on a busy
362
- * machine (2026-11-11). Refuses anything not light.
363
- */
364
- const readLight = async (cmd) => {
365
- if (!facts.isLight(cmd))
366
- throw new Error(`${cmd[0]} is not light, so it takes a slot: use startProcess`);
367
- const proc = Bun.spawn([...cmd], { stdout: 'pipe', stderr: 'ignore' });
368
- const cap = setTimeout(() => proc.kill(), 30_000);
369
- try {
370
- return await new Response(proc.stdout).text();
371
- }
372
- finally {
373
- clearTimeout(cap);
374
- }
375
- };
376
- /** This process's group: the service's, for a process of the service. */
377
- const thisProcessGroup = () => Number(runLightNow(['ps', '-o', 'pgid=', '-p', String(process.pid)]).stdout.trim());
378
- /** This process's last reading's CPU times, for the next to measure from. */
379
- let lastReading = null;
380
- /** `ps`'s answer (`PS_USE`) measured from this process's reading before it, and the pids worth asking where they run. */
381
- const measure = (psText) => {
382
- const now = Date.now() / 1000;
383
- const window = lastReading === null ? null : now - lastReading.at;
384
- const measured = usedSince(psText, window !== null && window >= SHORTEST_WINDOW_SECONDS && window <= LONGEST_WINDOW_SECONDS ? lastReading.times : null, window ?? 1);
385
- if (window === null || window >= SHORTEST_WINDOW_SECONDS)
386
- lastReading = { at: now, times: measured.times };
387
- const busy = measured.lines.split('\n').flatMap((line) => {
388
- const m = /^\s*(\d+)\s+\d+\s+([\d.]+)\s/.exec(line);
389
- return m !== null && Number(m[2]) >= WORTH_ASKING_PERCENT ? [Number(m[1])] : [];
390
- });
391
- return { ps: measured.lines, busy };
392
- };
393
- /**
394
- * WHICH OF THE BUSY PIDS RUN IN THE PROJECT'S FOLDERS, by how this system tells where a process runs. Linux serves each
395
- * process's working directory as a link, read in this process with nothing started (`pidsRunningUnder`). macOS has no such
396
- * link, so `lsof` is asked there. Asking `lsof` on Linux was the machine's whole load at 16:24-16:27 UTC on 2026-11-17:
397
- * 0.35 s for one pid on a quiet machine and 10 to 20 s on a busy one, 14 going at once (one per process waiting for a
398
- * slot), each a busy pid the next reading asked about; load 12.4 on 4 threads, 65-72% of it in the kernel.
399
- */
400
- const projectPids = process.platform === 'linux'
401
- ? { now: (busy) => pidsRunningUnder(busy, facts.projectRoot), later: async (busy) => pidsRunningUnder(busy, facts.projectRoot) }
402
- : {
403
- now: (busy) => (busy.length === 0 ? new Set() : inProjectFrom(runLightNow(cwdOf(busy)).stdout)),
404
- later: async (busy) => (busy.length === 0 ? new Set() : inProjectFrom(await readLight(cwdOf(busy)))),
405
- };
406
- /** What the machine, the service's group and project work are using now: over the time since this process last read it. */
407
- const useNow = (serviceGroup) => {
408
- const { ps, busy } = measure(runLightNow(PS_USE).stdout);
409
- const inProject = projectPids.now(busy);
410
- return readUse(ps, serviceGroup, (pid) => inProject.has(pid), facts.kinds);
411
- };
412
- /** `useNow`, read without holding this thread (`readLight`). */
413
- const useLater = async (serviceGroup) => {
414
- const { ps, busy } = measure(await readLight(PS_USE));
415
- const inProject = await projectPids.later(busy);
416
- return readUse(ps, serviceGroup, (pid) => inProject.has(pid), facts.kinds);
417
- };
418
- /**
419
- * Reads what project work uses and stores it for the line, without holding this thread (`useLater`): one reading at a
420
- * time across every process of the pool, claimed in the pool before it starts.
421
- */
422
- const storeProjectUse = async (serviceGroup) => {
423
- setSetting('project_use_reading', String(Date.now() / 1000));
424
- const use = await useLater(serviceGroup);
425
- setSetting('project_use', JSON.stringify({ at: Date.now() / 1000, cores: use.project }));
426
- return use;
427
- };
428
- /**
429
- * What project work uses, in threads, for the line: THE STORED READING, NEVER A READ OF THE SYSTEM HERE. The line's look
430
- * runs on the thread of whichever process waits, the one answering requests included, and `ps` plus `lsof` on a busy
431
- * machine take 10 s and more: read here, they held the API worker 10 to 14 s at a time whenever anything waited
432
- * (2026-11-17). The service stores a reading every tick (`holdToTheLimit`); with that one older than 5 seconds a waiting
433
- * process starts one of its own off the thread, unless another process started one in the last 30 seconds, and goes by
434
- * the last reading meanwhile. Only the live pool reads the system: a test's pool goes by what its test stored, or by the
435
- * count alone. None when there is none yet.
436
- */
437
- const projectUseNow = () => {
438
- try {
439
- const stored = setting('project_use');
440
- const last = stored === null ? null : JSON.parse(stored);
441
- const now = Date.now() / 1000;
442
- if (facts.poolFile() !== facts.livePool || (last !== null && now - last.at < READ_USE_EVERY_SECONDS))
443
- return last;
444
- if (now - Number(setting('project_use_reading') ?? 0) >= READING_TAKES_AT_MOST_SECONDS) {
445
- void storeProjectUse(Number(setting('service_group') ?? -1)).catch((e) => console.error(`[cpu slots] could not read project work's use: ${e instanceof Error ? e.message : String(e)}`));
446
- }
447
- return last;
448
- }
449
- catch (e) {
450
- console.error(`[cpu slots] could not read project work's use: ${e instanceof Error ? e.message : String(e)}`);
451
- return null;
452
- }
453
- };
454
- /** Grants this process's waiters whose turn has come. */
455
- const lookInLine = () => {
456
- const db = pool();
457
- reclaimSlots();
458
- const stopped = facts.stopped();
459
- const using = waiting.size > 0 ? projectUseNow() : null;
460
- const granted = db.transaction(() => {
461
- // The old pool's live slots count too, until it retires (`retireOldPool`).
462
- const held = db.query('SELECT COUNT(*) AS n FROM slots').get().n + heldInOldPool().n;
463
- const justTaken = using === null ? 0 : db.query('SELECT COUNT(*) AS n FROM slots WHERE taken > ?').get(Math.min(using.at, Date.now() / 1000 - JUST_TAKEN_SECONDS)).n;
464
- // Nothing starts while a slot is paused for the limit: it resumes first, or it would wait behind newer work for good.
465
- const paused = db.query('SELECT COUNT(*) AS n FROM slots WHERE paused IS NOT NULL').get().n;
466
- const free = paused > 0 ? 0 : roomInThreads(cpuLimit(), held, justTaken, using?.cores ?? 0);
467
- const stoppedOnly = stopped ? 'AND even_when_stopped = 1' : '';
468
- const atOnce = db.query(`SELECT id, holder, label, urgent FROM slot_line WHERE urgent = 1 AND holder = ? ${stoppedOnly} ORDER BY id`).all(process.pid);
469
- const inTurn = db.query(`SELECT id, holder, label, urgent FROM slot_line WHERE urgent = 0 ${stoppedOnly} ORDER BY batch, id LIMIT ?`).all(free);
470
- const line = [...atOnce, ...inTurn];
471
- const out = [];
472
- for (const row of line) {
473
- if (row.holder !== process.pid)
474
- continue;
475
- // Ours and nobody waiting on it: a reload of this module lost the waiter, and it must not hold up the line.
476
- if (!waiting.has(row.id)) {
477
- db.query('DELETE FROM slot_line WHERE id = ?').run(row.id);
478
- continue;
479
- }
480
- db.query('DELETE FROM slot_line WHERE id = ?').run(row.id);
481
- const slot = Number(db.query('INSERT INTO slots (holder, holder_started, label, taken, urgent) VALUES (?, ?, ?, ?, ?)')
482
- .run(process.pid, thisProcessStarted ?? null, row.label, Date.now() / 1000, row.urgent).lastInsertRowid);
483
- out.push({ line: row.id, slot });
484
- }
485
- return out;
486
- }).immediate();
487
- for (const g of granted) {
488
- const w = waiting.get(g.line);
489
- waiting.delete(g.line);
490
- w?.grant(slotOf(g.slot));
491
- }
492
- if (stopped) {
493
- for (const [line, w] of [...waiting]) {
494
- if (db.query('SELECT even_when_stopped AS e FROM slot_line WHERE id = ?').get(line)?.e === 1)
495
- continue;
496
- db.query('DELETE FROM slot_line WHERE id = ?').run(line);
497
- waiting.delete(line);
498
- w.refuse(facts.refusal(w.label));
499
- }
500
- }
501
- if (waiting.size === 0 && shared.ticker !== null) {
502
- clearInterval(shared.ticker);
503
- shared.ticker = null;
504
- }
505
- };
506
- const look = () => {
507
- try {
508
- lookInLine();
509
- }
510
- catch (e) {
511
- // A held lock: the next look, 250 ms on, tries again. A slot must never fail the work waiting for it.
512
- if (!isHeldLock(e))
513
- console.error(`[cpu slots] ${e instanceof Error ? e.message : String(e)}`);
514
- }
515
- };
516
- shared.look = look;
517
- /**
518
- * A slot: at once if one is free and nobody is ahead, else when its turn comes. URGENT WORK starts at once, over the limit,
519
- * and is never paused for it: what a project runs to go live and to say whether it is healthy. At 22:12 UTC on 2026-11-11
520
- * the typecheck that gates a version waited in the same line as two slow steps, and no fix could go live. A caller says so
521
- * with `urgent`, and nothing inherits it.
522
- */
523
- const takeSlot = (label, options) => {
524
- if (alreadyUnderASlot())
525
- return Promise.resolve(NO_SLOT);
526
- // A pool that cannot be read is a refusal the caller can handle, never a throw past it.
527
- try {
528
- if (facts.stopped() && options?.evenWhenStopped !== true)
529
- return Promise.reject(facts.refusal(label));
530
- }
531
- catch (e) {
532
- return Promise.reject(e);
533
- }
534
- thisProcessStarted ??= processStarted(process.pid);
535
- return new Promise((resolve, reject) => {
536
- // Into the line; a held lock tries again from a timer, never waiting inside SQLite.
537
- const enter = (triesLeft) => {
538
- let line;
539
- try {
540
- line = Number(pool().query('INSERT INTO slot_line (holder, label, since, even_when_stopped, batch, urgent) VALUES (?, ?, ?, ?, ?, ?)')
541
- .run(process.pid, label, Date.now() / 1000, options?.evenWhenStopped === true ? 1 : 0, isBatchWork() || options?.batch === true ? 1 : 0, options?.urgent === true ? 1 : 0).lastInsertRowid);
542
- }
543
- catch (e) {
544
- if (!isHeldLock(e) || triesLeft <= 0)
545
- return reject(e);
546
- setTimeout(() => enter(triesLeft - 1), 20);
547
- return;
548
- }
549
- waitInLine(line);
550
- };
551
- const waitInLine = (line) => {
552
- const giveUp = () => {
553
- if (!waiting.delete(line))
554
- return;
555
- soon('a waiter leaving the line', () => pool().query('DELETE FROM slot_line WHERE id = ?').run(line));
556
- reject(options?.signal?.reason instanceof Error ? options.signal.reason : new Error(`${label}: stopped while waiting for a CPU slot`));
557
- };
558
- waiting.set(line, {
559
- label,
560
- grant: (slot) => {
561
- options?.signal?.removeEventListener('abort', giveUp);
562
- resolve(slot);
563
- },
564
- refuse: reject,
565
- });
566
- options?.signal?.addEventListener('abort', giveUp, { once: true });
567
- look();
568
- // The ticker looks with the newest copy of this module.
569
- if (waiting.size > 0 && shared.ticker === null)
570
- shared.ticker = setInterval(() => shared.look(), 250);
571
- };
572
- enter(500);
573
- });
574
- };
575
- /** `work` under a slot, for work in a thread or in this process rather than a process of its own. */
576
- const withSlot = async (label, work) => {
577
- const slot = await takeSlot(label);
578
- try {
579
- return await work();
580
- }
581
- finally {
582
- slot.release();
583
- }
584
- };
585
- const poolNow = () => {
586
- const db = pool();
587
- reclaimSlots();
588
- const held = db.query('SELECT label, taken AS since, COALESCE(child, holder) AS pid FROM slots ORDER BY id').all();
589
- return {
590
- limit: cpuLimit(),
591
- threads: machineThreads(),
592
- held,
593
- stuck: stuckSlots(held, Date.now() / 1000),
594
- waiting: db.query('SELECT label, since FROM slot_line ORDER BY urgent DESC, batch, id').all(),
595
- };
596
- };
597
- /** Stores the project's reading, which is also the line's newest one, and the service's group, which the line reads by. */
598
- const recordUseSample = (s, serviceGroup) => soon('a use sample', () => {
599
- const db = pool();
600
- const held = db.query('SELECT COUNT(*) AS n FROM slots').get().n;
601
- const waitingNow = db.query('SELECT COUNT(*) AS n FROM slot_line').get().n;
602
- db.query('INSERT OR REPLACE INTO use_samples (at, machine_cores, service_cores, project_cores, cpu_limit, top, held, waiting) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
603
- .run(s.at, s.machine_cores, s.service_cores, s.project_cores, cpuLimit(), s.top, held, waitingNow);
604
- db.query('DELETE FROM use_samples WHERE at < ?').run(s.at - KEEP_SAMPLES_SECONDS);
605
- setSetting('service_group', String(serviceGroup));
606
- setSetting('project_use', JSON.stringify({ at: s.at, cores: s.project_cores }));
607
- });
608
- const useSamplesSince = (since) => pool().query('SELECT at, machine_cores, service_cores, COALESCE(project_cores, service_cores) AS project_cores, cpu_limit, top, held, waiting FROM use_samples WHERE at >= ? ORDER BY at').all(since);
609
- /** The platform's view of this limit (`project.ts` `CpuLimit`): the limit, and the newest reading in the last 10 minutes. */
610
- const asCpuLimit = {
611
- limit: cpuLimit,
612
- newestUse: () => {
613
- const newest = useSamplesSince(Date.now() / 1000 - 600).at(-1);
614
- return newest === undefined ? null : { at: newest.at, cores: newest.project_cores, held: newest.held ?? 0, waiting: newest.waiting ?? 0 };
615
- },
616
- };
617
- // ---------------------------------------------------------------------- work outside a workflow step
618
- /** The file that started a process, from the first frame outside this module and the project's wrapper. Pure on its stack. */
619
- const startedFrom = (stack) => {
620
- const own = new Set([path.basename(import.meta.path), ...facts.wrapperFiles.map((f) => path.basename(f))]);
621
- for (const line of stack.split('\n').slice(1)) {
622
- const file = /\(?((?:\/|[A-Za-z]:\\)[^():]+\.tsx?)(?::\d+)+\)?\s*$/.exec(line.trim())?.[1];
623
- if (file === undefined || own.has(path.basename(file)))
624
- continue;
625
- return facts.sourceOf(file.replaceAll('\\', '/'));
626
- }
627
- return 'unknown';
628
- };
629
- /** A process a step started, told its step by `env.stepRecord`: what it starts is that step's work. */
630
- const startedByAStep = () => Number(process.env[facts.env.stepRecord]) > 0;
631
- /**
632
- * WORK NO WORKFLOW STEP STARTED, recorded where it starts: a process is a step's when its caller passes the step's `usage`;
633
- * one started with none is stored here, by its label and the file that started it, and a page names each as a defect.
634
- */
635
- const recordOutsideStep = (label, source, at = Date.now() / 1000) => {
636
- try {
637
- soon(`${label} outside a step`, () => {
638
- const db = pool();
639
- db.query(`INSERT INTO outside_steps (hour, label, source, starts, last) VALUES (?, ?, ?, 1, ?)
640
- ON CONFLICT(hour, label, source) DO UPDATE SET starts = starts + 1, last = excluded.last`)
641
- .run(Math.floor(at / 3600) * 3600, label, source, at);
642
- db.query('DELETE FROM outside_steps WHERE hour < ?').run(at - KEEP_OUTSIDE_SECONDS);
643
- });
644
- }
645
- catch (e) {
646
- // The record never stops the work it records.
647
- console.error(`[cpu slots] could not record ${label} outside a step: ${e instanceof Error ? e.message : String(e)}`);
648
- }
649
- };
650
- /** Each kind of work started outside a step since `since` (unix seconds), most started first. */
651
- const outsideStepsSince = (since) => pool().query(`SELECT label, source, SUM(starts) AS starts, MAX(last) AS last FROM outside_steps WHERE hour >= ?
652
- GROUP BY label, source ORDER BY starts DESC, label`).all(Math.floor(since / 3600) * 3600);
653
- // ---------------------------------------------------------------------- starting a process
654
- /**
655
- * THE ONE WAY TO START A PROCESS: `label` says what it is in a page's list. Waits for a slot unless the command is light,
656
- * runs it at low priority, and gives the slot back and reports what it used when it exits. The process is an ordinary
657
- * subprocess; killing it frees its slot.
658
- */
659
- const startProcess = async (label, cmd, options) => {
660
- const { usage, signal: abort, evenWhenStopped, inLine, urgent, batch, ...spawn } = options;
661
- if ((usage === null || usage === undefined) && !startedByAStep())
662
- recordOutsideStep(label, startedFrom(new Error().stack ?? ''));
663
- const light = facts.isLight(cmd);
664
- const waitForSlot = async () => {
665
- inLine?.(true);
666
- try {
667
- return await takeSlot(label, { ...(abort === undefined ? {} : { signal: abort }), ...(evenWhenStopped === undefined ? {} : { evenWhenStopped }), ...(urgent === undefined ? {} : { urgent }), ...(batch === undefined ? {} : { batch }) });
668
- }
669
- finally {
670
- inLine?.(false);
671
- }
672
- };
673
- const slot = light ? NO_SLOT : await waitForSlot();
674
- const env = {
675
- ...(spawn.env ?? process.env),
676
- ...FEW_THREADS_ENV,
677
- ...(light ? {} : { [facts.env.slotHeld]: '1' }),
678
- ...(usage?.record === null || usage?.record === undefined ? {} : { [facts.env.stepRecord]: String(usage.record) }),
679
- };
680
- let proc;
681
- try {
682
- proc = Bun.spawn(['/usr/bin/nice', '-n', String(LOW_PRIORITY), ...cmd], { ...spawn, env });
683
- }
684
- catch (e) {
685
- slot.release();
686
- throw e;
687
- }
688
- slot.heldBy(proc.pid);
689
- void proc.exited.then(() => {
690
- slot.release();
691
- const used = proc.resourceUsage();
692
- if (used !== undefined)
693
- usage?.add({ label, cpuSeconds: Number(used.cpuTime.total) / 1e6, peakBytes: used.maxRSS });
694
- });
695
- return proc;
696
- };
697
- /**
698
- * AN AGENT'S PROCESS: takes no slot, it spends its life waiting on the network, runs at low priority with what it starts,
699
- * and reports its CPU and peak size to its step. Node's own spawn, as an agent SDK expects of a process.
700
- */
701
- const startAgentProcess = (options, usage) => {
702
- if (usage === null && !startedByAStep())
703
- recordOutsideStep('agent', startedFrom(new Error().stack ?? ''));
704
- const child = spawnNode('/usr/bin/nice', ['-n', String(LOW_PRIORITY), options.command, ...options.args], {
705
- stdio: ['pipe', 'pipe', 'ignore'], env: { ...options.env, ...FEW_THREADS_ENV }, signal: options.signal,
706
- ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
707
- });
708
- let cpu = 0;
709
- let peakBytes = 0;
710
- const read = () => {
711
- if (child.pid === undefined)
712
- return;
713
- const [time, rss] = runLightNow(['ps', '-o', 'time=,rss=', '-p', String(child.pid)]).stdout.trim().split(/\s+/);
714
- if (time === undefined || rss === undefined || time === '')
715
- return;
716
- cpu = cpuTimeSeconds(time);
717
- peakBytes = Math.max(peakBytes, Number(rss) * 1024);
718
- };
719
- const reading = setInterval(read, AGENT_READ_EVERY_MS);
720
- reading.unref();
721
- child.once('exit', () => {
722
- clearInterval(reading);
723
- const used = { label: 'agent', cpuSeconds: cpu, peakBytes };
724
- usage?.add(used);
725
- });
726
- return child;
727
- };
728
- // ---------------------------------------------------------------------- holding work already running to the limit
729
- /** Resumes every paused slot: at start, when everything is stopped (a stopped process cannot end), and on exit. */
730
- const resumeAll = () => {
731
- const db = pool();
732
- for (const s of db.query('SELECT id, paused_pids AS pids FROM slots WHERE paused IS NOT NULL').all()) {
733
- signal([...JSON.parse(s.pids ?? '[]')].reverse(), 'SIGCONT');
734
- soon('a slot resumed', () => db.query('UPDATE slots SET paused = NULL, paused_pids = NULL, paused_use = NULL WHERE id = ?').run(s.id));
735
- }
736
- };
737
- const HOLDING = Symbol.for(`${facts.name}.cpu-slots.holdToTheLimit`);
738
- /**
739
- * HOLDS PROJECT WORK TO THE LIMIT WHILE IT RUNS, not only when it starts: every 2 seconds, from the CPU time used since the
740
- * reading before, a slot run in a process of its own is paused (SIGSTOP, its whole tree) while project work is over the
741
- * limit, newest first, and resumed (SIGCONT), oldest first, once what it used fits again (`pauseOrResume`). Nothing new
742
- * starts while one is paused (`lookInLine`). Run by one process of the project, on the live pool only; it replaces a copy an
743
- * earlier load of this module started.
744
- *
745
- * WHY: on 2026-11-07 at 03:20 UTC the limit was lowered to 2 and five readings in eighteen were over it, up to 4.7:
746
- * lowering the limit stopped nothing already running, and a slot is one thread while `bun test` used 2.1 and `tsc` 2.2.
747
- */
748
- const holdToTheLimit = (serviceGroup) => {
749
- const holder = globalThis;
750
- if (holder[HOLDING] !== undefined)
751
- clearInterval(holder[HOLDING]);
752
- if (facts.poolFile() !== facts.livePool)
753
- return;
754
- resumeAll();
755
- if (!holder.resumesOnExit) {
756
- holder.resumesOnExit = true;
757
- process.once('exit', () => { try {
758
- resumeAll();
759
- }
760
- catch { /* The pool is gone with the process. */ } });
761
- }
762
- let before = null;
763
- // A tick still reading when the next is due is not overlapped: the next one skips.
764
- let reading = false;
765
- holder[HOLDING] = setInterval(() => {
766
- if (reading)
767
- return;
768
- reading = true;
769
- void tick().finally(() => {
770
- reading = false;
771
- });
772
- }, HOLD_EVERY_MS);
773
- // Reads the system without holding this thread (`readLight`), and stores what project work uses for the line, so the
774
- // line in this process never reads it itself (`projectUseNow`).
775
- async function tick() {
776
- try {
777
- if (facts.stopped())
778
- return resumeAll();
779
- const using = (await storeProjectUse(serviceGroup)).project;
780
- // Each slot's own use, from the CPU time its processes used since the tick before.
781
- const ps = await readLight(['ps', '-Ao', 'pid=,ppid=,time=']);
782
- const db = pool();
783
- const now = Date.now() / 1000;
784
- const times = new Map();
785
- for (const line of ps.split('\n')) {
786
- const m = /^\s*(\d+)\s+\d+\s+(\S+)/.exec(line);
787
- if (m !== null)
788
- times.set(Number(m[1]), cpuSeconds(m[2]));
789
- }
790
- const window = before === null ? null : now - before.at;
791
- const used = (pid) => {
792
- const was = before?.times.get(pid);
793
- const t = times.get(pid) ?? 0;
794
- return window === null || window <= 0 ? 0 : (was === undefined || was > t ? t : t - was) / window;
795
- };
796
- before = { at: now, times };
797
- const slots = db.query('SELECT id, holder, child, label, taken, paused, paused_use AS pausedUse FROM slots WHERE child IS NOT NULL AND child != holder AND urgent = 0').all()
798
- .filter((s) => alive(s.child))
799
- .map((s) => {
800
- const pids = processTree(ps, s.child).filter((pid) => pid !== s.holder && pid !== process.pid);
801
- return { ...s, pids, use: pids.reduce((sum, pid) => sum + used(pid), 0) };
802
- });
803
- if (window === null)
804
- return;
805
- const limit = cpuLimit();
806
- const { pause, resume } = pauseOrResume(limit, using, slots, now);
807
- for (const slot of slots.filter((s) => pause.includes(s.id))) {
808
- // Recorded before it is stopped: a held lock leaves it running for the next tick, never stopped with no record.
809
- try {
810
- db.query('UPDATE slots SET paused = ?, paused_pids = ?, paused_use = ? WHERE id = ?').run(now, JSON.stringify(slot.pids), slot.use, slot.id);
811
- }
812
- catch (e) {
813
- if (isHeldLock(e))
814
- continue;
815
- throw e;
816
- }
817
- signal(slot.pids, 'SIGSTOP');
818
- console.error(`[cpu limit] paused ${slot.label} (${slot.pids.length} processes, ${slot.use.toFixed(1)} threads): project work ${using.toFixed(1)} of a limit of ${limit}`);
819
- }
820
- const slot = slots.find((s) => s.id === resume);
821
- if (slot === undefined)
822
- return;
823
- const row = db.query('SELECT paused_pids AS pids FROM slots WHERE id = ?').get(slot.id);
824
- signal([...JSON.parse(row.pids ?? '[]')].reverse(), 'SIGCONT');
825
- soon('a slot resumed', () => db.query('UPDATE slots SET paused = NULL, paused_pids = NULL, paused_use = NULL WHERE id = ?').run(slot.id));
826
- console.error(`[cpu limit] resumed ${slot.label} (used ${(slot.pausedUse ?? 0).toFixed(1)} threads): project work ${using.toFixed(1)} of a limit of ${limit}`);
827
- }
828
- catch (e) {
829
- console.error(`[cpu limit] could not hold work to the limit: ${e instanceof Error ? e.message : String(e)}`);
830
- }
831
- }
832
- };
833
- return {
834
- setting, setSetting, machineThreads, cpuLimit, setCpuLimit, reclaimSlots, takeSlot, withSlot, poolNow,
835
- recordUseSample, useSamplesSince, asCpuLimit, startedFrom, outsideStepsSince, startProcess, startAgentProcess,
836
- runLightNow, thisProcessGroup, useNow, useLater, holdToTheLimit,
837
- };
838
- };
839
- //# sourceMappingURL=limiter.js.map