@roomi-fields/grillhouse 0.42.0 → 0.43.1

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.
@@ -0,0 +1,231 @@
1
+ // The watch of the memory of a pass: a heavy pass runs its command under it, and is cut before the
2
+ // kernel kills, as earlyoom and systemd-oomd end a group before the kernel's own OOM killer does.
3
+ //
4
+ // node garde-de-la-memoire.mjs --temoin <file> -- <command> [<argument>…]
5
+ //
6
+ // - The command runs in the process group of the watch, its streams the caller's: a signal sent
7
+ // to the group of a pass (the stop of an act, of a night, of a session) reaches it as it reaches
8
+ // the watch.
9
+ // - Every PAS ms the watch reads what the machine still gives (`memoireRestante` of
10
+ // scripts/mesure-de-la-machine.mjs: the memory available and the free swap) and the pressure of
11
+ // the memory (`/proc/pressure/memory`, line `full`, field `avg10`: the share of the last ten
12
+ // seconds in which every task waited for memory, in %). The pass is cut (`memoireEpuisee`) under
13
+ // MEMOIRE_MIN for memory and swap together, or at SEUIL_PRESSION_MEMOIRE of pressure, which a
14
+ // swap held in memory (zram) reaches first.
15
+ // - Cut, the watch ends the command and each process born of it (SIGTERM, then SIGKILL after DELAI
16
+ // ms for those still alive), writes why in <file>, and exits at 75, « à repasser », once they are
17
+ // dead: the pass was not judged, and holds no memory when it gives the machine back.
18
+ // - Otherwise it exits with the command's own code; a command a signal ended gives 1, the signal
19
+ // said on the error output.
20
+ // - A machine that says neither its memory nor its pressure is not watched: the command runs as
21
+ // it is.
22
+ import { spawn } from 'node:child_process';
23
+ import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
24
+ import { fileURLToPath, pathToFileURL } from 'node:url';
25
+ import { A_REPASSER } from './codes-de-sortie.mjs';
26
+ import { departDe, memoireRestante, processusVivant } from './mesure-de-la-machine.mjs';
27
+ import { MEMOIRE_MIN } from './regles-des-places.mjs';
28
+
29
+ /** This script. */
30
+ export const SCRIPT = fileURLToPath(import.meta.url);
31
+ /** The variable a trial fixes what the machine gives under: JSON `{ disponible, echange, pression }`. */
32
+ export const VARIABLE_MEMOIRE_D_ESSAI = 'GRILLHOUSE_MEMOIRE_D_ESSAI';
33
+ /** The pressure of the memory a pass is cut at, in %. */
34
+ export const SEUIL_PRESSION_MEMOIRE = 50;
35
+ const FICHIER_PRESSION = '/proc/pressure/memory';
36
+ const PAS = 2000;
37
+ const DELAI = 5000;
38
+
39
+ const go = n => (n / 1024 ** 3).toFixed(1).replace('.', ',');
40
+
41
+ /**
42
+ * The pressure `full avg10` of the memory in <texte> (/proc/pressure/memory), in %; null when it
43
+ * does not say it.
44
+ * @param {string} texte
45
+ * @returns {number | null}
46
+ */
47
+ export function lireLaPressionDeLaMemoire(texte) {
48
+ const m = /^full\b.*\bavg10=(\d+(?:\.\d+)?)/m.exec(texte);
49
+ return m ? Number(m[1]) : null;
50
+ }
51
+
52
+ /**
53
+ * Why a pass is cut at this memory, null while it may go on: the memory available and the free
54
+ * swap together under MEMOIRE_MIN, or the pressure of the memory at SEUIL_PRESSION_MEMOIRE.
55
+ * @param {{ disponible: number | null, echange: number, pression: number | null }} m bytes, %
56
+ * @returns {string | null}
57
+ */
58
+ export function memoireEpuisee({ disponible, echange, pression }) {
59
+ const suite =
60
+ 'la passe est coupée avant que le système ne tue, à repasser quand la machine a de la place.';
61
+ if (disponible !== null && disponible + echange < MEMOIRE_MIN) {
62
+ return `mémoire épuisée : ${go(disponible)} Go disponibles et ${go(echange)} Go d'échange libres, sous les ${go(MEMOIRE_MIN)} Go gardés ; ${suite}`;
63
+ }
64
+ if (pression !== null && pression >= SEUIL_PRESSION_MEMOIRE) {
65
+ return `mémoire épuisée : la machine attend sa mémoire ${String(pression).replace('.', ',')} % du temps (seuil ${SEUIL_PRESSION_MEMOIRE} %) ; ${suite}`;
66
+ }
67
+ return null;
68
+ }
69
+
70
+ /**
71
+ * What the machine gives now under <env>: a trial's, else the kernel's.
72
+ * @param {Record<string, string | undefined>} [env]
73
+ * @returns {{ disponible: number | null, echange: number, pression: number | null }}
74
+ */
75
+ export function mesurerLaMemoire(env = process.env) {
76
+ if (env[VARIABLE_MEMOIRE_D_ESSAI]) {
77
+ return { pression: null, ...JSON.parse(env[VARIABLE_MEMOIRE_D_ESSAI]) };
78
+ }
79
+ let pression = null;
80
+ try {
81
+ pression = lireLaPressionDeLaMemoire(readFileSync(FICHIER_PRESSION, 'utf8'));
82
+ } catch {
83
+ // no pressure stall information on the machine
84
+ }
85
+ return { ...memoireRestante(), pression };
86
+ }
87
+
88
+ // The processes born of <pid>, itself left out, as /proc says them now.
89
+ function descendants(pid) {
90
+ /** @type {Map<number, number[]>} */
91
+ const enfants = new Map();
92
+ for (const n of readdirSync('/proc')) {
93
+ if (!/^\d+$/.test(n)) {
94
+ continue;
95
+ }
96
+ try {
97
+ // The fields after the name, which may hold spaces and parentheses: state, then parent.
98
+ const stat = readFileSync(`/proc/${n}/stat`, 'utf8');
99
+ const parent = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
100
+ enfants.set(parent, [...(enfants.get(parent) ?? []), Number(n)]);
101
+ } catch {
102
+ // gone meanwhile
103
+ }
104
+ }
105
+ const nes = [];
106
+ for (const file = [pid]; file.length;) {
107
+ for (const e of enfants.get(file.shift()) ?? []) {
108
+ nes.push(e);
109
+ file.push(e);
110
+ }
111
+ }
112
+ return nes;
113
+ }
114
+
115
+ // <signal> to each process of <relevés> (`{ pid, depart }`) that still is the one relevé.
116
+ const signaler = (releves, signal) => {
117
+ for (const r of releves) {
118
+ if (!processusVivant(r)) {
119
+ continue;
120
+ }
121
+ try {
122
+ process.kill(r.pid, signal);
123
+ } catch {
124
+ // gone
125
+ }
126
+ }
127
+ };
128
+
129
+ // The processes <pids> as relevés now: each with its start, which tells it from another process
130
+ // that takes its number later.
131
+ const relever = pids => pids.map(pid => ({ pid, depart: departDe(pid) })).filter(r => r.depart);
132
+
133
+ /**
134
+ * Runs <cmd> <args> under the watch: its exit code, 75 when the watch cut it, its witness
135
+ * <temoin> then saying why. A cut ends only once the command and every process relevé are dead,
136
+ * SIGKILL sent after <delai> ms to those SIGTERM did not end.
137
+ * @param {{ cmd: string, args: string[], temoin: string, mesurer?: () => { disponible: number | null, echange: number, pression: number | null }, pas?: number, delai?: number, stdio?: import('node:child_process').StdioOptions, env?: NodeJS.ProcessEnv, cwd?: string }} o
138
+ * @returns {Promise<number>}
139
+ */
140
+ export function veiller({
141
+ cmd,
142
+ args,
143
+ temoin,
144
+ mesurer = () => mesurerLaMemoire(),
145
+ pas = PAS,
146
+ delai = DELAI,
147
+ stdio = 'inherit',
148
+ env = process.env,
149
+ cwd,
150
+ }) {
151
+ return new Promise(resolve => {
152
+ const enfant = spawn(cmd, args, { stdio, env, cwd });
153
+ // The processes relevés at the cut, and its end: all dead, or SIGKILL sent at the delay.
154
+ let releves = null;
155
+ let finDeLaCoupe = null;
156
+ const couper = raison => {
157
+ // Relevés twice, the command still their ancestor: one born between the two is caught.
158
+ const nes = new Set([enfant.pid, ...descendants(enfant.pid)]);
159
+ for (const p of descendants(enfant.pid)) {
160
+ nes.add(p);
161
+ }
162
+ releves = relever([...nes]);
163
+ signaler(releves, 'SIGTERM');
164
+ finDeLaCoupe = new Promise(fin => {
165
+ // SIGKILL at the delay to those SIGTERM did not end; the end once none lives, or as long
166
+ // again after SIGKILL at the latest.
167
+ const limite = Date.now() + delai;
168
+ let tues = false;
169
+ const voir = setInterval(() => {
170
+ const vivants = releves.filter(processusVivant);
171
+ if (vivants.length && !tues && Date.now() >= limite) {
172
+ tues = true;
173
+ signaler(vivants, 'SIGKILL');
174
+ }
175
+ if (vivants.length === 0 || Date.now() >= limite + delai) {
176
+ clearInterval(voir);
177
+ fin();
178
+ }
179
+ }, 100);
180
+ });
181
+ try {
182
+ writeFileSync(temoin, `${raison}\n`);
183
+ } catch {
184
+ // the exit code alone says the cut
185
+ }
186
+ };
187
+ const veille = setInterval(() => {
188
+ if (releves) {
189
+ return;
190
+ }
191
+ let raison = null;
192
+ try {
193
+ raison = memoireEpuisee(mesurer());
194
+ } catch {
195
+ // a measure that does not read cuts nothing
196
+ }
197
+ if (raison) {
198
+ couper(raison);
199
+ }
200
+ }, pas);
201
+ enfant.on('error', e => {
202
+ clearInterval(veille);
203
+ process.stderr.write(`⛔ ${cmd} ne se lance pas : ${e.message}\n`);
204
+ resolve(1);
205
+ });
206
+ enfant.on('exit', (code, signal) => {
207
+ clearInterval(veille);
208
+ if (finDeLaCoupe) {
209
+ void finDeLaCoupe.then(() => resolve(A_REPASSER));
210
+ return;
211
+ }
212
+ if (code === null) {
213
+ process.stderr.write(`⛔ ${cmd} est arrêté par le signal ${signal}.\n`);
214
+ }
215
+ resolve(code ?? 1);
216
+ });
217
+ });
218
+ }
219
+
220
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
221
+ const args = process.argv.slice(2);
222
+ if (args[0] !== '--temoin' || args[2] !== '--' || args.length < 4) {
223
+ process.stderr.write(
224
+ 'usage: garde-de-la-memoire.mjs --temoin <fichier> -- <commande> [<argument>…]\n'
225
+ );
226
+ process.exitCode = 2;
227
+ } else {
228
+ const [cmd, ...reste] = args.slice(3);
229
+ process.exitCode = await veiller({ cmd, args: reste, temoin: args[1] });
230
+ }
231
+ }
@@ -74,7 +74,14 @@ import { spawnSync } from 'node:child_process';
74
74
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
75
75
  import { createRequire } from 'node:module';
76
76
  import path from 'node:path';
77
- import { couvertPar, engendresDe, regenerer, touchesPar } from '../engendres.mjs';
77
+ import {
78
+ aRejouer,
79
+ couvertPar,
80
+ encoreDeclares,
81
+ engendresDe,
82
+ prendreLesEngendres,
83
+ regenerer,
84
+ } from '../engendres.mjs';
78
85
  import { avecLesDonnees, donneesDe } from '../donnees-cles.mjs';
79
86
  import { avecLesOutils, outilsDe } from '../outils-cles.mjs';
80
87
  import { lireCommit } from '../poussee-cles.mjs';
@@ -672,7 +679,9 @@ function remplacer(o, tip, tete) {
672
679
  return { garde: `la copie ne prend pas ${tip.slice(0, 7)}` };
673
680
  }
674
681
  // A conflict on generated files the project declares only is no conflict: main's version is
675
- // taken, and their command writes them again once the branch is replaced (below).
682
+ // taken, and their command writes them again once the branch is replaced (below). One the branch
683
+ // removes from the key (`encoreDeclares`, read in the copy) takes the branch's version, its
684
+ // deletion too, and its command is not played.
676
685
  let rebase = dansCopie('rebase', tete);
677
686
  let tours = Number(dansCopie('rev-list', '--count', `${tete}..${tip}`).stdout.trim()) || 1;
678
687
  while (rebase.status !== 0) {
@@ -683,8 +692,7 @@ function remplacer(o, tip, tete) {
683
692
  tours-- > 0 &&
684
693
  conflits.length > 0 &&
685
694
  conflits.every(f => engendres.some(e => couvertPar(e.entiers, f))) &&
686
- dansCopie('checkout', '--ours', '--', ...conflits).status === 0 &&
687
- dansCopie('add', '--', ...conflits).status === 0;
695
+ prendreLesEngendres({ conflits, vivants: encoreDeclares(engendres, copie), dansCopie });
688
696
  if (!engendresSeuls) {
689
697
  dansCopie('rebase', '--abort');
690
698
  return {
@@ -702,8 +710,9 @@ function remplacer(o, tip, tete) {
702
710
  if (installation) {
703
711
  return { sortie: [installation, "Le verrou de la branche replacée ne s'installe pas."] };
704
712
  }
705
- const touches = touchesPar(
713
+ const touches = aRejouer(
706
714
  engendres,
715
+ copie,
707
716
  dansCopie('diff', '--name-only', '--no-renames', '-z', tete, 'HEAD')
708
717
  .stdout.split('\0')
709
718
  .filter(Boolean)
@@ -64,7 +64,9 @@
64
64
  // of synthhub and open-synth-descriptors). A command of the project at another code than 0, one of
65
65
  // the frame on a real failure (126, 127, a signal), or a file it changes that its `fichiers` do not
66
66
  // cover, refuses the lot, the command, its code and its output named. A conflict on any other file
67
- // refuses it, as the three-way application says.
67
+ // refuses it, as the three-way application says. A generated file of the project the lot removes
68
+ // from the key (`encoreDeclares` of scripts/engendres.mjs, read in the copy once the lots are
69
+ // applied) follows the lot: its deletion is done, any other change applied, its command not played.
68
70
  //
69
71
  // What steps 2, 3 and 5 read of a lot is its files: each file added, modified or deleted, a
70
72
  // rename counting its source and its destination (named as the file is, not as git quotes it in
@@ -84,7 +86,14 @@ import { existsSync, readFileSync } from 'node:fs';
84
86
  import path from 'node:path';
85
87
  import { pathToFileURL } from 'node:url';
86
88
  import { arbitrageTranche, estArbitrage } from '../arbitrages.mjs';
87
- import { couvertPar, engendresDe, regenerer, touchesPar } from '../engendres.mjs';
89
+ import {
90
+ couvertPar,
91
+ engendresDe,
92
+ partDesLots,
93
+ poserLesRetires,
94
+ regenerer,
95
+ touchesPar,
96
+ } from '../engendres.mjs';
88
97
  import { langageDe } from '../langages.mjs';
89
98
  import { prefixe } from '../prefixe-des-tickets.mjs';
90
99
  import { commitsDelivering, gitLog } from '../un-commit-par-ticket.mjs';
@@ -427,10 +436,8 @@ function main(argv) {
427
436
  return refuser(`Les références ${o.references} ne se lisent pas : ${e.message}`);
428
437
  }
429
438
  }
430
- const references = [
431
- ...engendres.map(e => ({ ...e, cadre: false })),
432
- ...duCircuit.map(r => ({ ...r, lit: r.lit ?? [] })),
433
- ];
439
+ const duProjet = engendres.map(e => ({ ...e, cadre: false }));
440
+ const references = [...duProjet, ...duCircuit.map(r => ({ ...r, lit: r.lit ?? [] }))];
434
441
  // The files of the lot a reference writes in full, and the references the lot touches.
435
442
  const entiers = fichiers.filter(f => references.some(r => couvertPar(r.entiers, f)));
436
443
  const aRegenerer = touchesPar(references, fichiers);
@@ -482,6 +489,18 @@ function main(argv) {
482
489
  return refuser(`Le lot ${p} ne s'applique pas :\n${r.stdout}${r.stderr}`);
483
490
  }
484
491
  }
492
+ // The generated files the lots remove from the key follow the lots: main's version is not kept.
493
+ const part = partDesLots({
494
+ references,
495
+ duProjet,
496
+ entiers,
497
+ touchees: aRegenerer,
498
+ arbre: copie,
499
+ });
500
+ const suivis = poserLesRetires({ lots, fichiers: part.suivis, dansCopie });
501
+ if (suivis) {
502
+ return refuser(suivis);
503
+ }
485
504
  const divergents = avecCopie ? differents(copieTicket, lots, fichiers, tmp) : [];
486
505
  if (divergents.length) {
487
506
  return refuser(
@@ -493,10 +512,11 @@ function main(argv) {
493
512
  if (installation) {
494
513
  return refuser(installation);
495
514
  }
496
- if (aRegenerer.length) {
515
+ const aRejouer = part.rejouees;
516
+ if (aRejouer.length) {
497
517
  const env = avecLesDonnees(donnees, avecLesOutils(outils, process.env));
498
518
  const refus = regenerer({
499
- refs: aRegenerer,
519
+ refs: aRejouer,
500
520
  dansCopie,
501
521
  lancer: commande =>
502
522
  spawnSync('bash', monter('sh', '-c', commande), {
@@ -509,7 +529,7 @@ function main(argv) {
509
529
  if (refus) {
510
530
  return refuser(refus);
511
531
  }
512
- dire(`✓ références régénérées sur main à jour : ${aRegenerer.map(r => r.nom).join(', ')}`);
532
+ dire(`✓ références régénérées sur main à jour : ${aRejouer.map(r => r.nom).join(', ')}`);
513
533
  }
514
534
 
515
535
  // 6. The commit, in the copy: the commit committed is the commit the CI of the branch judges.
@@ -433,6 +433,12 @@ export function retirerALInterruption(retirer: () => void): () => void;
433
433
  export const SEUIL_PRESSION: number;
434
434
  /** The exit code of a pass « à repasser » (scripts/codes-de-sortie.mjs). */
435
435
  export const A_REPASSER: number;
436
+ /** The file a pass cut by the watch of its memory leaves in its results directory. */
437
+ export const MEMOIRE_COUPEE: string;
438
+ /** The script of the watch of the memory, which a pass runs under (scripts/garde-de-la-memoire.mjs). */
439
+ export const GARDE_DE_LA_MEMOIRE: string;
440
+ /** The variable of the workers of the tests of a task (scripts/places-de-la-machine.mjs). */
441
+ export const VARIABLE_TRAVAILLEURS: string;
436
442
  /** The file of Beads that holds the prefix of the tickets (scripts/prefixe-des-tickets.mjs). */
437
443
  export const CONFIG_BEADS: string;
438
444
  /** The prefix of the tickets, read from the key `issue-prefix`; throws when it is missing. */
@@ -456,8 +462,9 @@ export const PASSE_ROUGE: string;
456
462
  export function garderLeVert(etat: unknown): void;
457
463
  /** The measure of the repository at `racine` against its last green. */
458
464
  export function mesure(racine: string, o?: { tout?: boolean; dans?: string }): unknown;
459
- /** The workers a session of an agent plays its tests on (`GRILLHOUSE_TRAVAILLEURS` of `env`), or
460
- * null in a heavy pass (every core); refuses a value that is not a positive integer, by name. */
465
+ /** The workers a task plays its tests on (`GRILLHOUSE_TRAVAILLEURS` of `env`, which a session
466
+ * and a pass set), or null without the variable (the tool's own default); refuses a value that is
467
+ * not a positive integer, by name. */
461
468
  export function travailleursDeLaSeance(env?: NodeJS.ProcessEnv): number | null;
462
469
  /** The wait for the lock of the machine, ended without it (scripts/verrou-de-machine.mjs). */
463
470
  export class AttenteDeLaMachine extends Error {}
@@ -446,8 +446,8 @@ function jouerLesTests(racine, p, choix, options, temporaire = () => ({}), tranc
446
446
  const junit = path.join(m.workspace_root, 'target', 'nextest', PROFIL, 'junit.xml');
447
447
  const nextest = ['nextest', 'run', '--tool-config-file', `${PROFIL}:${NEXTEST}`];
448
448
  nextest.push('--profile', PROFIL, '--no-fail-fast');
449
- // The workers of a session of an agent (GRILLHOUSE_TRAVAILLEURS): `-j` of cargo and of nextest;
450
- // a heavy pass, without it, keeps every core.
449
+ // The workers of the task (GRILLHOUSE_TRAVAILLEURS, which a session and a pass set): `-j` of
450
+ // cargo and of nextest; without the variable, their own default.
451
451
  const travailleurs = travailleursDeLaSeance(process.env);
452
452
  const j = travailleurs === null ? [] : ['-j', String(travailleurs)];
453
453
  // A bench plays on one thread (`--test-threads 1`, which `-j` of nextest is the alias of): it
@@ -495,7 +495,10 @@ function jouerLesTests(racine, p, choix, options, temporaire = () => ({}), tranc
495
495
  ? [...duC, ...nommes]
496
496
  : []
497
497
  : [...nommes, ...filtreDesModules(nom, autres, modules)];
498
- const args = [...nextest, '-p', nom, ...selection, ...options];
498
+ // The day of a whole crate with no test at all is green (a crate born of its skeleton,
499
+ // its target of tests empty); a target or a module named that plays none stays an error.
500
+ const sansTest = cibles.length === 0 && !tranche ? ['--no-tests=pass'] : [];
501
+ const args = [...nextest, '-p', nom, ...selection, ...options, ...sansTest];
499
502
  prevues.push([
500
503
  p.prevoir(nom, d, 'nextest', true, args),
501
504
  { junit, temporaire: temporaire(nom) },
@@ -259,8 +259,8 @@ function jouerLesTests(p, choix, options) {
259
259
  const cache = path.join(p.racine, CACHE_DE_PYTEST, path.relative(p.racine, c.dossier));
260
260
  const args = [...UV_RUN, '--group', GROUPE, 'pytest', '-o', `cache_dir=${cache}`];
261
261
  args.push(...p.junit(c.nom, c.dossier));
262
- // The workers of a session of an agent (GRILLHOUSE_TRAVAILLEURS): `-n` of pytest-xdist, for a
263
- // package whose test group declares it; a heavy pass, without the variable, plays alone.
262
+ // The workers of the task (GRILLHOUSE_TRAVAILLEURS, which a session and a pass set): `-n` of
263
+ // pytest-xdist, for a package whose test group declares it; without the variable, one process.
264
264
  const travailleurs = travailleursDeLaSeance(process.env);
265
265
  if (travailleurs !== null && declareXdist(c.dossier)) {
266
266
  args.push('-n', String(travailleurs));
@@ -139,7 +139,7 @@
139
139
  // inherits the root's. The generator adds the variable to the `env` of the root's `test:unit`,
140
140
  // the project's entries kept, and the check refuses a `test:unit` of the root without it.
141
141
  //
142
- // Four variables pass to every task without entering any hash: the root's `globalPassThroughEnv`
142
+ // Some variables pass to every task without entering any hash: the root's `globalPassThroughEnv`
143
143
  // names them, Turborepo's strict mode of the variables keeping out of a task every variable its
144
144
  // configuration does not name. The results directory of a run (`GRILLHOUSE_RESULTATS`,
145
145
  // scripts/resultats.mjs), where the guards write their SARIF, Turborepo its summaries and Vitest
@@ -149,7 +149,9 @@
149
149
  // progress directory of a pass (`GRILLHOUSE_AVANCEMENT`, scripts/avancement.mjs), where Vitest
150
150
  // writes the files done and planned of each task, which the board reads; the temporary directory
151
151
  // (`TMPDIR`), the base of a pass (scripts/mesure/base-de-passe.mjs), where every task writes
152
- // its temporary files and which goes at the end of the pass. The generator adds each
152
+ // its temporary files and which goes at the end of the pass; the workers of the tests of a task
153
+ // (`GRILLHOUSE_TRAVAILLEURS`, scripts/places-de-la-machine.mjs), the bound a session or a pass
154
+ // sets, which the tool of each language reads. The generator adds each
153
155
  // one the root lacks, the project's entries kept, and the check refuses a
154
156
  // root without one.
155
157
  //
@@ -169,6 +171,7 @@ import {
169
171
  inscrireLePlan,
170
172
  paquetsSansPackageJson,
171
173
  TRACE,
174
+ VARIABLE_TRAVAILLEURS as TRAVAILLEURS,
172
175
  } from '../../services-du-noyau.mjs';
173
176
  import { matieres } from './consommateurs.mjs';
174
177
  import { parcourir } from './parcours.mjs';
@@ -307,7 +310,7 @@ const attenteDuTypage = racine => (paquets(racine).length ? ['build', '^build']
307
310
  // The temporary directory of a process, which names the base of its pass.
308
311
  const TEMPORAIRE = 'TMPDIR';
309
312
  // The variables the root's `globalPassThroughEnv` names, and why, as the check says it.
310
- const PASSAGES = [RESULTATS, CHANGEMENTS, AVANCEMENT, TEMPORAIRE];
313
+ const PASSAGES = [RESULTATS, CHANGEMENTS, AVANCEMENT, TEMPORAIRE, TRAVAILLEURS];
311
314
  const POURQUOI = {
312
315
  [RESULTATS]: "où les gardes, Turborepo et Vitest écrivent les résultats qu'un circuit lit",
313
316
  [CHANGEMENTS]:
@@ -316,6 +319,8 @@ const POURQUOI = {
316
319
  "le dossier d'avancement d'une passe, où Vitest écrit ses fichiers faits et prévus que lit le tableau",
317
320
  [TEMPORAIRE]:
318
321
  'la base de la passe, où chaque tâche écrit ses fichiers temporaires, effacée à sa fin',
322
+ [TRAVAILLEURS]:
323
+ "les travailleurs des tests d'une tâche, la borne que posent une séance et une passe",
319
324
  };
320
325
  // The variables of the tools of the project at <racine> (`grillhouse.outils` of its package.json,
321
326
  // scripts/outils-cles.mjs), in the order it declares them: the paths of tools outside the
@@ -44,7 +44,13 @@
44
44
  // every task whose prerequisites passed plays, and each red is named. <n>, the tasks side by
45
45
  // side, is half the cores of the machine, one at least (`concurrence`): each task of tests is
46
46
  // itself parallel (Vitest's workers), as make's `-j` and Bazel's `--local_cpu_resources` bound a
47
- // build by the machine; a `--concurrency` among the arguments replaces it.
47
+ // build by the machine; a `--concurrency` among the arguments replaces it. The workers of each
48
+ // task of tests are the cores shared between the tasks of tests side by side
49
+ // (`travailleursDeLaPasse`, GRILLHOUSE_TRAVAILLEURS): the test processes of a pass never
50
+ // outnumber the cores.
51
+ // - The run of Turborepo plays under the watch of the memory (scripts/garde-de-la-memoire.mjs): cut
52
+ // when the memory available and the free swap run out, or when the machine waits for its memory
53
+ // half of the time, the pass says why and ends at 75, « à repasser », no task judged.
48
54
  // - The pass plays no measure of time (grillhouse-bd7): the time budget benches and the time
49
55
  // witnesses (a test file that imports `mesurerAuRepos`) are out of the day, as the night tests
50
56
  // are, and the night plays them (scripts/langages/typescript/vitest-config/cibles.mjs,
@@ -106,6 +112,7 @@ import { availableParallelism, tmpdir } from 'node:os';
106
112
  import path from 'node:path';
107
113
  import { pathToFileURL } from 'node:url';
108
114
  import {
115
+ A_REPASSER,
109
116
  AttenteDeLaMachine,
110
117
  AVANCEMENT,
111
118
  avecLaMachineEtUnePlace,
@@ -115,8 +122,10 @@ import {
115
122
  garderLeRegistre,
116
123
  garderLeTotal,
117
124
  garderLeVert,
125
+ GARDE_DE_LA_MEMOIRE,
118
126
  LA_FORME,
119
127
  langageDe,
128
+ MEMOIRE_COUPEE,
120
129
  lireLaTranche,
121
130
  lireLeRegistre,
122
131
  mesure,
@@ -128,6 +137,7 @@ import {
128
137
  SCRIPT_DES_TESTS,
129
138
  TESTS_CIBLES,
130
139
  testsCibles,
140
+ VARIABLE_TRAVAILLEURS,
131
141
  } from '../../services-du-noyau.mjs';
132
142
  import { paquets, TYPAGE } from '../../paquets.mjs';
133
143
  import { RESULTATS } from '../../resultats.mjs';
@@ -152,9 +162,29 @@ const lister = dossier => (existsSync(dossier) ? readdirSync(dossier) : []);
152
162
  // The tasks a pass plays side by side on a machine of <coeurs> cores: half of them, one at least.
153
163
  const concurrence = (coeurs = availableParallelism()) => Math.max(1, Math.floor(coeurs / 2));
154
164
 
165
+ // The tasks side by side <args> ask for (`--concurrency=<n>`, `--concurrency <n>`), null without
166
+ // a whole number.
167
+ function concurrenceDemandee(args) {
168
+ const i = args.findIndex(a => CONCURRENCE.test(a));
169
+ if (i < 0) {
170
+ return null;
171
+ }
172
+ const v = args[i].includes('=') ? args[i].split('=')[1] : args[i + 1];
173
+ return /^[1-9]\d*$/.test(v ?? '') ? Number(v) : null;
174
+ }
175
+
176
+ /**
177
+ * The workers of each task of tests of a pass: the <coeurs> shared between the tasks of tests
178
+ * played side by side, at most <coteACote> and at most the <paquets> that play tests; one at least.
179
+ * @param {{ coeurs: number, coteACote: number, paquets: number }} o
180
+ * @returns {number}
181
+ */
182
+ export const travailleursDeLaPasse = ({ coeurs, coteACote, paquets: n }) =>
183
+ Math.max(1, Math.floor(coeurs / Math.max(1, Math.min(coteACote, n))));
184
+
155
185
  // The full pass in <racine>, its arguments <args> (`--gardes` among them: the guards alone), under
156
186
  // <env> and the lock of the machine; its verdict, 0 or 1, or 75 when the wait for the lock, or for
157
- // room in the temporary directory, reaches its bound. `dire` writes a line; `coeurs`, the cores of the machine.
187
+ // room in the temporary directory, reaches its bound, or when the watch of the memory cuts the run. `dire` writes a line; `coeurs`, the cores of the machine.
158
188
  export function verifier({
159
189
  racine = process.cwd(),
160
190
  args: demandes = [],
@@ -211,22 +241,24 @@ export function verifier({
211
241
  }
212
242
  }
213
243
 
214
- // Whether a package of <racine>, or its root, plays tests (a script `test:unit`).
215
- function depotAvecTests(racine) {
244
+ // The packages of <racine> that play tests (a script `test:unit`), its root for a repository
245
+ // without packages.
246
+ function paquetsAvecTests(racine) {
216
247
  const liste = paquets(racine);
217
248
  if (liste.length === 0) {
218
249
  try {
219
- return Boolean(
220
- JSON.parse(readFileSync(path.join(racine, 'package.json'), 'utf8')).scripts?.[
221
- SCRIPT_DES_TESTS
222
- ]
223
- );
250
+ return JSON.parse(readFileSync(path.join(racine, 'package.json'), 'utf8')).scripts?.[
251
+ SCRIPT_DES_TESTS
252
+ ]
253
+ ? 1
254
+ : 0;
224
255
  } catch {
225
- return false;
256
+ return 0;
226
257
  }
227
258
  }
228
- return liste.some(p => !p.hors && p.pkg.scripts?.[SCRIPT_DES_TESTS]);
259
+ return liste.filter(p => !p.hors && p.pkg.scripts?.[SCRIPT_DES_TESTS]).length;
229
260
  }
261
+ const depotAvecTests = racine => paquetsAvecTests(racine) > 0;
230
262
 
231
263
  // Whether <args> hold a filter of Turborepo (`--filter=<f>`, `--filter <f>`, `-F <f>`).
232
264
  const filtre = args => args.some(a => a.startsWith('--filter=') || a === '--filter' || a === '-F');
@@ -418,11 +450,22 @@ function jouerLaPasse({ racine, demandes, args, tout, ajouts, env, dire, coeurs,
418
450
  : tout
419
451
  ? testsCibles({ arguments: [], force: true })
420
452
  : undefined;
453
+ const borne = args.some(a => CONCURRENCE.test(a)) ? [] : [`--concurrency=${concurrence(coeurs)}`];
454
+ // The workers of each task of tests: the cores shared between those played side by side.
455
+ const travailleurs = travailleursDeLaPasse({
456
+ coeurs,
457
+ coteACote: concurrenceDemandee(args) ?? concurrence(coeurs),
458
+ paquets: paquetsAvecTests(racine),
459
+ });
421
460
  const e =
422
461
  gardesSeules || sansTests
423
462
  ? propre
424
- : { ...propre, ...ajouts, ...(cibles ? { [TESTS_CIBLES]: JSON.stringify(cibles) } : {}) };
425
- const borne = args.some(a => CONCURRENCE.test(a)) ? [] : [`--concurrency=${concurrence(coeurs)}`];
463
+ : {
464
+ ...propre,
465
+ ...ajouts,
466
+ ...(cibles ? { [TESTS_CIBLES]: JSON.stringify(cibles) } : {}),
467
+ [VARIABLE_TRAVAILLEURS]: String(travailleurs),
468
+ };
426
469
  const a = [
427
470
  ...tachesDeLaPasse(demandes, controlesDuDepot(racine)),
428
471
  '--continue=dependencies-successful',
@@ -437,11 +480,25 @@ function jouerLaPasse({ racine, demandes, args, tout, ajouts, env, dire, coeurs,
437
480
  const runs = path.join(racine, '.turbo', 'runs');
438
481
  const existait = existsSync(runs);
439
482
  const avant = new Set(lister(runs));
440
- const r = spawnSync('turbo', ['run', ...a, '--summarize'], {
441
- cwd: racine,
442
- env: e,
443
- stdio: 'inherit',
444
- });
483
+ // Under the watch of the memory, which writes in its witness why it cut the run.
484
+ const temoin = path.join(e.TMPDIR || tmpdir(), `memoire-coupee-${process.pid}`);
485
+ rmSync(temoin, { force: true });
486
+ const r = spawnSync(
487
+ process.execPath,
488
+ [GARDE_DE_LA_MEMOIRE, '--temoin', temoin, '--', 'turbo', 'run', ...a, '--summarize'],
489
+ { cwd: racine, env: e, stdio: 'inherit' }
490
+ );
491
+ if (existsSync(temoin)) {
492
+ const raison = readFileSync(temoin, 'utf8').trim();
493
+ rmSync(temoin, { force: true });
494
+ garderLesResumes(racine, avant, e);
495
+ // Said to whoever reads the results of the pass: its 75 is a cut, no wait of the machine.
496
+ if (e[RESULTATS]) {
497
+ writeFileSync(path.join(e[RESULTATS], MEMOIRE_COUPEE), `${raison}\n`);
498
+ }
499
+ dire(`⛔ ${raison}`);
500
+ return A_REPASSER;
501
+ }
445
502
  const nouveaux = lister(runs).filter(f => !avant.has(f) && f.endsWith('.json'));
446
503
  let resume = null;
447
504
  if (nouveaux.length === 1) {
@@ -173,10 +173,12 @@ export default {
173
173
  },
174
174
  };
175
175
 
176
- // The workers of a session of an agent: `maxWorkers` of Vitest is GRILLHOUSE_TRAVAILLEURS
177
- // (max(1, cores ÷ places), scripts/places-de-la-machine.mjs); without it (a heavy pass), Vitest's
178
- // own default stands: every core.
176
+ // The workers of a task: `maxWorkers` of Vitest is GRILLHOUSE_TRAVAILLEURS, which a session
177
+ // (max(1, cores ÷ places), scripts/places-de-la-machine.mjs) and a pass (the cores shared between
178
+ // its tasks of tests, ./verifier.mjs) set; without it, Vitest's own default stands: every core.
179
179
  function travailleurs() {
180
180
  const n = travailleursDeLaSeance(process.env);
181
- return n === null ? {} : { maxWorkers: n };
181
+ // Vitest's own least number of workers follows the cores of the machine, and refuses a most
182
+ // under it: the least goes with the most.
183
+ return n === null ? {} : { maxWorkers: n, minWorkers: 1 };
182
184
  }
@@ -5,6 +5,12 @@ import type { MesureDeLaMachine } from './regles-des-places.mjs';
5
5
  /** The memory available now, in bytes. */
6
6
  export function memoireDisponible(): number;
7
7
 
8
+ /** What <texte> (/proc/meminfo) says the machine still gives, in bytes. */
9
+ export function lireLaMemoire(texte: string): { disponible: number | null; echange: number };
10
+
11
+ /** What the machine still gives now: the memory available and the free swap, in bytes. */
12
+ export function memoireRestante(): { disponible: number | null; echange: number };
13
+
8
14
  /** The machine now: its cores, its load over one minute, its free memory in bytes. */
9
15
  export function mesureDeLaMachine(): MesureDeLaMachine;
10
16