@stateward/core 1.3.0 → 1.3.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.
package/dist/checker.d.ts CHANGED
@@ -1,6 +1,7 @@
1
+ import type { MemoryPlan } from "./memory-plan.js";
1
2
  import type { ResultCache } from "./cache.js";
2
3
  import type { TimingRecorder } from "./timing.js";
3
- import type { CheckProgress } from "./engine.js";
4
+ import type { CheckerSlicing, CheckProgress } from "./engine.js";
4
5
  import type { CheckResult, Config, EditorAction, EditorHint, Finding, FixForm, FixReview, FixSetReview, LibraryUse, Location, StatedGuarantee, RuleSelection, TokenType, ReportOutput, ReportPlace } from "./types.js";
5
6
  export type CheckInput = {
6
7
  config: Config;
@@ -49,6 +50,13 @@ export type SlicedCheck = {
49
50
  };
50
51
  /** The default slice: short against the editor's 200 ms budget, long against a pause's cost. */
51
52
  export declare const SLICE_MS = 20;
53
+ /** A memory budget for `createChecker` (`memory`). */
54
+ export type MemoryBudget = {
55
+ readonly mb: number;
56
+ readonly planned?: (plan: Extract<MemoryPlan, {
57
+ kind: "fits";
58
+ }>) => void;
59
+ };
52
60
  /** One config's checker: it keeps its programs between runs, so a later run only redoes what changed. */
53
61
  export type Checker = {
54
62
  /** Reuses the previous run's programs as `oldProgram`. */
@@ -139,7 +147,7 @@ export type Checker = {
139
147
  * Editor requests are answered from the programs of the last check. A plugin that throws
140
148
  * propagates the error: the language server is the boundary that logs it.
141
149
  */
142
- export declare function createChecker({ config, cwd, rules, cache, uncapped, ignores, timing, retainPrograms, }: {
150
+ export declare function createChecker({ config, cwd, rules, cache, uncapped, ignores, timing, retainPrograms, slicing, memory, }: {
143
151
  config: Config;
144
152
  cwd: string;
145
153
  rules?: RuleSelection;
@@ -163,6 +171,18 @@ export declare function createChecker({ config, cwd, rules, cache, uncapped, ign
163
171
  * programs afterwards: a later request (a fix tried, a hover) builds them again.
164
172
  */
165
173
  retainPrograms?: false;
174
+ /**
175
+ * Starts a new type checker every so many files of a project (`CheckerSlicing`). Not a config
176
+ * key: for stateward's own tests. Wins over the slicing `memory` plans.
177
+ */
178
+ slicing?: CheckerSlicing;
179
+ /**
180
+ * A memory budget each full check plans for (`memory-plan.ts`): from the size of the programs,
181
+ * before building them, how many files share one type checker. `planned` is told the plan
182
+ * before the check starts. A budget below what parsing and binding needs throws
183
+ * `MemoryBudgetError`, before anything is built.
184
+ */
185
+ memory?: MemoryBudget;
166
186
  }): Checker;
167
187
  /** One run with a fresh checker. */
168
188
  export declare function check({ config, cwd, overlays, rules, cache, uncapped, ignores, }: CheckInput): CheckResult;
package/dist/checker.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { createBackend, toTypeScriptPath } from "./backend/typescript6.js";
2
+ import { displayPath } from "./display-path.js";
3
+ import { MemoryBudgetError, planMemory } from "./memory-plan.js";
2
4
  import { emptyCache } from "./cache.js";
3
5
  import { reviewFixes, verifyFixSet } from "./fixes.js";
4
6
  import { legacyMarkerRewrite } from "./guarantee-markers.js";
5
7
  import { ledgerGuarantees } from "./ledger.js";
6
8
  import { unlistedGuarantees } from "./stated.js";
7
- import { drain, filePhaseRun, needsJsDoc, projectPhaseSteps, projectRuleIds, ruleOffAtFn, runFileRules, silentReasons, } from "./engine.js";
9
+ import { builtSources, drain, filePhaseRun, needsJsDoc, projectPhaseSteps, projectRuleIds, ruleOffAtFn, runFileRules, silentReasons, } from "./engine.js";
8
10
  /** The default slice: short against the editor's 200 ms budget, long against a pause's cost. */
9
11
  export const SLICE_MS = 20;
10
12
  function fileTotal(units) {
@@ -14,6 +16,23 @@ function fileTotal(units) {
14
16
  function pause() {
15
17
  return new Promise((resolve) => setImmediate(resolve));
16
18
  }
19
+ /**
20
+ * The slicing the budget's plan asks for (undefined when every project keeps one checker), after
21
+ * telling `planned`; throws `MemoryBudgetError` when the budget is below the plan's floor.
22
+ */
23
+ function budgetSlicing(cwd, memory, pending, keepsPrograms) {
24
+ const plan = planMemory(memory.mb, pending.map((unit) => ({ tsconfig: unit.tsconfig, size: unit.size() })), keepsPrograms);
25
+ if (plan.kind === "below-floor") {
26
+ throw new MemoryBudgetError(plan, displayPath(cwd, plan.tsconfig));
27
+ }
28
+ memory.planned?.(plan);
29
+ const perChecker = new Map(plan.projects
30
+ .filter((project) => project.slices > 1)
31
+ .map((project) => [project.tsconfig, project.filesPerChecker]));
32
+ return perChecker.size === 0
33
+ ? undefined
34
+ : { filesPerChecker: (tsconfig) => perChecker.get(tsconfig) };
35
+ }
17
36
  /** The own files by name, for editor requests; binds each program, as plugins walk the nodes. */
18
37
  function index(units) {
19
38
  for (const unit of units)
@@ -27,7 +46,7 @@ function index(units) {
27
46
  * Editor requests are answered from the programs of the last check. A plugin that throws
28
47
  * propagates the error: the language server is the boundary that logs it.
29
48
  */
30
- export function createChecker({ config, cwd, rules = { kind: "configured" }, cache = emptyCache(), uncapped, ignores, timing, retainPrograms, }) {
49
+ export function createChecker({ config, cwd, rules = { kind: "configured" }, cache = emptyCache(), uncapped, ignores, timing, retainPrograms, slicing, memory, }) {
31
50
  const backend = createBackend({
32
51
  config,
33
52
  cwd,
@@ -59,27 +78,32 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
59
78
  const started = performance.now();
60
79
  timing?.start();
61
80
  known = undefined;
81
+ const pending = backend.pending(overlays);
82
+ const keepsPrograms = retainPrograms !== false;
83
+ const planned = memory === undefined ? undefined : budgetSlicing(cwd, memory, pending, keepsPrograms);
62
84
  const opened = () => {
63
- const units = backend.open(overlays);
85
+ const units = pending.map((unit) => unit.open());
64
86
  timing?.program(performance.now() - started);
65
87
  return units;
66
88
  };
67
89
  const startFilePhase = (units) => {
68
- filePhase = filePhaseRun(config, cwd, units, rules, cache === false ? undefined : cache, ignores !== false, timing);
90
+ filePhase = filePhaseRun(config, cwd, units, rules, cache === false ? undefined : cache, ignores !== false, timing, slicing ?? planned);
69
91
  return filePhase;
70
92
  };
71
93
  let phase;
72
- if (retainPrograms === false) {
73
- // No variable holds the units here: once the file phase returns they can be collected.
94
+ if (!keepsPrograms) {
95
+ // One project at a time: the file phase builds each program when it reaches it and lets
96
+ // it go after its files, so the largest program is held, not all of them. No variable
97
+ // holds a unit here.
74
98
  lastUnits = undefined;
75
- phase = yield* startFilePhase(opened()).steps;
99
+ phase = yield* startFilePhase(pending).steps;
76
100
  backend.release();
77
101
  }
78
102
  else {
79
103
  lastUnits = opened();
80
104
  // Building the programs is a step of its own, so its cost is told apart from a rule's.
81
105
  yield { phase: "files", done: 0, total: fileTotal(lastUnits) };
82
- phase = yield* startFilePhase(lastUnits).steps;
106
+ phase = yield* startFilePhase(builtSources(lastUnits)).steps;
83
107
  }
84
108
  filePhase = undefined;
85
109
  const kept = new Map();
@@ -43,11 +43,41 @@ export declare const RESULTS_CACHE_DEFAULT_MB = 200;
43
43
  export declare function resultsCacheLimit(env: {
44
44
  STATEWARD_CACHE_MAX_MB?: string | undefined;
45
45
  }): number;
46
+ /**
47
+ * What a save did. `over-limit`: the run's own results were written whole although they pass the
48
+ * folder's limit (`bytes` against `limit`); only older results, and other projects' files, are
49
+ * dropped for the limit, never what the run wrote or used.
50
+ */
51
+ export type SaveOutcome = {
52
+ readonly kind: "unchanged";
53
+ } | {
54
+ readonly kind: "saved";
55
+ } | {
56
+ readonly kind: "over-limit";
57
+ readonly bytes: number;
58
+ readonly limit: number;
59
+ } | {
60
+ readonly kind: "failed";
61
+ readonly error: Error;
62
+ };
46
63
  export type DiskCache = {
47
64
  readonly cache: ResultCache;
48
- /** Writes the cache if it changed since it was read or last saved; a failure to write is returned, not thrown. */
49
- save(): Error | undefined;
65
+ /**
66
+ * Writes the cache if it changed since it was read or last saved; a failure is returned, not
67
+ * thrown. Once written, the journal (`keepProgress`) is folded in and removed.
68
+ */
69
+ save(): SaveOutcome;
70
+ /**
71
+ * Appends each file's results to the journal beside the cache as the check finishes them
72
+ * (journal.ts), so a run that dies keeps them for the next. A failure to open is thrown; a
73
+ * failure to write later ends the journal and is given to `onError`.
74
+ */
75
+ keepProgress(onError: (error: Error) => void): void;
76
+ /** The journal's path (`journalPath`). */
77
+ readonly journal: string;
50
78
  };
79
+ /** The journal of the results file `file`. */
80
+ export declare function journalPath(file: string): string;
51
81
  /**
52
82
  * Opens the cache of `project` (an absolute folder) in `dir`. A cache written by other code (another
53
83
  * stateward version, or another build of core or of a plugin the config loads: `implementationId`)
@@ -1,11 +1,12 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, statSync, renameSync, rmSync, rmdirSync, unlinkSync, writeSync, } from "node:fs";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, rmdirSync, unlinkSync, writeSync, } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import path from "node:path";
6
- import { END_TEXT, emptyCache, parseSnapshot, pruneUnused, snapshotChunks } from "./cache.js";
6
+ import { emptyCache, parseSnapshot, pruneUnused, snapshotChunks } from "./cache.js";
7
7
  import { cacheEntries, dropLeastRecentlyUsed, limitBytes, markUsed } from "./disk-limits.js";
8
8
  import { implementationId } from "./implementation.js";
9
+ import { openJournal, readJournal, removeJournal } from "./journal.js";
9
10
  let version;
10
11
  /** The stateward version (core's): a new release reads nothing an older one wrote. */
11
12
  export function statewardVersion() {
@@ -80,6 +81,8 @@ export function resultsCacheLimit(env) {
80
81
  }
81
82
  /** A results file of the folder: one per project (`check-<key>.json`). */
82
83
  const RESULTS_FILE = /^check-[0-9a-f]+\.json$/;
84
+ /** A journal a check keeps beside its results file (journal.ts). */
85
+ const JOURNAL_FILE = /^check-[0-9a-f]+\.journal$/;
83
86
  /** A temporary file a writer left (it died between writing and renaming). */
84
87
  const TEMPORARY_FILE = /^check-[0-9a-f]+\.json\..*\.tmp$/;
85
88
  /** Error codes of a rename that Windows refuses while another process has the target open. */
@@ -105,6 +108,10 @@ function renameWithRetry(rename, from, to, wait) {
105
108
  }
106
109
  }
107
110
  }
111
+ /** The journal of the results file `file`. */
112
+ export function journalPath(file) {
113
+ return file.replace(/\.json$/, ".journal");
114
+ }
108
115
  /**
109
116
  * Opens the cache of `project` (an absolute folder) in `dir`. A cache written by other code (another
110
117
  * stateward version, or another build of core or of a plugin the config loads: `implementationId`)
@@ -125,100 +132,94 @@ io = {}) {
125
132
  const key = createHash("sha1").update(`${project}\n${implementation}`).digest("hex").slice(0, 16);
126
133
  const file = path.join(dir, `check-${key}.json`);
127
134
  const version = statewardVersion();
128
- const cache = readCache(file, { version, implementation, project }, limit);
135
+ const cache = readCache(file, { version, implementation, project });
136
+ const owner = { version, implementation, project };
137
+ const journal = journalPath(file);
138
+ // What a run that did not finish left: newer than the file, so it wins.
139
+ const left = readJournal(journal, owner);
140
+ for (const [name, entry] of left?.entries ?? [])
141
+ cache.files.set(name, entry);
142
+ if (left !== undefined && left.entries.size > 0)
143
+ cache.changed = true;
144
+ /** Whether this cache owns the journal: it read one, or keeps one. */
145
+ let journaled = left !== undefined;
146
+ let open;
129
147
  // Used now: when the folder is over its limit, the files used longest ago go first.
130
148
  if (cache.files.size > 0)
131
149
  markUsed(file);
150
+ const head = JSON.stringify({ stateward: version, implementation, project });
151
+ const write = (to) => writeWhole(to, `${head.slice(0, -1)},"snapshot":`, snapshotChunks(cache), "}");
152
+ /** The journal's results are in the file now (or were never more than it holds): it goes. */
153
+ const settle = () => {
154
+ open?.close();
155
+ open = undefined;
156
+ if (journaled)
157
+ removeJournal(journal);
158
+ journaled = false;
159
+ };
132
160
  return {
133
161
  cache,
162
+ journal,
163
+ keepProgress(onError) {
164
+ mkdirSync(dir, { recursive: true });
165
+ open?.close();
166
+ open = openJournal(journal, owner, cache, onError);
167
+ journaled = true;
168
+ },
134
169
  save() {
135
- if (!cache.changed)
136
- return undefined;
170
+ if (!cache.changed) {
171
+ settle();
172
+ return { kind: "unchanged" };
173
+ }
137
174
  const temporary = `${file}.${String(process.pid)}.${randomBytes(4).toString("hex")}.tmp`;
138
175
  try {
139
176
  mkdirSync(dir, { recursive: true });
140
177
  pruneUnused(cache);
141
- const head = JSON.stringify({ stateward: version, implementation, project });
142
- const written = writeCapped(temporary, `${head.slice(0, -1)},"snapshot":`, snapshotChunks(cache), "}", limit);
143
- if (!written) {
144
- // Over the limit before any file's results: the old file would be stale, and a cold
145
- // run costs time, never findings.
146
- rmSync(temporary, { force: true });
147
- rmSync(file, { force: true });
148
- cache.changed = false;
149
- return undefined;
150
- }
178
+ let bytes = write(temporary);
179
+ // Over the limit: the results of rules no longer run go before any of this run's.
180
+ if (bytes > limit && pruneUnused(cache, 1))
181
+ bytes = write(temporary);
151
182
  renameWithRetry(io.rename ?? renameSync, temporary, file, io.wait ?? sleep);
152
183
  // Saved: a later save (after fixes were tried) writes only what changes after this one.
153
184
  cache.changed = false;
185
+ settle();
154
186
  pruneResults(dir, file, version, limit);
155
- return undefined;
187
+ return bytes > limit ? { kind: "over-limit", bytes, limit } : { kind: "saved" };
156
188
  }
157
189
  catch (error) {
158
190
  rmSync(temporary, { force: true });
159
- return error instanceof Error ? error : new Error(String(error));
191
+ return { kind: "failed", error: error instanceof Error ? error : new Error(String(error)) };
160
192
  }
161
193
  },
162
194
  };
163
195
  }
164
196
  /**
165
197
  * Writes `head`, the chunks and `tail` to `file`, one chunk at a time, so no string holds the
166
- * whole text. A file's results that would take the file past `limit` bytes are left out, with
167
- * every file's after them: they are checked again on the next run. False, with nothing useful
168
- * written, when the parts other than the files' results alone pass the limit.
198
+ * whole text, and returns its size in bytes. Every file's results are written: the folder's limit
199
+ * never drops what a run checked, which would check it again on every run.
169
200
  */
170
- function writeCapped(file, head, chunks, tail, limit) {
201
+ function writeWhole(file, head, chunks, tail) {
171
202
  const fd = openSync(file, "w");
172
203
  try {
173
- let bytes = 0;
174
- const write = (text) => {
175
- bytes += writeSync(fd, text);
176
- };
177
- // Room is kept for the closing text, so the file stays whole and within the limit.
178
- const tailBytes = Buffer.byteLength(tail) + Buffer.byteLength(END_TEXT);
179
- if (Buffer.byteLength(head) + tailBytes > limit)
180
- return false;
181
- write(head);
182
- let entries = 0;
183
- let full = false;
184
- for (const chunk of chunks) {
185
- if (chunk.kind === "end") {
186
- write(chunk.text);
187
- continue;
188
- }
189
- if (chunk.kind === "part") {
190
- if (bytes + Buffer.byteLength(chunk.text) + tailBytes > limit)
191
- return false;
192
- write(chunk.text);
193
- continue;
194
- }
195
- if (full)
196
- continue;
197
- const text = entries === 0 ? chunk.text : `,${chunk.text}`;
198
- if (bytes + Buffer.byteLength(text) + tailBytes > limit) {
199
- full = true;
200
- continue;
201
- }
202
- write(text);
203
- entries++;
204
- }
205
- write(tail);
206
- return true;
204
+ let bytes = writeSync(fd, head);
205
+ for (const chunk of chunks)
206
+ bytes += writeSync(fd, chunk);
207
+ return bytes + writeSync(fd, tail);
207
208
  }
208
209
  finally {
209
210
  closeSync(fd);
210
211
  }
211
212
  }
212
- function readCache(file, expected, limit) {
213
+ function readCache(file, expected) {
214
+ // Another version's file is not parsed: it may be large, and it is never used.
215
+ if (writtenBy(file) !== expected.version)
216
+ return emptyCache();
213
217
  let parsed;
214
218
  try {
215
- // A file past the limit (an older stateward wrote it) is not read: it may not fit in a string.
216
- if (statSync(file).size > limit)
217
- return emptyCache();
218
219
  parsed = JSON.parse(readFileSync(file, "utf8"));
219
220
  }
220
221
  catch {
221
- // Missing, unreadable or not JSON: a cold run.
222
+ // Missing, unreadable, not JSON, or more than one string can hold: a cold run.
222
223
  return emptyCache();
223
224
  }
224
225
  if (typeof parsed !== "object" || parsed === null)
@@ -272,7 +273,7 @@ function pruneResults(dir, file, version, limit) {
272
273
  dropLeastRecentlyUsed(current, limit, new Set([file]));
273
274
  }
274
275
  function resultsFiles(dir) {
275
- return cacheEntries(dir, (name) => RESULTS_FILE.test(name) || TEMPORARY_FILE.test(name)).filter((entry) => path.dirname(entry.file) === dir);
276
+ return cacheEntries(dir, (name) => RESULTS_FILE.test(name) || TEMPORARY_FILE.test(name) || JOURNAL_FILE.test(name)).filter((entry) => path.dirname(entry.file) === dir);
276
277
  }
277
278
  export function resultsCacheStats(dir, limit) {
278
279
  const files = resultsFiles(dir).filter((entry) => entry.file.endsWith(".json"));
package/dist/engine.d.ts CHANGED
@@ -131,7 +131,7 @@ export type FilePhase = {
131
131
  * from it, and a project rule whose summaries are all unchanged reuses its last findings; the
132
132
  * cache is then updated with this run (cache.ts). Results that include a failure are not kept.
133
133
  */
134
- export declare function runFilePhase(config: Config, cwd: string, units: readonly ProjectUnit[], selection?: RuleSelection, cache?: ResultCache, ignores?: boolean, timing?: TimingRecorder): FilePhase;
134
+ export declare function runFilePhase(config: Config, cwd: string, units: readonly UnitSource[], selection?: RuleSelection, cache?: ResultCache, ignores?: boolean, timing?: TimingRecorder): FilePhase;
135
135
  /**
136
136
  * Where a check stands at a point where it can pause: after a rule that ran on a file, after a
137
137
  * file of the file phase, after a project rule of the project phase. `file` and `rule` name what
@@ -156,8 +156,37 @@ export type PhaseRun<T> = {
156
156
  };
157
157
  /** Runs `steps` to the end, with no pause: the synchronous check. */
158
158
  export declare function drain<T>(steps: Generator<CheckProgress, T, undefined>): T;
159
+ /**
160
+ * How many own files of a project share one type checker: after that many files the project
161
+ * starts a new checker on the same parsed program (`ProjectUnit.renewChecker`), so what the old
162
+ * one computed can be collected. The slices follow the file list, so the same input gives the same
163
+ * slices.
164
+ */
165
+ export type CheckerSlicing = {
166
+ /** Files per checker in the project of `tsconfig`; undefined keeps one checker for the project. */
167
+ readonly filesPerChecker: (tsconfig: string) => number | undefined;
168
+ /**
169
+ * For tests only: the projects and their files in reverse order, to show that what a rule
170
+ * reports on a file does not depend on what the checker answered before.
171
+ */
172
+ readonly reversed?: true;
173
+ };
174
+ /**
175
+ * One project of a run, as the file phase reaches it: `open` builds its program (or hands the one
176
+ * built already), and `release` lets it go once the phase is done with its files, so a run that
177
+ * keeps no program holds one project's at a time.
178
+ */
179
+ export type UnitSource = {
180
+ readonly tsconfig: string;
181
+ /** The unit when it is built already: its files count in the progress from the start. */
182
+ readonly built?: ProjectUnit;
183
+ open(): ProjectUnit;
184
+ release(): void;
185
+ };
186
+ /** Units built already, kept after the phase (`release` lets nothing go). */
187
+ export declare function builtSources(units: readonly ProjectUnit[]): readonly UnitSource[];
159
188
  /** `runFilePhase`, one file per step. */
160
- export declare function filePhaseRun(config: Config, cwd: string, units: readonly ProjectUnit[], selection?: RuleSelection, cache?: ResultCache, ignores?: boolean, timing?: TimingRecorder): PhaseRun<FilePhase>;
189
+ export declare function filePhaseRun(config: Config, cwd: string, units: readonly UnitSource[], selection?: RuleSelection, cache?: ResultCache, ignores?: boolean, timing?: TimingRecorder, slicing?: CheckerSlicing): PhaseRun<FilePhase>;
161
190
  /** The rules' project sides: each project rule's check over the summaries, and the result. */
162
191
  export declare function runProjectPhase(config: Config, phase: FilePhase, started: number, keepSummaries?: Map<string, () => ReadonlyMap<string, Json>>, cache?: ResultCache, capped?: boolean, timing?: TimingRecorder): CheckResult;
163
192
  /**